Python - If statement not functioning inside def() function - python

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.

Related

How do I get my code to run the if statement?

I'm a beginner in Python and I'm writing a code for a school project and ran into an early bug.
For some reason my if function won't run.
import time #imports computer time to program(buit in function)
count= 0
print(" Gymship") # center this
print("--------------------------------------") # this should go across the whole screen
print("Input a level to view the description or InputSign up to begin signing up for a card")
print("--------------------------------------------------------------------------")
print("Bronze")
time.sleep(1) # this wil pause the program for 1 second(for effect)
print("Silver")
time.sleep(1)
print("Gold")
time.sleep(1)
print("Platinum")
time.sleep(2)
print("-----------------------------------------------") # this should go across the whole screen
print("Sign up")
print(" ")
input()
if input == "Bronze":
print("Bronze")
print("--------------------------------------------")
print("You acquire a bronze card when you use two or less gym services")
print("2 Hours limit in the gym")
print("-------------------------------------")
print(input("Back to return to menu screen"))
count = count + 1
This is not correct:
input()
if input == "Bronze":
The way input() works is by returning a value. The name input refers to the function itself, so the function input will never equal the text "Bronze" unless you explicitly do something bad, like input = "Bronze" (it's bad because if you overwrite input, you'll no longer be able to access that function).
Instead, you should be using the returned value:
usr_input = input()
if usr_input == "Bronze":
Also, the line print(input("Back to return to menu screen")) is unnecessarily complicated; the print() will print whatever was returned by input(), but input() will display the "Back to return to menu screen" prompt without wrapping it in an if statement. So, input("Back to return to menu screen") is all you need. If you keep it the way you have it, if someone typed some text and then hit enter, the text would display again, because the print() is printing whatever that text was that the user typed.
You first need to assign a variable to the input and then check if the variable is equal to "Bronze"
Right now you are taking the input, but are not storing it anywhere. So the fixed code would be
user_input = input()
if user_input == "Bronze":

Python Variable is not Defined

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

Using Python Class to make game- how to update self init?

I am making a text-based game on python using the class system to keep track of main character changes (like its name). I am writing the main code for the game outside of the Main Character Class- inside of the main function.
I am struggling because I need to update self.character_name inside the Main Character class to an input from the user inside the main function. I am unsure how to do this, I have the code written below- however it is not updating the name inside Main Character class. How can I rewrite this?
I'm also worried that I will have this problem when trying to update pets, characters_known. However, I do not seem to have this problem with updating Health or XP....
class Main_Character():
def __init__(self):
self.health=100
self.exp=0
self.level=0
self.character_name=""
self.characters_known={None}
self.pets={None}
self.progression_tracker=0
def __str__(self):
return "Name: "+ str(self.character_name)+" | "+ "Health:"+ str(self.health) + " | " +"XP:"+ str(self.exp) + " | "+ "Level:"+ str(self.level)+" | "+"Pets:"+str(self.pets)
def Char_Name(self,name):
if name.isalpha()==False:
print("You entered a name containing non-alphabetic characters, pease reenter a new name:")
main()
elif len(name)>=10:
print("You entered a name containing 10 or more characters, pease reenter a new name:")
main()
else:
self.character_name=name
def Char_Level_Experience(self,exp,b):
self.exp+=exp
b=2
if exp<=0:
exp=1
ans = 1
level=0
while ans<exp:
ans *= b
level += 1
if ans == exp:
self.level=level
print("You have reached level", self.level)
else:
level = int(log(exp, 2))
level = min(level, exp)
if level>=0:
self.level=level
else:
level=0
def healing(self,heal):
if self.health+heal>=100:
self.health=100
else:
self.health+=heal
def other_answers(answer):
if answer=='quit':
raise SystemExit
if answer=='pets':
print("Pets owned:", Main_Character().pets)
user_decision=input("Would you like to continue where you left off? Type 'yes' to continue, or 'no' to go back to main menu")
if user_decision=='yes':
if Main_Character().progression_tracker==0:
main()
elif Main_Character().progression_tracker==1:
choice1()
if user_decision=='no':
main()
else:
other_answers(user_decision)
if answer=='characters':
print("Characters met:", Main_Character().characters_known)
user_decision=input("Would you like to continue where you left off? Type 'yes' to continue, or 'no' to go back to main menu:")
if user_decision=='yes':
if Main_Character().progression_tracker==0:
main()
if Main_Character().progression_tracker==1:
choice1()
if user_decision=='no':
main()
else:
other_answers(user_decision)
def start_check():
print("If you understand the game, type 'go' to continue- if not, type 'more information' to receive more information about how to play the game")
begin_game=input("")
if begin_game=="go":
choice1()
if begin_game=='more information':
print("\n","The object of the game is to gain XP [experience points] without dying")
start_check()
else:
other_answers(begin_game)
def choice1():
Main_Character().progression_tracker=1
print("You are a knight in the Kings Guard- the King has asked to meet with you about a very special mission")
print("What would you like to do?")
print(" 1.Go Directly to King","\n", "2. Finish your dinner")
choice=input("1 or 2?")
if choice=="1":
Main_Character().Char_Level_Experience(1,2)
elif choice=="2":
Main_Character().Char_Level_Experience(.5,2)
else:
other_answers(choice)
print(Main_Character())
def main():
print("Welcome!")
unfiltered_name=input("Please enter the name of your character:")
Main_Character().Char_Name(unfiltered_name)
print("Welcome,", Main_Character().character_name,"!", "Here are your current stats!")
print(Main_Character())
start_check()
You haven't quite understood how classes and instances work.
Calling the class is what you do when you need a new character. Every time you call Main_Character(), you get a whole new instance - with the default values as set in __init__. If you had characters for each of your friends, you would call it one time for each one. You then would need to keep each of those instances in a variable, so you can reference them again each time.
So, for instance:
my_character = Main_Character()
unfiltered_name=input("Please enter the name of your character:")
my_character.Char_Name(unfiltered_name)
print("Welcome,", my_character.character_name,"!", "Here are your current stats!")
print(my_character)
You create a new character each time you call Main_Character. Instead, you should call it once:
the_character = Main_Character()
...
the_character.name = "..."

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