I am creating a menu but i have come across an error an would like some help as i don't know what is wrong or how to fix it, the piece of code says i am putting an argument in but i have not entered an argument.
class menu(object):
def print_menu():
# menu options
print "Main Menu:"
print "Start"
print "Quit"
def user_menu():
# users input
menu_choice = raw_input('> ')
if menu_choice == 'start':
start()
#does nothing as of yet
elif menu_choice == 'quit':
raise SystemExit
def start():
pass
#initialising main menu
main = menu()
def start_up()
main.print_menu()
#first attempt
main.user_menu()
#second attempt
main.user_menu()
#third attempt
main.user_menu()
# start again to show the menu options
start_up()
start_up()
please help, this is the traceback error most recent call the occurs in the console when i run the script
Traceback (most recent call last):
File "Engine.py", line 38, in <module>
start_up()
File "Engine.py", line 27, in start_up
main.print_menu()
TypeError: print_menu() takes no arguments (1 given)
You forgot to add self as an argument.
So it has to look like this:
class menu(object):
def print_menu(self):
# menu options
print "Main Menu:"
print "Start"
print "Quit"
def user_menu(self):
# users input
menu_choice = raw_input('> ')
if menu_choice == 'start':
start()
#does nothing as of yet
elif menu_choice == 'quit':
raise SystemExit
Also, I am not sure if using class here is needed. If I were you, I would get rid of the menu class and use just leave those methods.
Related
I'm very new to Python and I'm struggling when it comes to saving the data that the user has entered to a json file when quitting the application. Also every time I run my code all the data inside the json file is wiped. When I enter the input to save and exit I get this error code:
Traceback (most recent call last):
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 86, in <module>
main_menu()
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 23, in main_menu
save()
File "C:\Users\User\Downloads\sit_resources\sit_resources\sit_admin_application.py", line 82, in save
patients_file.write(finallist)
io.UnsupportedOperation: not writable
Here is my code below:
import json
patients_file = open("patients.json", "r")
loaded_patients = json.load(patients_file)
def main_menu():
'''Function docstring documentation here'''
print("\nSIT Data Entry Menu")
print("==========================")
print("1: Print Patients' List\n2: Add Patient\n3: Delete Patient\n4: Exit")
print("==========================")
input1 = input("Enter your menu selection:")
if input1 == "1":
patients_list()
elif input1 == "2":
add_patient()
elif input1 == "3":
remove_patient()
elif input1 == "4":
save()
else:
print ("Please enter a valid input")
main_menu()
def patients_list():
print("\nSIT current patients:\n")
loaded_patients.sort(key=str.casefold)
for number, item in enumerate(loaded_patients, start=1):
print(number, item)
print("\nTotal number of registered patients is", len(loaded_patients))
main_menu()
def add_patient():
newpatient = input("\nEnter new Patient -> Lastname Firstname:")
print ("Do the details you have entered look correct? y/n")
confirm = input()
if confirm == "y":
loaded_patients.append(newpatient)
print ("Patient successfully added to list")
main_menu()
elif confirm == "n":
print ("Patient import cancelled")
add_patient()
else:
print ("Please enter a valid input")
add_patient()
def remove_patient():
print ("Which of the following patients would you like to remove?")
loaded_patients.sort(key=str.casefold)
for number, item in enumerate(loaded_patients, start=1):
print(number, item)
try:
removepatient = int(input("\nEnter the number of the patient you would like to remove"))
print ("Does the patient number you have entered look correct? y/n")
delconfirm = input()
if delconfirm == "y":
try:
removepatient = (removepatient - 1)
loaded_patients.pop(removepatient)
print ("Patient was successfully removed from the list")
main_menu()
except IndexError:
print("Please enter a valid input")
remove_patient()
elif delconfirm == "n":
print ("Deletion cancelled")
remove_patient()
else:
print ("Please enter a valid input")
remove_patient()
except ValueError:
print ("Please enter a valid input")
remove_patient()
def save():
open("patients.json", "w")
finallist = json.dumps(loaded_patients)
patients_file.write(finallist)
print("Patient List successfully saved")
quit()
main_menu()
I store the json file in the same directory and all it contains is a list:
["Soreback Leigh", "Neckache Annette", "Sorefoot Jo", "Kaputknee Matt", "Brokentoe Susan", "Tornligament Alex"]
If anyone could help me out and let me know what I'm doing wrong or any simpler method I could use, it would be greatly appreciated.
Thanks
Your code has several issues, including the one you're asking about.
The main thing is the overall structure: your code keeps calling functions from functions, never really returning - that can work for a very long time, but in the end it will fail, and it's not the correct way to go about this.
Take for example your main_menu() - once an option is selected, you call the function matching it, and when the work there is done, you call main_menu() again. However, a better way to do the same:
def main_menu():
choice = ''
while choice != '4':
print('some options, 4 being "save and quit"')
if choice == 1:
patients_list()
...
# no if choice == 4: save() here, we'll save at the end
save()
This way, the menu will keep getting printed when you return to it, but every function that is executed, is allowed to return and then the loop restarts, unless option 4 was entered. And since you can allow the functions to return, no need to call main_menu() at the end of them.
Your save() function has some issues: it doesn't need quit() any more, but you also didn't do anything with the file you opened. A nice way to do this in Python is to use a 'context manager', which boils down to using with, like this:
def save():
with open("patients.json", "w") as patients_file:
finallist = json.dumps(loaded_patients)
patients_file.write(finallist)
That's assuming your loaded_patients always contains all the current patients of course. Given that's what it is for, you should consider just calling it patients.
Your file only contains a list, because a list is what you are creating in those functions and a list is a valid content for a json file. If you expected a dictionary, you should construct one in the rest of the code, but from your example it's unclear what exactly you would expect that dictionary to look like.
The conventional way to load and save json:
with open('patients.json', 'r') as f:
loaded_patients = json.load(f)
with open('patients.json', 'w') as f:
json.dump(loaded_patients, f)
You are trying to write to patients_file, which you opened in read-only mode.
I'm working on a project, and I got a bit stuck. I want the user the of the program to be able to call a function. But it must be easy for the user to call it. For example
def definition():
print("This is a function")
command = input("> ")
if command == definition:
definition()
else:
print("")
in this function I want the user not to write the () in the input. But I want the user just to be able to write 'definition' to call the function. Does anyone have any clue how to do this?
You are missing the quotes from around definition, therefore trying to compare an undeclared variable with an inputted string which will always equate to false.
Try:
def definition():
print("This is a function")
command = input("> ")
if command == 'definition':
definition()
else:
print("")
You are mixing up the function name (callable object in you code) and the name from your input.
For your problem I would use a dictionary of function names for the keys and function references for the value
def function1():
print ('calling function1')
def function2():
print ('calling function2')
def function3():
print ('calling function3')
functions = {}
functions['function1'] = function1
functions['function2'] = function2
functions['function3'] = function3
name = input('Enter the function name:\n')
if name in functions:
functions[name]()
else:
print ('Invalid function name. Use one of: ')
for key in functions.keys():
print (' - ' + key)
Just one command "definition"
def definition():
print("This is a function")
command = input("> ")
if command == "definition":
definition()
else:
print("Wrong command !")
More commands and functions
def definition():
print("This is definition function")
def modify():
print("This is modify function")
func = {"definition":definition, "modify":modify}
command = input("> ").strip().lower()
if command in func:
func[command]()
else:
print("Wrong command !")
You will have to implicitly define the conditions with if statement..
For ease of user you can do like this:
def definition():
#your function here
if __name__=='__main__':
print ("Choose your option:\n1. Definition")
choice = int(input("Enter choice: "))
if choice == 1:
definition ()
Try this
whitelist_funcs = ['definition', 'something else']
command = input("> ")
if command in whitelist_funcs:
exec(f"{command}()")
else:
print("")
I am struggling to access the list created by using .readlines() when opening the text file. The file opens correctly, but I am not sure how I can access the list in the function 'display_clues()'.
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clues_open()
print(clue_list)
Error:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
display_clues()
File "N:\Personal Projecs\game\game.py", line 35, in display_clues
print(clue_list)
NameError: name 'clue_list' is not defined
Thanks!
def clues_open():
try:
cluesfile = open("clues.txt","r")
clue_list = cluesfile.readlines()
#print clue_list #either print the list here
return clue_list # or return the list
except:
print("Oops! Something went wrong (Error Code 3)")
exit()
def display_clues():
clues_yes_or_no = raw_input("Would you like to see the clues? Enter Y/N: ")
clues_yes_or_no = clues_yes_or_no.lower()
if clues_yes_or_no == "y":
clue_list = clues_open() # catch list here
print clue_list
display_clues()
You have to return the list from clues_open() to display_clues():
def clues_open():
with open("clues.txt","r") as cluesfile:
return cluesfile.readlines()
def display_clues():
clues_yes_or_no = input("Would you like to see the clues? Enter Y/N: ")
if clues_yes_or_no.lower() == "y":
clues_list = clues_open()
print(clue_list)
As a side note: I removed your worse than useless except block. Never use a bare except clause, never assume what actually went wrong, and only catch exception you can really handle.
Easy one for you guys. Why can't I get cmd to run a function from a dictionary? (I didn't want to paste all the code, but everything called has a class or function somewhere else. I have functions called "help()" and "exit() and such in a commands.py file and it's already been imported.)
The error I'm getting is: "line 87, in runCMD Commands[cmd](Player, args) KeyError: 0"
Commands = { #In-game commands
'help': help,
'stats': stats,
'exit': exit
}
def isValidCMD(cmd):
if cmd in Commands:
return True
return False
def runCMD(cmd, Player, args):
Commands[cmd](Player, args)
def main(Player): #Main function
Player.dead = False
while(Player.dead == False):
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(0, 1, Player)
else:
print("Please enter a valid command.")
charactercreation()
main(Player)
You should be calling
runCMD(cmd, 1, Player) # or runCMD(cmd, Player, 1) <= looks like they are in the wrong order
anyway, they first parameter of runCMD needs to be one of the keys in Commands
Possibly you mean to pass an arbitrary number of parameters in args. then you need to place a * in there
def runCMD(cmd, Player, *args):
Commands[cmd](Player, *args)
def main(Player): #Main function
Player.dead = False
while(Player.dead == False):
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd, Player, 0, 1)
else:
print("Please enter a valid command.")
I'm very new to programming (so sorry if I don't present this problem right).
This is from LPTHW Exercise 36:
My Error:
Traceback (most recent call last):
File "ex36.py", line 329, in <module>
start()
File "ex36.py", line 149, in start
arena()
File "ex36.py", line 161, in arena
if stealth == True:
NameError: global name 'stealth' is not defined
My Assumption:
I thought 'stealth' was defined in the previous function, start(), but the definition didn't carry over to arena(). How do I fix it, and why doesn't 'stealth' from 1 function carry over to another function?
My Code (text-based game in progress):
from sys import argv
script, enemy = argv
...
def start():
print """ Choose a skill to train in
"""
stealth = False
gun = False
knife = False
heal = False
skill = raw_input("> ")
if 'gun' in skill:
print """
"""
gun = True
skill = gun
...
else:
dead()
arena()
def arena():
print """ You enter the arena. Will you:
hide, hunt for food, or search for water?
"""
path = raw_input("> ")
if "hide" in path:
print """ Hide
"""
if stealth == True:
print """ Witness
"""
witness()
else:
battle()
...
else:
print """ Dead
"""
dead()
start()
All advice is greatly appreciated. Thank you for your help.
Variables defined locally in one function have local scope and are not automatically accessible within another, disjunct function. You might want to consider passing stealth to arena when called from start, e.g. arena(stealth), and then stealth would be defined as a parameter of arena, i.e.
def arena(stealth):