In your case, in inputHandler, you are creating a new variable called active and storing False in it. This will not affect the module level active.
To fix this, you need to explicitly say that active is not a new variable, but the one declared at the top of the module, with the global keyword, like this
def inputHandler(value):
global active
if value == 'exit':
active = False
But, please note that the proper way to do this would be to return the result of inputHandler and store it back in active.
def inputHandler(value):
return value != 'exit'
while active:
userInput = input("Input here: ")
active = inputHandler(userInput)
If you look at the while loop, we used while active:. In Python you either have to use == to compare the values, or simply rely on the truthiness of the value. is operator should be used only when you need to check if the values are one and the same.
But, if you totally want to avoid this, you can simply use iter function which breaks out automatically when the sentinel value is met.
for value in iter(lambda: input("Input here: "), 'exit'):
inputHandler(value)
Now, iter will keep executing the function passed to it, till the function returns the sentinel value (second parameter) passed to it.
In your case, in inputHandler, you are creating a new variable called active and storing False in it. This will not affect the module level active.
To fix this, you need to explicitly say that active is not a new variable, but the one declared at the top of the module, with the global keyword, like this
def inputHandler(value):
global active
if value == 'exit':
active = False
But, please note that the proper way to do this would be to return the result of inputHandler and store it back in active.
def inputHandler(value):
return value != 'exit'
while active:
userInput = input("Input here: ")
active = inputHandler(userInput)
If you look at the while loop, we used while active:. In Python you either have to use == to compare the values, or simply rely on the truthiness of the value. is operator should be used only when you need to check if the values are one and the same.
But, if you totally want to avoid this, you can simply use iter function which breaks out automatically when the sentinel value is met.
for value in iter(lambda: input("Input here: "), 'exit'):
inputHandler(value)
Now, iter will keep executing the function passed to it, till the function returns the sentinel value (second parameter) passed to it.
Yes, you can indeed do it that way, with a tweak: make active global.
global active
active = True
def inputHandler(value):
global active
if value == 'exit':
active = False
while active:
userInput = input("Input here: ")
inputHandler(userInput)
(I also changed while active is True to just while active because the former is redundant.)
Python: 'break' outside loop - Stack Overflow
How to break out of while loop in Python? - Stack Overflow
break outside of loop?
python - How to break while loop while outside of the terminal - Stack Overflow
Videos
I have a long while loop, it has a lot of code in it and a lot of delays.
I want to break out of the loop when a condition is met but I need to break out of it instantly. The only thing I can think of, is to print if statements constantly through the loop, checking if the condition is true, but this seems a little silly because it would have literally 100s of break statements.
Is there any better way to do this without typing break statements after every single line of code, that seems impractical because there's 100s of lines of code in the while loop, it takes around 10 minutes to finish and I need it to break instantly
Because break cannot be used to break out of an if statement -it can only break out of loops. That's the way Python (and most other languages) are specified to behave.
What are you trying to do? Perhaps you should use sys.exit() or return instead?
Some other common ways this error may show up:
1. Incorrect indentation
Indentation is extremely important in Python. It helps determine the grouping of statements, so if you don't group statements correctly, your code will not work as expected.
Suppose you perform some computation inside a loop and depending on its result, either continue on in the loop or break out of the loop. If you inadvertently put the if-else block outside the loop because you missed the indentation, you will get the error in the title. To solve the error in that case, use indentation correctly.
For example the following will raise the error in the title.
for i in range(10):
print(i) # <--- do something
if i % 3: # <--- break out of loop on some condition
break
The following solves this error:
for i in range(10):
print(i)
if i % 3: # <--- use indentation correctly
break # <--- to break out of loop
Of course your program will probably have much more code than this but the general structure might be the same in which case, see if the proposed solution applies.
I think this issue is exacerbated by some IDEs that use 2 spaces (not the 4 recommended by PEP8) per indentation level by default, which sometimes makes it difficult to see where indentation ends.
2. Include a break statement inside a function
The break statement must be explicitly inside the loop definition; it cannot be nested in a function that will be executed inside a loop.
For example, the following raises the error in the title:
def func(x):
x *= 10
if x > 20: # <--- break out of loop on condition
break
for i in range(10):
func(i) # <--- call function
To solve it, move the conditional check out of the function and put it in the loop.
def func(x):
x *= 10
return x # <--- return the value
for i in range(10):
x = func(i) # <--- call function
if x > 20: # <--- check condition
break
A couple of changes mean that only an R or r will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
I would run the loop until ans is 'Q' like this:
ans = 'R'
while not ans == 'Q':
print('Your score is so far ' + str(myScore) + '.')
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans == 'R':
R = random.randint(1, 8)
print("You rolled a " + str(R) + ".")
myScore = R + myScore
So I am making a Point of sale system code in python with my group and I am wondering how do I make the code run again so you can make multiple order?
Please check the bottom of the code:
https://pastebin.com/f39GpLwT
edit: also i forgot to mention but pls help me in improving the code. I am begginer in python so i only know if else elif
edit: problem solved! I just forgot to indent and put "while True:" on top
Because you are new to programming, I will get a few basic tips in my answer too.
INFINITE LOOP
You are trying to start an infinite loop by first settingagain = 'y' and afterwards you are using this variable to evaluate a while loop. Because you are not changing the value of y, it is better to not use a variable to create this infinite loop. Instead, try this:
while True:
(some code)
DEFINE FUNCTION IN LOOP
You're defining the function main() inside of the while loop. As far as I can tell, there is no use for that. Just leave out the first while loop. If you define a function, it is permanent (much like a variable), so no need to redefine it everytime. Using your code, you won't even get to call the function, because you never end the first loop.
CONTINUE/BREAK NOT IN LOOP
The error is quite self-explanaitory, but here we go. If you would ever end the first loop (which in this case, you won't), the next thing you do is call your function main(). This will generate a number and make the user guess it until he got it right. When that happens, you get out of that function (and loop).
Next, you ask if the user would like to play again. This is just an input statement. You store the answer in the variable 'again'. You check, with an if statement (note that this is not a loop!) what the answer is. You want the user to play again if he typed 'y', so instead of using again != 'y', you could use the following:
if again == 'y':
main() # you call the function to play again
If 'n' was typed in, you want to exit the script, which you do not by typing break, because you are not in a loop, just in an if-statement. You can either type nothing, which will just go out of the if-statement. Because there is nothing after the if, you will exit the script. You could also useexit(), which will immediately exit the script.
Lastly, you want to repeat the question if neither of these two things were answered. You can put the if-statement inside of a loop. You can (if you want) use your break and continue when doing this, but you mostly want to avoid those two. Here is an example:
while True:
again = raw_imput('y for again or n to stop')
if again == 'y':
main()
exit() # use this if you don't want to ask to play again after the 2nd game
elif again == 'n':
print('bye!')
exit()
# no need for an 'else' this way
# every exit() can be replaced by a 'break' if you really want to
BASIC BREAK/CONTINUE USAGE
Finally, here is some basic usage of break and continue. People generally tend to avoid them, but it's nice to know what they do.
Using break will exit the most inner loop you are currently in, but you can only use it inside of a loop, obviously (for-loops or while-loops).
Using continue will immediately restart the most inner loop you are currently in, regardless of what code comes next. Also, only usable inside of a loop.
EVERYTHING TOGETHER
import random
again = 'y'
def main():
print ("gues a number between 0 - 10.")
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print ('Your the man')
found = True
else:
print ('to bad dude try again')
main()
while True:
again = input('would you like to play again press y to play again press n yo exit')
if again == 'n':
print ('bye!')
exit() # you could use break here too
elif again == 'y':
main()
exit() # you can remove this if you want to keep asking after every game
else:
print ('oeps i don\'t know what you mean plz enter y to play again or n to exit')
I hope I helped you!
You loops and def are all muddled, you want something more like:
import random
again = 'y'
while again == "y" :
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
while True:
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
break
- Raise an exception, that you can handle outside the While loop
- Return a flag to be captured by the caller and handle accordingly. Note,
"if logic" directly in the while loop,, would be the most preferred way.
Python has a cool feature in generators - these allow you to easily produce iterables for use with a for loop, that can simplify this kind of code.
def input_until(message, func):
"""Take raw input from the user (asking with the given message), until
when func is applied it returns True."""
while True:
value = raw_input(message)
if func(value):
return
else:
yield value
for value in input_until("enter input: ", lambda x: x == "exit"):
...
The for loop will loop until the iterator stops, and the iterator we made stops when the user inputs "exit". Note that I have generalised this a little, for simplicity, you could hard code the check against "exit" into the generator, but if you need similar behaviour in a few places, it might be worth keeping it general.
Note that this also means you can use it within a list comprehension, making it easy to build a list of results too.
Edit: Alternatively, we could build this up with itertools:
def call_repeatedly(func, *args, **kwargs):
while True:
yield func(*args, **kwargs)
for value in itertools.takewhile(lambda x: x != "exit",
call_repeatedly(raw_input, "enter input: ")):
...