'Making a certain statement loop forever in Python
while 1 == 1:
do = raw_input('What would you like to do?')
In the above example you can see that the code is meant to make something loop forever, for example:
if do == 'x':
print 'y'
elif do == 'z':
print 'a'
So this if
statement has been carried out and I want the raw_input
to be carried out again so that the person can enter something else and the program goes on again.
I would not like to put the entire program in a
while True:
program or a
while 1 != 2:
statement.
Solution 1:[1]
Normally you do this until a certain condition is met, for example, the user types q
to quit; otherwise it is just an infinite loop and you would need to force quit the entire program.
Try this logic instead:
result = raw_input('What would you like to do? Type q to quit: ')
while result.lower() != 'q':
if result == 'x':
print 'y'
if result == 'z':
print 'a'
result = raw_input('What would you like to do? Type q to quit: ')
print('Quitting. Good bye!')
Solution 2:[2]
def user_input():
do = raw_input('What would you like to do?')
if do == 'x':
print 'y'
user_input()
elif do == 'z':
print 'a'
user_input()
elif do =='quit':
print 'exiting user input'
else:
user_input()
user_input()
The above uses some recursive calls and is less succinct than a while statement, but would work if you are looking to avoid using while.
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 | Burhan Khalid |
Solution 2 | Burhan Khalid |