Python Variable is not Defined - python

Currently my code has a main menu, it asks the user to choose from the option it prints out, this is inside a 'def' function. At the end of the variable I define, there is a input prompt to ask the user for their input named 'option'. However when i run the code i get a syntax. i.e:
The code:
def main_menu():
print ("\nMain Menu ")
print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
option = input ("\nEnter your Option: ")
main_menu()
option_class = input("\nWhich Class do you wish to preview: ")
one = "1.txt"
if option == "alpha".lower():
if option_class == "1":
with open (one, "r") as r:
for line in sorted(r):
print (line, end='')
when running the code I receive the following syntax:
NameError: name 'option' is not defined

option is locally defined. You can return entered value from function and assign it to option like this:
def main_menu():
print ("\nMain Menu ")
print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
return input ("\nEnter your Option: ")
option = main_menu()

Your variable option is only defined locally in your function main_menu(), not globally.

The variable option is only local to the function main_menu. You can fix it by making option global:
def main_menu():
global option
#...
option = '...'
See: Global vs local variables

Related

multiple global statements within function elifs

The program first asks the user if they'd like to load their own file or use the the file provided by the script.
filename=0
def first(filename):
print('Please Select:')
print('Run Program Now? Press "1"')
start = int(input('Load Your Own List and Run Program? Press "2": '))
if start ==1:
global filename
filename = 'file.txt'
elif start ==2:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
global filename
filename = tkinter.filedialog.askopenfilename()
else:
print("You didn't enter a valid selection!")
first(filename)
main()
I'm using another function which should call the correct file based on the user input.
def guess(real):
WORDLIST = filename
with open(WORDLIST, 'r') as in_file:
Error:
ErrorSyntaxError: name 'filename' is assigned to before global declaration
This all worked earlier when I had the user input and elif statements within
def guess(real):
Although I wanted to call it separately and that's why I have the user input in it's own function.
You don't need to use return with global variables, however I would avoid using global variables if possible. You might want to read "why are global variables evil" for more details.
A simplified version of the code you provided is shown below using return and then passing the result to another function to avoid using global variables:
def first():
while True:
print('Please Select:')
print('Run Program Now? Press "1"')
start = int(input('Load Your Own List and Run Program? Press "2": '))
if start == 1:
filename = 'file.txt'
return filename
elif start == 2:
filename = 'hello.txt'
return filename
else:
print("You didn't enter a valid selection!")
def second(filename):
print (filename)
filename = first()
second(filename)

Python - If statement not functioning inside def() function

I hope someone can help me with this issue.
from tkinter import *#This enables me to use the tkinter commands
window=Tk()#This declares the window
window.title("Binary-Denary converters")#This defines the name of the window
loop=1
def selection():
global submitbutton
global variable
global choice#This declares the variable so it can be used anywhere in the code
label1=Label(window,text="Submit 1 for D-B \nSubmit 2 for B-D ")#This tells the user what to input
label1.pack()
variable= StringVar(window)
variable.set("")
choice=OptionMenu(window, variable,"1 ", "2 ")
choice.pack()
submitbutton=Button(window, text="Submit",command=getinput)
submitbutton.pack()
def getinput():
global variable
global userinput
userinput=variable.get()#This takes the users input and assigns it to a variable
print(userinput)
if userinput =="1":
DToB()
else:
BToD()
def DToB():
display1=Label(window, text="D to B")
display1.pack()
submitbutton.destroy()
def BToD():
display2=Label(window, text="B to D ")
display2.pack()
submitbutton.destroy()
selection()
The user has a drop down list, and selects 1 for DToB and 2 for BToD, the program is able to identify the number that the user chose and I checked it does this by printing userinput. I have also checked and it is a str value that comes from this drop down list I confirmed this by adding userinput to userinput which gave me 1 1 instead of 2 if it was an int.
The issue is with the if statement " if userinput =="1" " in the getinput() function which even when userinput does = 1 just goes with what is in the else part of the statement.
I have used if statements like this in very similar codes before so I cannot understand what I have done wrong.
Here is some pictures of the program running
pic1 pic2
The problem is this line:
choice = OptionMenu(window, variable, "1 ", "2 ")
When the user chooses 1, the value of the StringVar is actually set to "1 ", not "1". Either change the values of the option menu or change if userinput == "1" to if userinput = "1 ", and your code will behave as expected.

Python Amateur - 'Greeting program' - 'Referenced before assignment error'

Like I said in my previous question, I'm a python amateur. I've made a couple silly mistakes. I'm attempting to make a highly simple greeting program using Python 3.4 however I have encountered an error. The error I have is:
UnboundLocalError: local variable 'lastNameFunction' referenced before assignment
Here's my code (I know I probably don't need to post it all, but there isn't much of it):
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()
I'd appreciate any help and advice! Please take into consideration I am really new to this stuff. I'm also not quite sure on having a function inside of a function, but I thought it would be a fix so that the 'firstName' was available when entering the 'lastName'.
Thanks in advance! :)
You need to move the lastNameFunction declaration somewhere before you call it using lastNameFunction(), e.g.:
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
if __name__ == '__main__':
main()
You can also move it outside the main function, but you will then need to pass the firstName in using the function arguments:
def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
def main():
...
lastNameFunction(firstName)
...
Move your lastNameFunction to somewhere before the call. Ideally, you would place this above the main function.
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...
The problem is you called lastNameFunction() before you defined it in the while loop. Try defining the function outside the while loop.
The organisation of the whole program seems a little bit off.
Imports usually go at the top of the module.
Functions defined in functions are usually just for closures, which you a) don't need here and b) might be a bit advanced for your current experience level.
Recursive calls like your calling main() from within main() are wrong. When you adopt that style of control flow instead of a loop, you will eventually run into limitations of recursive calls (→ RuntimeError). You already have the necessary loop, so simply leaving out the elif branch already asks the user again for the first name.
running isn't used anywhere, so you can remove it and just use while True:.
I would move asking the user for ”anything” + the question if the input was correct into its own function:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()

