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("")
Related
class Calculator:
def get_input(self, get = input("Expression here press q to exit: ")):
pass
def compute(self, res):
pass
def display(self):
pass
calc = Calculator()
while calc.get_input() != "q":
calc.get_input()
calc.display()
exit()
This is calculator like i just remove its data because of review issues here so much code
but the input must be example: 435+422
you must include the operation in input like that, this is done so my problem now is
i dont know how to loop it.
the out put must be
-enter expression or "q" to exit : 2+2
-enter expression or "q" to exit : 1+2
-enter expression or "q" to exit : q
-bye exit
i dont knooow
Try
class Calculator:
def get_input(self):
user_input = input("Expression here press q to exit: ")
return user_input
Instead of invoking input in arguments
The problem is that your get_input doesn't return anything. So calc.get_input() allways evaluates to None
Try:
class Calculator:
def get_input(self):
return input("Expression here press q to exit: ")
def compute(self, res):
pass
def display(self):
pass
calc = Calculator()
while calc.get_input() != "q":
calc.get_input()
calc.display()
exit()
This question already has answers here:
Python: Name resolution; order of function def's
(5 answers)
Closed 5 years ago.
I'm not sure how to fix my code, could someone help!
It prints this --> "NameError: free variable 'info' referenced before assignment in enclosing scope", I don't know how to make info a global variable, i think that is the problem...Someone please help!
import time
import random
admincode = ["26725","79124","18042","17340"]
stulogin = ["NikWad","StanBan","ChrPang","JaiPat","JusChan","AkibSidd","VijSam"]
teachercode = ["KGV"]
def main():
def accesscontrol():
global teachercode, stulogin, admincode
print("Enter: Student,Teacher or Admin")
option = input("--> ")
if option == "Student":
info()
elif option == "Teacher":
print("Enter you teacher code(xxx)")
option = input
if option == teachercode:
print("Access Granted")
info()
else:
print("Please input the correct code!")
accesscontrol()
elif option == "Admin":
print("Enter your admin code(xxxxx)")
option = input("--> ")
if option == admincode:
print("access granted, my master!")
else:
accesscontrol()
accesscontrol()
def info():
print("Hello, enter your information below")
usname = input("Username: ")
pwname = input("Password: ")
done = False
while not done:
print("Is this the information correct?[Y/N]")
option = input("--> ")
if option == "Y":
print("Information saved")
print("Username :",usname,"\nPassword:",pwname)
done = True
else:
main()
return info()
info()
main()
The problem is that you define accesscontrol and info as local names relative to main. So when you call info inside accesscontrol it can't find it, because it's a name "owned" by in other words local to main.
Instead of having the functions like this:
def main():
def accesscontrol():
# ...
def info():
# ...
# ...
Move them out of main() like this:
def accesscontrol():
# ...
def info():
# ...
def main():
# ...
Thus keeping main() as simply:
def main():
accesscontrol()
info()
You need to define info() before it is called. Also you had an unnecessary call to info(), which I removed.
import time
import random
admincode = ["26725", "79124", "18042", "17340"]
stulogin = ["NikWad", "StanBan", "ChrPang", "JaiPat", "JusChan", "AkibSidd", "VijSam"]
teachercode = ["KGV"]
def main():
def info():
print("Hello, enter your information below")
usname = input("Username: ")
pwname = input("Password: ")
done = False
while not done:
print("Is this the information correct?[Y/N]")
option = input("--> ")
if option == "Y":
print("Information saved")
print("Username :", usname, "\nPassword:", pwname)
done = True
else:
main()
return info()
def accesscontrol():
global teachercode, stulogin, admincode
print("Enter: Student,Teacher or Admin")
option = input("--> ")
if option == "Student":
info()
elif option == "Teacher":
print("Enter you teacher code(xxx)")
option = input
if option == teachercode:
print("Access Granted")
info()
else:
print("Please input the correct code!")
accesscontrol()
elif option == "Admin":
print("Enter your admin code(xxxxx)")
option = input("--> ")
if option == admincode:
print("access granted, my master!")
else:
accesscontrol()
accesscontrol()
main()
In my python program, I have multiple functions defined, then a main function that also holds the menu. The menu is the first thing that should be displayed, but the program is attempting to run the defined functions that are before the main function, first. This is resulting in many problems. Any suggestions.
#!usr/bin/env python
import operator
saved_string = ''
def remove_letter():
return
def num_compare():
return
def print_string():
print saved_string
return
def calculator():
sign_dict = {"+": operator.add(), "-": operator.sub(), "*": operator.mul(), "&": operator.div()}
num1 = int(raw_input("First number: "))
sign = str(raw_input("Action: "))
num2 = int(raw_input("Second number: "))
print sign_dict[sign] (num1, num2)
return
def accept_store():
global saved_string
saved_string = str(raw_input("Enter string: "))
return
def main():
opt_list = [accept_store(),
calculator(),
print_string(),
num_compare(),
remove_letter()]
while(True):
print "SELLECT OPTIONS:"
print "1\tAccept and Store"
print "2\tCalculator"
print "3\tPrint String"
print "4\tNumber Compare"
print "5\tRemove Letter"
opt_choice = int(raw_input("SELLECTION: "))
opt_choice -= 1
opt_list[opt_choice]()
return
main()
() is a function call notation. So in opt_list, you're listing all the function calls, not the function names. You'd have to change it to:
opt_list = [fn1, fn2, ...]
Then call each function like:
for f in opt_list:
f()
i will try to explain my situation with examples:
Im using global to declare a variable but this work only in a function, when i try to another sub function doesnt work.
register.py
def main():
alprint = input("Enter something: ")
if alprint == "a":
def alCheck():
global CheckDot
CheckDot = input("Enter your opinion: ")
def alTest():
global CheckTest
CheckTest = input("Hope it works: ")
alCheck()
alTest()
main()
and content.py
from register import CheckTest
if CheckTest == "ad":
print("You are welcome!")
When i declare this variable checkTest in a sub function(function, alTest()) of main, using global and importing to another file, it doesnt work, i tried a lot of things, but nothing.
It would work, except that if the user enters something other than a for the first input, CheckTest is not defined, so it gives an ImportError. You might want to try something like this instead:
def main():
global CheckTest, CheckDot
def alCheck():
global CheckDot
CheckDot = input("Enter your opinion: ")
def alTest():
global CheckTest
CheckTest = input("Hope it works: ")
alprint = input("Enter something: ")
if alprint == "a":
alCheck()
alTest()
else:
CheckTest = None
CheckDot = None
main()
This way, CheckTest, and CheckDot are always defined.
import os
name = input("Please enter your username ") or "name"
server = input("Please enter a name you wish to call this server ") or "server"
prompt = name + "#" + server
def error(choice):
print(choice + ": command not found")
commands()
def clear():
os.system("cls")
commands()
def commands():
while 1 > 0:
choice = input(prompt)
{'clear': clear}.get(choice, error(choice))()
commands()
When running this code, no matter what I enter the dictionaries .get function always returns an error. When I enter 'clear' the script should go to that function. Does anyone have an idea why this does not work correctly? Thanks.
You'll always see the error, because all arguments to a function must be evaluated before the function is called. So error(choice) will be called to get its result before it is passed as the default value to get().
Instead, leave out the default, and check it explicitly:
result = {'clear': clear}.get(choice)
if result:
result()
else:
error(choice)
You don't want to actually call error(choice).
You can partially apply parameters to a function but leave it to be called later:
>>> def error(choice):
... print(choice + ': command not found')
>>> from functools import partial
>>> func = partial(error, choice='asdf')
>>> func()
asdf: command not found
So you want:
{'clear': clear}.get(choice, partial(error, choice))()