I have a code sample where the problem is:
while True:
for i in range(3):
i = input()
if i == 'quit'
break
else:
print('Try again')
When I type quit in my input it doesn't break out of the code. Thanks for your help!
Try using this code:
while True:
i = input()
if i == 'quit'
break
print('Try again')
I removed for loop because it has no usage and for loop is the reason of break not working because you are breaking out of for loop and not the while loop. I also removed else in if statement.
You're just breaking out of the for loop, not the while loop. If you want to get out of while loop then use this code:
while True:
for i in range(3):
i = input()
if i == 'quit':
break
else:
print('Try again')
continue
break
As Vishwa Mittar explained your code "break" works only for inner loop not for outer loop So you can use flag for while loop instead of bool as below
flag = True
while flag:
for i in range(3):
i = input()
if i == 'quit':
flag=False
break
else:
print('Try again')```
NOTE - The following answer(s) assume(s) that you need the for loop for some purpose.
The break statement is breaking out of the for loop. You need to create a variable outside the for loop with its value set to false. In the if i == 'quit', you need to set that variable to true. Then outside the for loop you need to check if that variable is true. If so, break out of the while loop.
So the final code would look something like this :-
while True:
exit_loop = false
for i in range(3):
i = input()
if i == 'quit':
exit_loop = true
break
else:
print('Try again')
if exit_loop: break
EDIT:
Another solution could be to raise an error and handle it using the try statement.
while True:
try:
for i in range(3):
i = input()
if i == 'quit':
raise ValueError('')
else:
print('Try again')
except Exception as e:
break
Related
I wrote a while loop asking the user whether they're male or female. Everything after "else" has been greyed out. When I hover over it with my mouse it says:
"Code is unreachable Pylance".
sex = input('What is your sex? (m/f/prefer not to say) ')
while True:
sex = input('What is your sex? (m/f/prefer not to say' )
print('success:)')
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")
How can this be fixed?
Note the differences. the break exit the loop totally.
The while loop continues operation as long as it condition evaluates as True. so therefore you need to create condition to either break from the loop within your code or modify the loop to evaluate as false.
Also, you would realise that when the loop eventually turns false only then is the else statement called. However, the else wont be called if break keyword was used to exit the loop.
tries = 5
opt =('m','f','prefer not to say')
while tries: #evaluates True but false if tries = 0
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
tries -=1
continue
print('success:)')
tries=0 # note here the bool(0) == False
else:
print('happens if there is no break from the loop')
print("we're out of the loop")
#opt 2
while True:
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
continue
print('success:)')
break. # completely exits the loop
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")
I have written a piece of code with a while loop, that I want to run until the user enters the string exit. However, I don't want the loop to be stopped for a repeat prompt after every loop cycle. How can I achieve this?
Currently the code loops correctly, however it does not respond to exit once in the while loop.
if __name__ == '__main__':
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
while name == True:
if prog_question == "exit":
name = False
break
else:
temperature_info = measure_temp()
if temperature_info[1] == "No error":
if int(temperature_info[0]) < int(check_temp):
heater("on",check_period*60)
else:
heater("off",check_period*60)
else:
measure_temp()
You are trying to let the user interrupt an infinite loop.
Your idea using input has the disadvantage that the user needs to actually input something on each iteration.
It might be more interesting to use try/except for that:
from time import sleep
try:
print("Hit Ctrl-C to stop the program")
while True:
print("still running")
sleep(1)
except KeyboardInterrupt:
print("this is the end")
Or you could also have a look at the module signal.
Just move the prompt to inside of the loop.
name = True
while name:
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
if prog_question == "exit":
name = False
break
else:
...
This question already has answers here:
How can I break out of multiple loops?
(39 answers)
How can I fix the if statements in my while loops?
(1 answer)
Closed 5 years ago.
I am wondering if someone can help me figure out how to fully break out of my while loop(s) and continue with the rest of my program. Thanks!
import time
while True:
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
break
#Continue with rest of my program
The solution below adds a flag to control when to break out of the external loop that is set to break out each loop, and set back if no break has occurred in the internal loop, i.e. the else statement has been reached on the inner loop.
import time
no_break_flag = True
while no_break_flag:
no_break_flag = False
company_name = input("\nWhat is the name of your company? ")
if company_name == "":
time.sleep(1)
print("\nThis is not eligible. Please try again")
else:
while True:
verify_name = input("\nPlease verify that {} is the correct name of your company \nusing Yes or No: ".format(company_name))
if verify_name.lower() == "no":
print("\nPlease re-enter your company name.")
time.sleep(1)
break
elif verify_name.lower() not in ('yes', 'y'):
print("\nThis is an invalid response, please try again.")
time.sleep(1)
break
else:
print("\nWelcome {}.".format(company_name))
verify_name == True
break
else:
no_break_flag = True
#Continue with rest of my program
Obviously as you have a condition of while True on the inner loop you will always exit by breaking, but if you had some other condition this would break the external loop only if a break statement was reached on the inner loop.
Here I want to exit the if block, but I don't want to use sys.exit() as it will terminate the program. I have a few lines to be executed at the end, hence I want to exit the if block only.
I can't use break as it flags an error "break outside loop".
In this I want the program to exit the block at "if (retry == 3)", line 55 and print the lines at the end. However, it’s not happening until it is using sys.exit(), where it’s completely exiting the program.
import random
import sys
loop = ''
retry = 0
loop = input('Do you want to play lottery? yes/no: ')
if loop != 'yes':
print('Thank you!! Visit again.')
sys.exit()
fireball = input('Do you want to play fireball? yes/no: ')
lotto_numbers = sorted(random.sample(range(0, 4), 3))
fireball_number = random.randint(0, 3)
while loop == 'yes':
user_input1 = int(input('Please enter the first number: '))
user_input2 = int(input('Please enter the second number: '))
user_input3 = int(input('Please enter the third number: '))
print('Your numbers are: ', user_input1, user_input2, user_input3)
def check():
if lotto_numbers != [user_input1, user_input2, user_input3]:
return False
else:
return True
def fbcheck():
if lotto_numbers == [user_input1, user_input2, fireball_number]:
return True
elif lotto_numbers == [fireball_number, user_input2, user_input3]:
return True
elif lotto_numbers == [user_input1, fireball_number, user_input3]:
return True
else:
return False
retry += 1
result = check()
if (result == True):
print("Congratulations!! You won!!")
else:
print("Oops!! You lost.")
if (fireball == 'yes'):
fb_result = fbcheck()
if (fb_result == True):
print("Congratulations, you won a fireball!!")
else:
print("Sorry, you lost the fireball.")
print('No of retries remaining: ', (3 - retry))
if (retry == 3):
sys.exit()
loop = input('Do you want to try again? yes/no: ')
continue
else:
pass
print("Winning combination: ", lotto_numbers)
if (fireball == 'yes'):
print('fireball no: ', fireball_number)
print('Thank you!! Visit again.')
You don't need anything at all. Code inside the if block will execute and the script will run code after the if block.
if is not a loop, so it doesn't repeat. To proceed to further code, just remember to stop the indent; that's all.
I.e.:
if some_condition:
# Do stuff
# Stop indent and do some more stuff
I think I gotcha your willing.
You want to execute something after the if condition is executed? So, create a subtask, and call it!
def finish_program():
print("something")
a = "foo"
print("finish program")
loop = input('Do u want to play lottery ? yes/no : ')
if loop!='yes':
print('Thank you!! visit again.')
finish_program()
Is there a use of break statement in python? I noticed that we can end the while loop with another faster ways.
As an example we can say:
name=""
while name!="Mahmoud":
print('Please type your name.')
name = input()
print('Thank you!')
instead of:
while True:
print('Please type your name.')
name = input()
if name == 'Mahmoud':
break
print('Thank you!')
and what is the meaning of while True?
break is useful if you want to end the loop part-way through.
while True:
print('Please type your name.')
name = input()
if name == 'Mahmoud':
break
print('Please try again')
print('Thank you!')
If you do this with while name != 'Mahmoud':, it will print Please try again at the end, even though you typed Mahmoud.
while True: means to loop forever (or until something inside the loop breaks you out), since the looping condition can never become false.