Calling function inside if statement

im trying to call function inside if statement but it does not work. This is one of my first attempts in using Python. What am I doing wrong?
#!/usr/bin/python
menu = raw_input ("Hello, please choose form following options (1,2,3) and press enter:\n"
"Option 1\n"
"Option 2\n"
"Option 3\n")
if menu == str("1"):
savinginfile = raw_input ("Please, state your name: ")
option1()
elif menu == str("2"):
print ("Option 2")
elif menu == str("3"):
print ("Option 3")
def option1():
test = open ("test.txt", "rw")
test.write(savinginfile)
print ("Option 1 used")
test.close()
Would recommend that you pass savinginfile as a parameter:
def option1(savinginfile):
test = open ("test.txt", "rw")
test.write(savinginfile)
print ("Option 1 used")
test.close()
You need to define option1 before calling. Python interprets from top to bottom.
You need to define your function before you try to call it. Just put def option1(): #and all that code below it above your if statements.
It's also bad practice to throw around too many global variables. You shouldn't use savinginfile the way you are -- instead, pass it to the function as a parameter and let the function operate in its own scope. You'll need to pass the function the name of the file to use before it's able to use savinginfile. Try instead:
def option1(whattosaveinfile):
test = open("test.txt","a+") #probably better to use a with statement -- I'll comment below.
test.write(whattosaveinfile) #note that you use the parameter name, not the var you pass to it
print("Option 1 used")
test.close()
#that with statement works better for file-like objects because it automatically
#catches and handles any errors that occur, leaving you with a closed object.
#it's also a little prettier :) Use it like this:
#
# with open("test.txt","a+") as f:
# f.write(whattosaveinfile)
# print("Option 1 used")
#
#note that you didn't have to call f.close(), because the with block does that for you
#if you'd like to know more, look up the docs for contextlib
if menu == "1": #no reason to turn this to a string -- you've already defined it by such by enclosing it in quotes
savinginfile = raw_input("Please state your name: ")
option1(savinginfile) #putting the var in the parens will pass it to the function as a parameter.
elif menu == "2": #etc
#etc
#etc

python: global name 'user_input' is not defined

I keep getting the error message "global name 'user_input' not defined. new to python and to SO, hope you can help. Here's my code. Sorry if it's a mess. just starting out and teaching myself...
def menu():
'''list of options of unit types to have converted for the user
ex:
>>> _1)Length
_2)Tempurature
_3)Volume
'''
print('_1)Length\n' '_2)Temperature\n' '_3)Volume\n' '_4)Mass\n' '_5)Area\n'
'_6)Time\n' '_7)Speed\n' '_8)Digital Storage\n')
ask_user()
sub_menu(user_input)
def ask_user():
''' asks the user what units they would like converted
ex:
>>> what units do you need to convert? meter, feet
>>> 3.281
'''
user_input = input("Make a selection: ")
print ("you entered", user_input)
#conversion(user_input)
return user_input
def convert_meters_to_feet(num):
'''converts a user determined ammount of meters into feet
ex:
>>> convert_meters_to_feet(50)
>>> 164.042
'''
num_feet = num * 3.28084
print(num_feet)
def convert_fahrenheit_to_celsius(num):
'''converts a user determined temperature in fahrenheit to celsius
ex:
>>> convert_fahrenheit_to_celsius(60)
>>> 15.6
>>> convert_fahrenheit_to_celsius(32)
>>> 0
'''
degree_celsius = (num - 32) * (5/9)
print(round(degree_celsius, 2))
def sub_menu(num):
'''routes the user from the main menu to a sub menu based on
their first selection'''
if user_input == '1':
print('_1)Kilometers\n' '_2)Meters\n' '_3)Centimeters\n' '_4)Millimeters\n'
'_5)Mile\n' '_6)Yard\n' '_7)Foot\n' '_8)Inch\n' '_9)Nautical Mile\n')
ask = input('Make a selection (starting unit)')
return
if user_input == '2':
print('_1)Fahrenheit\n' '_2)Celsius\n' '_3)Kelvin\n')
ask = input('Make a selection (starting unit)')
return
When you do:
user_input = input("Make a selection: ")
Inside the ask_user() function, you can only access user_input inside that function. It is a local variable, contained only in that scope.
If you want to access it elsewhere, you can globalise it:
global user_input
user_input = input("Make a selection: ")
I think what you were trying was to return the output and then use it. You kind of got it, but instead of ask_user(), you have to put the returned data into a variable. So:
user_input = ask_user()
THere's no need to globalise the variable (as I showed above) if you use this method.
In your menu function, change the line that says ask_user() to user_input = ask_user().

Categories