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

using a break in while loop

hi, so i tried using a break function in a while loop in the code below and that raised a few questions in my mind: def tf_quiz (tf_question, tf_answer): nonsense = "today i tried weed with a "+tf_question + " and a "+ tf_answer return nonsense num_que = 4 counter = 0 while counter <= num_que: shift = tf_quiz (input ("who is the first person i had with today? "),input("who is the second person that shared the weed? ")) print (shift) counter += 1 if tf_quiz("amy","fowler"): break my aim is to stop the loop when it encounters "amy" "fowler" when i run the code without "break" but rather a print statement after the if statement, it works fine. but when the "break" was included if stops after the first loop and doesnt wait to encounter "amy" "fowler". 1. what could be wrong? 2. can one use break directly after "if" (like in the code) or must it come after else

10th Apr 2018, 5:18 AM
Doe Dare Oladimeji
Doe Dare Oladimeji - avatar
3 Answers
+ 1
1. Your if statement is always true because you pass 'nonsense' value all the time from the tf_quiz unconditionally. That is why you always got break done 2. You can use break whereever in the loop - it depends on what are you going to get. 3. Better practice is to create your program in Code Playgreound section and post a link to it here.
10th Apr 2018, 7:43 AM
strawdog
strawdog - avatar
0
thanks. will do that next time
10th Apr 2018, 7:47 AM
Doe Dare Oladimeji
Doe Dare Oladimeji - avatar
0
store shift inputs into separate variables and use the variables in the if statement instead of a function(which will just always return true and break). also call the tf_quiz with these variables, preferrably after the if, assuming you want it to break before running it.
10th Apr 2018, 12:36 PM
Markus Kaleton
Markus Kaleton - avatar