Is it possible to have more than one global variable within a python script?
import os,csv,random
def user():
global Forname
Forname = input('What is your forname? ').capitalize()
while True:
try:
global answerr
answerr = input('Welcome to the phone troubleshooting system '
'\nApple\nSamsung '
'\nOut of the following options enter the name of the device you own ').lower()
except ValueError:
continue
if answerr in ('apple','samsung'):
break
myfile = open(answerr+'_device.csv','r')
answer = input(Forname + ', do you have anymore problems? ').lower()
if 'yes' in answer:
#do whatever
else:
#do whatever
Using the global variable 'answerr' I'd like to open a csv file, and the refer to the user with the forname they input, but I want to use them multiple times through out my code within def functions. I apologise in advance if you do not understand what I'm asking, I'm relatively new to coding given the fact that I'm still a school student.
Of course it's possible. But there is absolutely no reason to use any global variables in this code, let alone multiple.
The point of a function is that it can return a value:
def user():
forename = input('What is your forename? ').capitalize()
return forename
Can I have multiple global variables within a Python script?
Yes and here's how:
When you're assigning any variable at the top-level of a module like: n = "Stackoverflow!" then your variable is global automatically. So let's say we have this modules:
#globals.py
x = 2 + 2
y = 5 + x
both x and y are global variables which means they're accessible to functions, classes and so on. *Just remember any assignment at the top-level of a module is actually global (this is what we call a global scope and it can contain as much variables as your memory allows). This is just like the code you posted. However, what we cannot have is same named variables in any scope:
same = 20
same = "s"
print(same)
will print s, not 20.
Hope you'll find this helpful :-)
Related
I have 2 functions: check_question_count() that asks a user to give an input of a number between 1 and 15 , validates the input, then returns it; random_question() function takes that returned number and generates a number of questions.
The issue is that the returned value from the first function does not seem to be returned, because i get an error that says: UnboundLocalError: local variable 'q_count' referenced before assignment.
def random_question():
check_question_count()
q_index = 1
global saved_question_count
saved_question_count = int(q_count)
print('Awesome! you will be asked ', saved_question_count,' randomly selected questions out of the total of 15 questions available.')
#Using a while loop to print out a randomly selected question:
while q_count != 0:
b = len(questions_list) - 1
rand_num = random.randint(0,b)
global selected_question
selected_question = questions_list[rand_num]
print('\n')
print(q_index,'.',selected_question)
global user_answer
user_answer = input('Your answer is: ').capitalize()
#Using a function to validate the user_answer input:
check_submitted_answers(user_answer)
questions_list.remove(selected_question)
questions_list = questions_list
q_count = q_count - 1
q_index = q_index +1
#4- Function to check the question count input and make sure its a number between 1 to 15:
def check_question_count():
global q_count
q_count = input('\nHow many questions do you like to take? You can choose a number between 1 to 15: ')
while True:
if q_count not in ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']:
print('Error: Invalid input! Please type in only a number between 1 and 15: ')
q_count = input('\nHow many questions do you like to take? You can choose a number between 1 to 15: ')
continue
else:
return q_count
random_question()
Any help is appreciated, thanks.
There are two problems with your code. One is severe, the other is not.
The root cause of the error UnboundLocalError: local variable 'q_count' referenced before assignment is the line q_count = q_count - 1 in random_question(). This supposed to modify the variable, but that variable is supposed to be global, and thus, not writable. This makes python believe you have a local, modifiable variable q_count, and thus, all the mentions of it in the current scope must mean this local one - and when you reference it first, it is referenced before assigned.
One solution would be to just use the global version, i.e. global saved_question_count, q_count. Another one would be to remove the line q_count = q_count - 1 - but you probably need that line. A third one would be to create a new (local) variable, and initialize it with q_count.
The best solution would be (that also fixes the second problem of unnecessary global variables) is to just return the value. Others have already explained that in detail.
You are not saving the returned value in any given variable i.e instead of
check_question_count()
try:
q_count = check_question_count()
in order to save the returned value in a variable.
You should also look into the proper use of global keyword because it is being used unnecessarily here-Use of "global" keyword
def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.
This question already has answers here:
Function not changing global variable
(4 answers)
Closed 1 year ago.
from random import randrange
on = ''
max_number = 0
random_number = 0
def start():
max_number = int(input('Enter max generated number: '))
random_number = randrange(max_number)
print(random_number)
on = True
start()
print(on) # returns false??
for a school project, i need to make a number guessing game. This is the start code i have. I declared "on" before the start function but the function wont change the value of the boolean to true
Right now, on is a "local" variable, only seen and used inside the scope of the function. To change the value of any variable inside and outside the function, you need to type the command global {variable}, usually at the top of a function. In your case, add this to your function:
def start():
global on <-- Right Here
max_number = int(input('Enter max generated number: '))
You can research more about global and nonlocal variables online.
Acknowledging #Samwise comment, global and nonlocal variables aren't always the best option, but I think that it's best to learn it anyway (the more you know!). He is correct, that you will likely not even need the on variable, and also that using a return statement is the best option.
Please Note That This Happened In 2019 So I picked up a few things from then
So please don't judge me.
So I have decided to try and make a very basic language in python.
And it is pretty basic right now but I want to improve it.
And one thing all languages need: variables
And right now I have this:
# Some other if statements up here
# neon is the name of the variable
# Something programmed real quickly to show example
elif neon[0:6] == ("addvar"):
var = neon[7:]
elif neon.startswith("add"+ var):
invar = neon.split("add"+ var , 1)[1]
elif neon.startswith("out"+ var):
print(invar)
YES it is very messy and horrid but I had to start with something and it is
very buggy. I had to start working on math so I skipped out on the variables. I tried a few tests before e. g. Appending data to a list and whatnot.
My Problem:
It only lets me have one variable
But now I wonder if there is a way that finally goes through the lexer and parser
Please tell me if there is
Use a dictionary to hold all your variables.
variables = {}
# some other code here
elif neon.startswith("addvar "): # addvar variablename
var = neon.split()[1]
variables[var] = None # create empty variable
elif neon.startswith("add "): # add variablename value
_, var, value = neon.split()
variables[var] = value
elif neon.startswith("out "): # out variablename
var = neon.split()[1]
print(variables[var])
def getValidSeason( ):
season = input ( "Enter a season between 1980 and 2016: " )
while season < 1980 or season > 2016:
season = input ( "Enter a season between 1980 and 2016: " )
return season
def getValidDriver( ):
driver = input ( "Enter a driver's name: " )
# This is where the first problem is
# I want to be able to use the value of season from getValidSeason( )
# in the getValidDriver( ) function
while getValidSeason( ) != 1980 and driver != "Steve Park" or driver != "Jamie McMurray"
driver = input ( "Enter a driver's name: " )
return driver
def printResults( ):
# Basically the same as before, I want the value of the driver
# variable defined in the getValidDriver( ) to be used in the print results( ) function
print ( "The driver being selected is",getValidDriver( ) )
def main( ):
# I don't believe my question has anything to do with what you put in the main function , but I might be wrong.
I looked around and could not find help with my problem. I am sorry if there is already a solution out there, but I couldn't find anything. Maybe I was wrong. I'm struggling with programming. I did find a question on this website that was basically the same question but it involved an earlier version of Python, and they were talking about stuff that is no longer used in the current version of Python.
Thanks for the help.
Your code is very close (although I don't understand the condition of the while loop). I cleaned up the formatting such as lowercase R in return and spacing conventions in function calls. I changed the inputs to convert to ints in getValidSeason() since you are trying to get strings. I also added some print lines in the while loop for my own benefit.
Also importantly, you don't need a main here (although it would be ok), but you do need to call your printResults() function to get the code running (the very last line of code). Let me know if you have questions about something I did or didn't explain.
CODE:
def getValidSeason():
season = int(input("Enter a season between 1980 and 2016: "))
while season < 1980 or season > 2016:
season = int(input("Enter a season between 1980 and 2016: "))
return season
def getValidDriver():
driver = input("Enter a driver's name: ")
season = getValidSeason()
# This is where the first problem is
# I want to be able to use the value of season from getValidSeason( )
# in the getValidDriver() function
#EDIT: Not sure what logic you actually want here
while season != 1980 and driver != "Steve Park" or driver != "Jamie McMurray":
print('Last driver selected was: '+str(driver))
print('Last season selected was: '+str(season))
driver = input("Enter a driver's name: ")
season = getValidSeason()
return driver
def printResults():
# Basically the same as before, I want the value of the driver
# variable defined in the getValidDriver() to be used in the print results() function
valid_driver = getValidDriver()
print ("The driver being selected is",valid_driver)
printResults()
EDIT:
#This is Function "func1"
#It takes the variable "name" as its one and only argument
# and it adds '_1' to the end of it before returning name
def func1(name):
print('In func1 you passed in the name: '+name)
print('Adding "_1" to the end of the name')
name = name+'_1'
print('In func1 your new name is: '+name)
print('')
return name
#Just like func1
def func2(name):
print('In func2 you passed in the name: '+name)
print('Adding "_2" to the end of the name')
name = name+'_2'
print('In func2 your new name is: '+name)
print('')
return name
#Function that will ask the user for a name
#Doesn't take any arguments
#Returns the name
def get_name():
name = 'Steve' #<-- just set to always be steve for now (you can replace this w/ an 'input()')
print('Your original name was '+name)
print('')
name_f1 = func1(name) #<-- original name w/ '_1' added to the back
name_f2 = func2(name) #<-- original name w/ '_2' added to the back
name_f1_f2 = func2(name_f1) #<-- orig name w' '_1_2' added to the back
name_f2_f1 = func1(name_f2) #<-- orig name w' '_2_1' added to the back
return name
#Call the get_name function which will then call func1 and func2
get_name()
You probably want to save the functions' return value in a variable in the other function. Here's an example for printResults:
def printResults():
driver = getValidDriver()
# you can now use the 'driver' variable
print("The driver being selected is", driver)
Python Course Shows that you simply need to add the global flag if you want to declare the variable as global inside a function. to further quote Python Course :
"The way Python uses global and local variables is maverick. While in many or most other programming languages variables are treated as global if not otherwise declared, Python deals with variables the other way around. They are local, if not otherwise declared."
I am not sure if this will resolve your issue completely since you are returning the variable back out. Thats simply the first thing I noticed about your code.
"I believe I understood the code you just put up. I'm getting my new keyboard in a couple days so I can't type the code yet, but I think I understand what is going on there. I don't think it answered my question though, unless I am missing something. Let's say in get_name( ) it asks the user to type in a name, and the user types in Tom. The variable that stores this is called name1. Now I want to use the variable name1 in multiple different functions, but I want the value of name1 to automatically be = to the user input defined in get_name( ) without the user having to type it again.
I think I could ask the user the question by using a global variable to ask it, but isn't it proper coding to have it inside a function? Functions are supposed to do 1 thing each and be used to break the program up. Putting the question outside of a function I think you aren't supposed to do. "
I read your comments on the comment section. I posted them above. I think the only thin you can do is call the function or created a global variable.