Return to main function in python - python-3.x

Working on Python 3.4.3
Let's say I have created three fuctions:
def choosing(mylist=[]):
print("We will have to make a list of choices")
appending(mylist)
done = False
while(done == "False"):
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(mylist)))
done = True
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
appending(mylist)
done = False
elif(action == "Delete"):
removing(mylist)
done = False
def appending(mylist1 = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
mylist1.append(c)
print("You have inserted {} choices".format(len(mylist1)))
print("Please verify them below: ")
for x in range(0, len(mylist1)):
print(mylist1[x])
def removing(mylist2 = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
mylist2.remove(r)
print("{} successfully removed!".format(r))
Now problem is I can't just call choices() in append or remove function as choices() function will call append again and again infinitely.
So how do I get back in choices after appending or removing data in list?

As suggested by tobias_k, you should add the contents of choices() into a while loop.
I also found
some other problems:
False does not equal "False", so your while loop never runs.
You use terms like mylist, mylist1, and mylist2 - it's better to rename these to choosing_list, appending_list, and removing_list, so it's clearer.
You also shouldn't use False to define a while loop - instead, make a variable, then set it to True. When you have to stop, set it to False.
Here is the code with those problems fixed:
def appending(appending_list = []):
print("Please type EOF when you want to stop!")
while True:
c = input("Please enter EOF to stop adding. Please enter a choice: ")
if(c=="EOF"):
break
else:
appending_list.append(c)
print("You have inserted {} choices".format(len(appending_list)))
print("Please verify them below: ")
for x in range(0, len(appending_list)):
print(appending_list[x])
return appending_list
def removing(removing_list = []):
print("Following are choices: ")
r = input("What do you want to remove? ")
removing_list.remove(r)
print("{} successfully removed!".format(r))
return removing_list
print("We will have to make a list of choices")
choosing_list = appending()
list_incomplete = True
while list_incomplete:
confirm = input("Is your list complete?[Y/N]")
if(confirm == "Y"):
print("Yaay! Choices creation complete."
"{} choices have been added successfully".format(len(choosing_list)))
list_incomplete = False
elif(confirm == "N"):
action = input("What do you want to do? [Append/Delete]")
if(action == "Append"):
choosing_list = appending(choosing_list)
elif(action == "Delete"):
choosing_list = removing(choosing_list)
Let me know if there's any problems with this code.

Related

python simple help (NameError: name is not defined)

Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.

create lists with different index in python

I am trying to create a list using a loop, but I want the group to have the same index. Using append, it merges them together. What am I doing wrong?
L=[]
l=[]
def information():
i=0
while i <= 3:
if i==0:
first_name = str(input('First Name : '))
l.append(first_name)
i += 1
elif i==1:
last_name = str(input('Second Name : '))
l.append(last_name)
i += 2
elif i > 2:
wish = str(input('If you wish to continue Press Y/y or Press N/n:'))
if wish == 'y' or wish == 'Y':
L.append(l)
start()
elif wish != 'y' or wish != 'Y':
break
def start():
information()
start()
print('l', l)
print('L ', L)
My desired output is:
[['sachin', 'tendulkar'],['sachin', 'tendulkar'],['sachin', 'tendulkar']]
and I am getting this instead:
['sachin', 'tendulkar','sachin', 'tendulkar']
A little different than what you had going but this might work
Names = []
def information():
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
while ((wish == 'y') or (wish == 'Y')):
fname = str(input('First Name: '))
lname = str(input('Last Name: '))
Names.append([fname, lname])
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
information()
print (Names)

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

A permanent list change(Save python file)

I am a noob in python and i need help.I have made a phonebook where you can add the contacts.But the problem is that when i exit the program the changes to the list are not saved.I want the user to be able to make permanent changes to the list.I have seen posts about a file=open("something",'w') code to do this(I think) but i dont know where to insert this code and i dont really understand what it is.Could someone help me understand what this is about..Here is the full code:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
I appreciate the help.
When you choose to add a contact, it does properly add the name and number to the list. But, that is it.
When you re-run the program, the list gets re-assigned due to the first 2 lines of your code:
name = ["ranga","hari"]
number = [9895497777,9]
So, you won't see the last changes.
This is where you should maintain a file which lives outside the scope of your code, rather than a list.
You can modify your add function like this:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
Note: You would also need to change the other functions search and remove to read and write from the file. I've just given you a taste of how things are done. You need to modify your code and make it work.
Let me know if it helps.
I took your advice and made a new text file but i still did not know how to do it but after reading ur answers i understood and at last i came to this..
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
Now the problem seems to be the remove function..if i try to remove a line with \n at the end of it then it wont work while the opp. seems to work.Any guess what i am doing here?
And thanks for the help Mayank porwal
At the first you should know name = ["ranga","hari"], number = [9895497777,9] that you have defined are in the code and you can not change those value, and after exit() they will reset to default value.
you should use of file (for example .txt file) in this issue:
1. you must create a .txt file in your project (for example Contacts.txt)
2. and write your information in there (for example in first line: Kourosh +98938....)
3. at the first step in your program you must read Contact.txt and load it in a structure like a list or dictionary (for example
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4.now you can edit, add, remove structure.
5.and finally you can write structure in the file, before exit()
for example:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed

Ignoring quotes while sorting lists in Python?

I am making a program to read from a file, alphabetize the info, and paste it into an output.. The only issue I am having is in the information that begins with quotes ("").
The main function for the program is to auto-sort MLA works cited pages (for fun obviously).
Here is the code... I would love any criticism, suggestions, opinions (Please keep in mind this is my first functioning program)
TL;DR -- How to ignore " 's and still alphabetize the data based on the next characters..
Code:
import os, sys
#List for text
mainlist = []
manlist = []
#Definitions
def fileread():
with open("input.txt", "r+") as f:
for newline in f:
str = newline.replace('\n', '')
#print(str)
manlist.append(str)
mansort(manlist)
#print("Debug")
#print(manlist)
def main():
print("Input Data(Type 'Done' When Complete or Type 'Manual' For file-read):")
x = input()
if x.lower() == 'done':
sort(mainlist)
elif x == '':
print("You must type something!")
main()
elif x.lower() == 'manual':
fileread()
else:
mainlist.append(x)
main()
def mansort(manlist):
print("What would you like to name the file?(Exit to Terminate):")
filename = input()
manlist = sorted(manlist, key=str.lower)
for s in manlist:
finalstring2 = '\n'.join(str(manlist) for manlist in manlist)
if filename == '':
print("You must choose a name!")
elif filename.lower() == 'exit':
sys.exit()
else:
with open(filename + ".txt", "w+") as f:
f.write(str(finalstring2))
def sort(mainlist):
os.system("cls")
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?(Exit to Terminate):")
filename = input()
if filename.lower() == 'exit':
sys.exit()
elif filename == '':
print("You must type something!")
sort(mainlist)
else:
with open(filename + ".txt", "w+") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
Please keep all criticism constructive... Also, just as an example, I want "beta" to come after alpha, but with my current program, it will come first due to "" 's
sorted(mainlist, key=str.lower)
You've already figured out that you can perform some transformation on each item on mainlist, and sort by that "mapped" value. This technique is sometimes known as a Schwartzian Transform.
Just go one step further - remove the quotes and convert it to lower case.
sorted(mainlist, key=lambda s: s.strip('"').lower())

Resources