I am trying to make an on/off switch for my program:
(see after the ### for what I'm talking about)
while 1:
str = raw_input("insert your word: ")
n = input("insert your scalar: ")
def string_times(str, n):
return n * str
print string_times(str, n)
###
def switch(on,off):
raw_input("On or off? ")
if switch == "on":
continue
if switch == "off":
break
switch(on,off)
I get a continue not in loop error. Basically, I want to create an on or off switch after the program runs once. What do I fix?
You cannot use break and continue in a nested function. Use the return value of the function instead:
def switch():
resp = raw_input("On or off? ")
return resp == "on":
while True:
# other code
if not switch():
break
Note that there is little point in defining your functions in the loop. Define them before the loop, as creating the function object takes some performance (albeit a small amount).
The switch() function needs no arguments (you didn't use them at all), and the continue is also not needed. If you didn't break out of the loop, it'll just continue from the top when you reach the end.
You only need continue if you want the loop to start at the top again skipping the rest of the code in the loop:
count = 0
while True:
count += 1
print count
if loop % 2 == 0:
continue
print 'We did not continue and came here instead.'
if count >= 3:
break
print 'We did not break out of the loop.'
Related
This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 months ago.
I am trying to use two variables (i, and q) across three functions. I want to test whether i and q are valid after each input . If they are then they will be added to list and the while loop continues. If they are not valid Then the function will stop and all input will be taken and presented. I have tried to make both i and q global variables but it does not seem to work as it is saying that "i" is not defined. How do I check the i and q variables in separate functions?
Any help would be really appreciated as I am only new and thought this should work.
I didn't know what to add so I have put down the three functions in full below:
Updated:
def add_item():
code_inputed = []
quan_inputed = []
VC()
VQ()
vc_result = VC(I)
vq_result = VQ(q)
while True:
if i != "END":
if vc_result == True and vq_result == True:
code_inputed.append(int(i))
quan_inputed.append(int(q))
elif vc_result == True and vq_result == False:
print("Invalid Quanity")
break
elif vc_result == False and vq_result == True:
print ("Invalid code")
break
else:
print("Invalid inputs")
break
return code_inputed,quan_inputed
def VC():
i = input("enter code: ")
minimum = 0
maxiumum = 39
if i == "END":
return False
elif int(i) > minimum and int(i) <= maximum:
True
else:
False
def VQ():
q = input("enter quantity: ")
minimum = 0
maxiumum = 49
if int(q) > minimum and int(q):
True
else:
False
Thank you for any help
Please read this W3Schools - Python global variables for a better understanding of how global variables work.
I think the problem with your code is, you should initialize your variables i and q first, before the add_item() function, and then get them from the global scope using the global keyword in the add_item function too.
i = 0
def add_item():
global i
Plus, you want to recheck your add_item() conditions,
while True:
i = input("enter code: ")
return i
if i != "END":
q = input("enter quantity: ")
return q # your code stops at this return
VC()
VQ()
if VC == True and VQ == True:
code_inputed.append(int(i))
quan_inputed.append(int(q))
elif VC == True and VQ == False:
print("Invalid Quanity")
break
elif VC == False and VQ == True:
print ("Invalid code")
break
else:
print("Invalid inputs")
break
P.S. you actually don't have to use global variables in this context, you can just pass the values as functions arguments.
Looks like you need some help here. First of all the global keyword is for functions where you are setting the global variable. Also, forget about globals. Pass i and q to the functions directly. Then set those calls equal to variables and check those variables.
vc_result = VC(i)
vq_result = VQ(q)
if vc_result == True and vq_result == True:
...
Plus, return immediately exits the function so no processing will continue. Those should be removed. I recommend reviewing tutorials on python functions to fill in your knowledge.
What i want is if you choose a specific things to do by typing 1 or 2,but it will always
run the 'gen' option(number 1) even if you type 2.
while True:
a=int(input("pls choose what do you want to do.\n1=generates password \n2=acess saved passwords \n3=save passwords\nenter here:"))
if a == 1:
gen=True
break
if a==2:
see=True
break
if a==3:
save=True
break
else:
print('pls enter a valid respond\n----------------------------------------')
continue
if gen: #*<--it will always run this*
break
break
if see:
f = open("data.txt", "a")#*this did not run if typed '2'*
content=f.read()
f.close()
print(content)
Remove the break from if statement
while True:
a=int(input("pls choose what do you want to do.\n1=generates password \n2=acess saved passwords \n3=save passwords\nenter here:"))
if a == 1:
gen=True
break---> Your code break when you type 1
if a==2:
see=True
break ---> Your code break when you type 2
if a==3:
save=True
break
else:
print('pls enter a valid respond\n----------------------------------------')
continue
if gen: #*<--it will always run this*
break
break
if see:
f = open("data.txt", "a")#*this did not run if typed '2'*
content=f.read()
f.close()
print(content)`enter code here`
It's not entirely clear what you're asking, but there are at least two things you should change to accomplish what I imagine it is you're trying to do. First, you should use elif for the conditions a == 2 and a == 3:
if a == 1:
gen = True
break
elif a == 2:
see = True
break
elif a == 3:
save = True
else:
print(...)
continue
...
Right now, it appears that you will ask for a valid response whenever the input is not 3 (including when it is 1 or 2), but I imagine you only wish to print this statement when the inputs is not 1, 2, or 3.
Second, the reason f = open("data.txt"...) did not run is that this code block is inside the while loop. Whenever part of the code causes the program to exit the while loop (such as a break statement), nothing in the rest of the loop will be executed, including the if see: block.
I am working on a simple function to let the user select the language.
But for some reason, I can't see my mistake and the while loop never breaks.
def chooseLanguage():
"""Simple function to let the user choose what language he wants to play in"""
if game["language"] == "en_EN":
import res.languages.en_EN as lang
elif game["language"] == "de_DE":
import res.languages.de_DE as lang
else:
while game["language"] is None:
print ("Hello and welcome! Please select a language.")
print ("1. German / Deutsch")
print ("2. English")
langC = input ("Your choice: ")
if inputValidator(1, langC) == 1:
game["language"] = "de_DE"
break
elif inputValidator(1, langC) == 2:
game["language"] = "en_EN"
break
if game["language"] is None:
chooseLanguage()
else:
pass
Evidently the infinite loop was caused by inputValidator returning a value that was neither equal to 1 or 2. Thus the exit conditions of the loop were never met. And so it continues.
I have a program where a user inputs data, the data is turned into a list, and then the main function loops over the list until it has looped twice. Then the program should go back to maininput, so the user can input more data. However I can't get maininput to start before main, so main never gets the list to start the whole process. I tried calling maininput at the start of the program, obviously this can't work though since its not defined yet before line one.
Example structure:
def maininput():
userdata = input('input data: ')
list=[]
#userdata turned into a list...
def main():
counter = 0
for input in list:
counter +=1
#stuff done with input
if counter == 2:
print('Program finished')
maininput()
else:
pass
while True:
main()
I think you need some parameters in place to pass data around
def maininput():
userdata = input('input data: ')
#userdata turned into biglist1...
return biglist1
# take a list and the amount of iterations performed
def main(lst, counter=0):
if counter == 2: # change recursion when counter is reached
print('Program finished')
lst = maininput()
return main(lst) # also resetting the counter
for x in lst:
#stuff done with input
return main(lst, counter+1) # endlessly recurse
# No while loop needed, this function is recursive
main(maininput())
if the program have to run indefinitely, and if with big list you refer to the user input data, you can try this:
def maininput():
userdata = input('input data: ')
#userdata turned into a list...
return list
def main():
counter = 0
bigList = maininput()
while True:
for data in bigList:
#doing stuff
counter+=1
if counter == 2:
print('Program finished')
main()
else:
pass
main()
Why can't you just call maininput() before you hit the while True loop?
i.e:
maininput()
while True:
main()
So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)