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
Related
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":
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.
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
I am trying to make a program that can add/delete/show students in a class, and the 5 classes are 5 lists in a list.
Help is greatly appreciated.
When I run this code:
global classes
def intro():
print("Welcome to Powerschool v2.0!")
print("Actions:")
print("1. Add Student")
print("2. Delete Student")
print("3. Show Students in a Class")
print("4. Show All Students")
x = int(input())
while x<1 or x>4:
print ("Please choose an action, 1-4.")
x = int(input())
if x == 1:
action1()
elif x == 2:
action2()
elif x == 3:
action3()
elif x == 4:
action4()
classes = [[],[],[],[],[]]
return classes
def action1():
print("Which Class? 1-5")
a = int(input())
print("Please enter the student's name.")
z = input()
classes[a-1].append(z)
again()
def action2():
print ("Which Class? 1-5")
print ("Which student?")
again()
def action3():
print ("Which Class? 1-5")
y = int(input())
if y == 1:
print (classes[0])
elif y == 2:
print (classes[1])
elif y == 3:
print (classes[2])
elif y == 4:
print (classes[3])
elif y == 5:
print (classes[4])
again()
def action4():
print (classes)
again()
def again():
print("Would you like to do something else? y/n")
h = input()
if h == "y":
intro()
else:
quit
def main():
intro()
main()
My error is:
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 67, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 65, in main
intro()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 19, in intro
action1()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 33, in action1
classes[a-1].append(z)
NameError: name 'classes' is not defined
I did return classes at the end of intro() but I see that doesn't work.
I followed some suggestions, and nothing really happened :/
You're defining classes in your intro method, and, even though it's returning it, your action1 method doesn't see any variable named classes anywhere.
Relevant answer on Python scope and relevant documentation.
return doesn't do what you think it does. return statements are a way of passing execution control back up a context (For example, from intro() to main()), with the ability to send back some information for the higher context to use. Although you're passing classes back to main(), you never do anything with it at that context so it goes away.
One way to solve the problem would be to declare classes as a global variable. This is the easiest thing to do, but isn't generally good design. You could do this either by using the global keyword before declaring the local variable classes in intro() (See this question for guidance on global), or by declaring classes outside any of your functions.
Another solution would be to pass classes as a parameter to your action functions.
In either case, you would need to declare classes before any calls to your action functions.
This is because classes is out of scope for the second two methods. Therefore, you have two options:
Option 1
Pass classes to the methods action1(), action2(), etc like so:
def action1(classes)
...and the when you call it:
action1(classes) //with the classes var you just made
Option 2 (recommended)
Simply put the classes var outside your methods or declare it global like so:
global classes = [[],[],[],[],[]]
...right before:
def intro()
In general, you should read up on how return works; it is not necessary in the code you wrote
classes only exists in intro():, you would have to declare it as a global variable to access it in other functions or declare it outside the function.
classes = [[],[],[],[],[]] # can be accessed by action3() ,action4()
def intro():
Newish to python, working on a text adventure, testing out the use of functions.
def cell1():
loop = 1
while loop == 1:
print("ONE")
cave1 = input()
if cave1 == ("end?"):
print("\nthis should end program")
loop = 0
break
elif cave1 == ("TWO"):
global testvar
testvar = 1
option1()
else:
print("INVALID")
def option1():
print("TWO")
loop = 1
while loop == 1:
print("test1 definition")
print (testvar)
test1 = input()
if test1 == ("ONE"):
print("you pick up the cheese")
loop = 0
cell1()
elif test1 == ("THREE"):
option2()
else:
print("INVALID")
def option2():
print("THREE")
loop = 1
while loop == 1:
print("This is option 3")
test2 = input()
if test2 == ("ONE"):
print("testering2")
cell1()
elif test2 == ("TWO"):
global testvar
testvar = 2014
option1()
else:
print("INVALID")
run = True
while run == (True):
print ("testing 123")
cell1()
print("restart about to activate")
cont = input("Restart? ")
if (cont) != "yes":
break
This program should allow you to go between options (what would be rooms) and eventually in cell1, the program should be end-able.
if the program is run and "end?" is typed as the first input, the program goes into the continue bit at the bottom, however, if you go between the 'rooms' then back to cell1, typing "end?" will call option 2.
Ive had a look around and it is still baffling me, am i ding something wrong?
Any help is appreciated, thank you.
The reason "end?" only quits for the player when they are within the first cell is because you're only checking for that input therein. The execution contained within option1() and option2() doesn't affect the execution of cell1(). You're not returning anything from your option functions, nor are you changing a sentinel value.
So, there's two basic ways you could go about this.
First, you could return a value from your functions:
if option1() == "END":
break
Or, you could alter your while loop:
# is_running is defined globally
while is_running:
And then just set is_running to False in any of your methods whenever the user types "end?". That'd probably be the easiest way with the design you're using now.
I'm sure you can tell, though, that in general your program is going to get exponentially more complex as you add more rooms and your function calls get further nested.
I'm pretty sure that the issue you're having is because you don't always break out of the loop in one function when you call another function. For instance, if your entries were TWO, ONE then end?, you'd find yourself still in the cell1 loop. That's because when the inner call to cell1 returns, the control flow of the program goes back to where that function was called from, which is option1, since loop is now 0, the loop ends and option1 returns, to the outer call to cell1, where the loop is still running.
Unless you want the game you're designing to have a tree structure, where you can return to where you came from with different semantics than moving to some other place, I'd suggest using a different architecture. Rather than each of your functions calling the next function when appropriate, return that function instead. Then you'd write a single top level loop that calls the function. Here's an example where the function to be called by the top level loop is saved in a variable named state:
def cell1():
print("In cell1!")
while True:
choice = input("pick 'ONE' or 'TWO' (or type 'quit' to exit):")
if choice == "ONE":
return option1
elif choice == "TWO":
return option2
elif choice == "quit":
return None
else:
print("I'm sorry, I didn't understand that.")
def option1(): # these other two functions are very basic in my example
print("In option1!") # but you can make them as complex as you want
return option2
def option2():
print("in option2!")
return cell1
def control_loop(initial_state=cell1):
state = initial_state
while state is not None:
state = state() # the next state is the return value of the previous state
The problem is you are getting deeper and deeper within nested functions. For example, changing
if test1 == ("ONE"):
print("you pick up the cheese")
loop = 0
cell1()
to
if test1 == ("ONE"):
print("you pick up the cheese")
loop = 0
break
will allow you to run your program, enter room two, go back to room one, and "end?" will work properly. This won't fix your issues completely though because there is a similar problem where when you go from two to three where if you simply changed
if test2 == ("ONE"):
print("testering2")
cell1()
to
if test2 == ("ONE"):
print("testering2")
break
it would break the current function and go back into option1() (if you run your program, go to room two, then to room three, then back to one) where "end?" doesn't do anything. Hopefully this gets you on the right track.