I have this long python code and I'm having trouble finishing or fixing it and I need help.
First I have these codes -
This will just display the menus and i have created several def functions. One is for creating data and saving to the txt file, and the other is to use a hash function to split the name. Contact info as data is created in the txt file. Finally, in a while loop I have to somehow call up the menu codes and this is where I get stuck, or I may need to fix the whole thing. Also when I put a phone number in like 555-5555, it makes an error. How would I input a number like this value?
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
menu()
choice = int(input("What would you like to do?: "))
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number))
foo.close()
def contact():
data = open("foo.txt")
file = {}
for person in data:
(Id, number) = person.split()
file[number] = Id
data.close()
while choice !=3:
if choice == 1:
print(data())
if choice ==2:
print(data())
menu()
choice = int(input("What would you like to do?: "))
It seems that the program never stops and I have to use option 3 from the menu to exit the program.
Phone number like 555-5555 is not valid integer number so keep it as a text.
Inside menu() you call menu() which call menu(), etc. It is recursion. When you choose 3 you leave last menu() and return to previous menu().
EDIT:
btw: you have to add "\n" in write
def menu():
print("Contact List Menu:\n")
print("1. Add a Contact")
print("2. Display Contacts")
print("3. Exit\n")
def data():
foo = open("foo.txt", "a+")
name = input("enter name: ")
number = int(input("enter the number: "))
foo.write(name + " " + str(number) + "\n") # new line
foo.close()
def contact():
data = open("foo.txt")
for person in data:
name, number = person.split()
print(name, number)
data.close()
#----------------
menu()
choice = int(input("What would you like to do?: "))
while choice !=3:
if choice == 1:
data()
if choice == 2:
contact()
menu()
choice = int(input("What would you like to do?: "))
Related
Just starting out with python functions (fun_movies in functions.py) and I can't seem to get out (via "no" or False) once in the loop:
main_menu.py
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
#try:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
functions.py
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
return movies
Code works fine when not called via import. When called via import (in main_menu.py), it keeps asking for infinite movies even when I input a "no". I can't find a way to exit the loop. Initially I had a "pass" but that didn't work.
Thanks in advance!
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies [name] = [genre]
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = [genre]
movies.update(movies_if)
elif query == "no":
a = False
else:
print ("Wrong input!")
return movies
A few things:
Firstly, you don't need a==True as this statement returns True when a is True and False when a is False, so we can just use a as the condition.
Secondly, only use the input at the start of the loop as you want to ask once per iteration
Thirdly, place your return outside the loop so you only return when a==False and you don't want to input another movie.
edit:
main file>
from functions import *
def menu():
print("Press 1 for movies.")
print("Press 2 to exit.")
menu()
option = int(input("Input a number: "))
while option != 0:
if option == 1:
fun_movies()
elif option == 2:
print("Goodbye! ")
break
else:
print ("Wrong input")
option = int(input("Input a number"))
global movies
movies = {}
def fun_movies():
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies[name]= genre
a = True
while a:
query = input("Do you want to input another movie? (yes/no) ")
if query == "yes":
name = input("Insert movie name: ")
genre = input("Input genre: ")
movies_if = {}
movies_if [name] = genre
movies.update(movies_if)
elif query == "no":
break
else:
print ("Wrong input!")
# continue
return movies
print(fun_movies())
Hope It works for you!
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
Hi, I am trying to create a vocabulary test on python. My code works up until this chunk. After the program prompts the user for their guess, the program will say it is incorrect even if it is the right answer. Is there an error in this code? How can I get around this?
This is what it looks like:
English: white
Spanish: blanco
Incorrect
English: purple
Spanish: morado
Incorrect
Thanks!
Full Code:
def main():
import random
wrongAnswers = []
print("Hello, Welcome to the Spanish-English vocabulary test.")
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")
print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk
while True: #SK
selection = input("Insert your selection: ").lower() #user inputs selection #sk
if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
print("You have chosen", selection, "to be tested on.")
break
if False:
print("try again.")
selection = input("Insert your selection: ").lower()
break
file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.rstrip("\n").split(",")
key, values = items[0], items[1:]
dictionary[key] = values
length = len(dictionary)
print(length,'entries found')
n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
if len(wrongAnswers) > 0:
wrong = str(wrongAnswers)
output = input("Please name the file you would like you wrong answers to be saved in: ")
outf = open(output, 'w')
outf.write(wrong)
outf.close()
else:
print("You got all of the problems correct!")
main()
In class we have to create a save/load function utilizing the split() method for a class and dictionary. I managed to get the save function working, but the load function does not seem to want to work for me. I either get it almost working but the saved file does not load, or i get the error
"playerclass" has no "player" attribute. needs to use the init method. Here is the code in its entirety def loaddata(): is mainly the area of concern.
class playerclass:
name = ""
phone = ""
jersey = ""
def __init__(self, name, phone, jersey):
self.name = name
self.phone = phone
self.jersey = jersey
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setjersey(self, jersey):
self.jersey = jersey
def getname(self):
return self.name
def getphone(self):
return self.phone
def getjersey(self):
return self.jersey
def disroster(self):
print("Player Bio")
print("-----------")
print("Name: ", self.name)
print("Phone #: ", self.phone)
print("Jersey #: ", self.jersey)
def savedata (players):
filename = input("Enter file name: ")
print("Saving....")
outFile = open(filename, "wt")
for x in players.keys():
name = players[x].getname()
phone = str(players[x].getphone())
jersey = str(players[x].getjersey())
outFile.write(name+","+phone+","+jersey+"\n")
print("Save Complete")
outFile.close()
def loaddata ():
players = {}
filename =input("Enter filename to load: ")
inFile = open(filename, "rt")
print("Loading.....")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine [:-1]
name, phone, jersey = inLine.split(",")
players[name] = playerclass(name, phone, jersey)
print("Load Successfull.")
inFile.close()
return players
def roster(players):
if len(players) == 0:
print("No players on roster: ")
else:
for x in players.keys():
players[x].disroster()
def add_player (players):
newName=input("Enter name of player to add: ")
newPhone = int(input("Enter phone number of player: "))
newJersey = int(input("Enter number of assigned jersey: "))
players[newName]= playerclass(newName, newPhone, newJersey)
return players
def ed_player (players):
oldName = input("Enter players name to edit: ")
if oldName in players:
newName = input("Enter new name for player: ")
newPhone = int(input("Enter new phone number for player: "))
newJersey = int(input("Enter newly assigned jersey number: "))
players[oldName] = playerclass(newName, newPhone, newJersey)
return players
def del_player(players):
delName = input("Enter players name to delete from roster: ")
if delName in players:
del players[delName]
return players
def displayMenu():
print("-------Main Menu-------")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
return input("Menu Choice: ")
print("Team Management Tools.")
players = {}
menu_choice = displayMenu()
while menu_choice != '9':
if menu_choice == '1':
roster(players)
elif menu_choice == '2':
players = add_player (players)
elif menu_choice == '3':
players = del_player (players)
elif menu_choice == '4':
players = ed_player (players)
elif menu_choice == '5':
savedata (players)
elif menu_choice == '6':
loaddata ()
menu_choice = displayMenu()
print("Updating roster Goodbye:")
Remove players = {} from your loaddata function, and it'll load properly.
If you actually want to reset the contents of the dictionary when loading (which might have been your intent, although I would say that's a questionable design decision), you can do:
def loaddata():
global players
players = {}
...
This is because any variables you write to are assumed to be local variables (as in, local to the function) unless you say otherwise.
I might be overlooking something, but I'm not seeing anything that attempts to read a player attribute from any object, so I'm not sure where the error is coming from. Was it from a different version of this code? Or, if it is the posted version that has that error, can you provide exactly what series of inputs lead to the error?
The rest of this answer isn't directly relevant to your question, just some tips based on things I noticed in your code.
I would remove the:
name = ""
phone = ""
jersey = ""
Because you set them in __init__ and so they're redundant and not doing anything. For looping over lines in files, you can use a for loop, which is more readable than while loops. Example:
for line in infile:
print(line)
And you should look into with. It's another type of block, and they're very useful when working with files because they'll automatically close the file when the block ends, so you don't have to. As an example:
with open("foo", "r") as stream:
for line in stream:
print(line)
# stream got implicitly closed because the block ended
I want to set a limit to which the user can input names. This is where I got to and got stuck. How would I set a limit of 10 to the names the user can input into the list and restrict them from entering anymore?
names = []
print ('1 = Add Name ')
print ('2 = Display List ')
print ('3 = Quit ')
while True:
option = input('What would you like to do: ')
if option == '1':
name= input('Enter name: ')
names.append(name)
you can do :
if option == '1':
names = [input('Enter name:') for _ in range(10)]
I hope that following script can help you:
# libraries
import sys
# list variable to store name
names = []
# limits to save name
limit = 10
# function to display menu
def menu():
print("Enter 1 to add Name")
print("Enter 2 to show list")
print("Enter 3 to quit")
choice = int(raw_input("Enter your choice : "))
return choice
# running for infinite times till user quits
while(True):
choice = menu()
if(choice == 1):
name = raw_input("Enter name to add in list : ")
if(len(names) > 10):
print("You cannot enter more names")
else:
names.append(name)
print(name + " - Name saved successfully.")
if(choice == 2):
print("List of names : ")
print(names)
if(choice == 3):
sys.exit()
Code:
students = []
choice = None
while choice != 0:
print(
"""
0 - Exit
1 - Show all students
2 - Add a student
"""
)
choice = input("Choice: ")
print()
if choice == "0":
print("Goodbye")
break
elif choice == "1":
print("\nStudents: ")
for entry in students:
email, name, number = entry
print(name, "\t", email, "\t", number)
elif choice == "2":
name = input("What is the students name?")
email = input("What is the students email adress? ")
number = int(input("What is the students number? ")
entry = email, name, number
students.append(info)
students.sort(reverse=False)
student = students
else:
print("Sorry, but", choice, "isn't a valid choice.")
When I run this in the compiler, I get a syntax error for the line
entry = email, name, number
I don't know why, please tell me.
You have a missing ) on the line immediately above the line of the error.
number = int(input("What is the students number? ") #here
entry = email, name, number
In general, missing parentheses cause the stack trace to point to the line immediately following.