How to break while loop in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to break while loop in Python

What is the mistake in this code? I want the loop break if user input China. But there is some problem loop is not breaking keep running. question = input("Which country is the largest producer of tea\n1.Srilanka \n2. Kenya \n3.China \n4.Pakistan\nType your answer here: ") while question != "China": if question == "China": break print("Bravo") else: print(input("Your answer is wrong, please try again! "))

26th Jan 2018, 8:51 PM
Abdul Basit
Abdul Basit - avatar
4 Answers
+ 1
While True is an infinite loop. It will keep iterating until it reaches a break statement. The only way to reach the break statement is if the input is China. Else it prompts the user for input again. The continue statement continues the loop but since there are no more statements it starts the loop over and checks if this time input is China. It repeats until the input is China. question = input(‘Your text’) while True: if question == ‘China’: print(‘Bravo’) break else: question = input(“Your text”) continue
27th Jan 2018, 5:34 AM
Travis
Travis - avatar
+ 2
If take out the last line as you said then how can I take input from user if he didn't answer correctly first time?
26th Jan 2018, 9:02 PM
Abdul Basit
Abdul Basit - avatar
+ 1
"""What is the mistake in this code? I want the loop break if user input China. But there is some problem loop is not breaking keep running. """ question = input("Which country is the largest producer of tea\n1.Srilanka \n2.Kenya \n3.China \n4.Pakistan\nType your answer here: ") stuff = ("China") if question in stuff: print("Bravo") else: print("Nope")
26th Jan 2018, 9:41 PM
Ole113
Ole113 - avatar
0
If you take out the last statement print(input(........) Take out the input part
26th Jan 2018, 8:59 PM
Ole113
Ole113 - avatar