'Initializing a string variable in python
I'm a python noob currently working with while loops. I get the idea about a condition has to be met for the loop to stop:
while some_number < 10:
I want to use strings to stop the loop:
continue_or_quit = str(input('Press c to continue, q to quit: ')).
When I run this loop in the interpreter, it says variable referenced before assignment. How do I make this work?
Solution 1:[1]
Option 1 (using an infinite loop and break):
while True:
... # some code
continue_or_quit = input('Press c to continue, q to quit: ')
if continue_or_quit == 'q':
break
Option 2 (initializing a truthy value):
continue_or_quit = 'a' # anything other than 'q'
# forcing the while loop to run the first time
while continue_or_quit != 'q':
... # some code
continue_or_quit = input('Press c to continue, q to quit: ')
Also, you don't need to use str on input since its result is already a string.
Solution 2:[2]
One thing which I noticed but won't solve your problem: In Python, the input() function will always return a string, so there is no need to cast this into a string with str().
As for your problem: With while, the loop will run as long as the condition is met. There is no need to tell the loop explicitly that it should continue. What you can do to address your need is to have the while some_number < 10: condition and then, inside the loop, ask if the user wishes to stop: continue_or_quit = input('Press q to quit: ')
You can then check if the user typed q (or Q, if you want to be case-insensitive) and, if so, break out of the loop:
while some_number < 10:
# Do something
continue_or_quit = input('Press q to quit: ')
if continue_or_quit == "q" or continue_or_quit == "Q":
break
But don't forget that some_number should change, otherwise you'll end up in a infinite loop (unless the user quits).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrGeek |
| Solution 2 | Schnitte |
