Global variables in multiples functions in Python - python

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.

Related

call a 'def' with an 'input' in Python

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("")

NameError: name 'useraction' is not defined

I made sure to have global before main(), and I did assign a value to the variable useraction. Why does it still say it's undefined?
import os.path
from os import path
shoppinglist = []
global useraction
def main():
Displaylist()
RunItemAction()
def Displaylist():
i = 0
if (len(shoppinglist)>0):
while (i<=len(shoppinglist)):
print(shoppinglist[i] +"\n")
i+=1
useraction = str(input("Do you want to add, remove, or search for an item? "))
useraction = useraction.upper()
def RunItemAction():
if( useraction == "ADD"):
AddItem()
I think you should use it like this.
import os.path
from os import path
shoppinglist = []
useraction="" # or any default value you want to give
def main():
Displaylist()
RunItemAction()
def Displaylist():
global useraction
i = 0
if (len(shoppinglist)>0):
while (i<=len(shoppinglist)):
print(shoppinglist[i] +"\n")
i+=1
useraction = str(input("Do you want to add, remove, or search for an item? "))
useraction = useraction.upper()
def RunItemAction():
global useraction
if( useraction == "ADD"):
AddItem()
Any name defined at the global scope is, by definition, global.
The global statement is used in another scope to mark a name that would otherwise be local as global.
import os.path
from os import path
shoppinglist = []
def main():
Displaylist()
RunItemAction()
def Displaylist():
global useraction
i = 0
if (len(shoppinglist)>0):
while (i<=len(shoppinglist)):
print(shoppinglist[i] +"\n")
i+=1
useraction = str(input("Do you want to add, remove, or search for an item? "))
useraction = useraction.upper()
def RunItemAction():
global useraction
if( useraction == "ADD"):
AddItem()
That said, don't use a global variable at all. Pass arguments to functions, and make them return values.

Changing the value of variables in a class through a function outside the class in python

I am trying to modify the value of a variable (in this case an integer) that is located inside of a class using a function that's outside of that class. But when I call the function, the value of the variable us_balance stays the same: 42.
class Country:
us_balance = 42
def buy(country, amount):
if country.lower == "us":
Country.us_balance = Country.us_balance - amount
def stats():
print(Country.us_balance)
while True:
user_input = input("> ").lower()
if user_input == "buy":
amount = input("$ ").lower()
balance_to_set = amount.split()
buy(balance_to_set[0], int(balance_to_set[1]))
if user_input == "stats":
stats()
break
Any ideas on how to fix this?
You should create an instance of the class and pass that in to the various functions. By using Country it is creating a new instance of the class each time and that is why the stats function is reporting 42 as the value.
Here's a example that should work for you.
class Country:
us_balance = 42
def buy(ci, country, amount):
if country.lower() == "us":
new = ci.us_balance = ci.us_balance - amount
ci.us_balance = new
def stats(ci):
print(ci.us_balance)
# Create an instance of the class
ci = Country()
while True:
user_input = input("> ").lower()
if user_input == "buy":
amount = input("$ ").lower()
balance_to_set = amount.split()
buy(ci, balance_to_set[0], int(balance_to_set[1]))
if user_input == "stats":
stats(ci)
break
All I had to do was just add parentheses to the .upper() function in the class

Why Can't I break out of the loop?

Python beginner here. Sorry if it's a basic python concept
over = False
def run():
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
while not over:
run()
Although the input is 'y' the loop doesn't stop.
You need to write global over, so function run() will change global variable
over = False
def run():
global over
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
while not over:
run()
You shouldn't be using a global variable here. Return a boolean, and call run as the condition of the loop. (At this point, you may want to reconsider the name run as well.)
def run():
user_input = input("Over? (y/n)")
return user_input == 'y'
while run():
...
You are setting the local variable over inside the function run(), but you aren't passing it out to the scope from which it was called. Instead return the value to the calling scope like this:
over = False
def run():
user_input = input("Over? (y/n): ")
if(user_input == 'y'):
over = True
else:
over = False
return over
while not over:
over = run()

Python main() not executing properly

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()

Categories

Resources