So in this book chapter 3 subsection "Creating Intentional Infinite Loops" author gives this example:
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
But it doesn't work. It only spits out break-outside-loop and continue-not-properly-in-loop errors. From what I've read break/continue can't be used to break out of an if - it can only break out of loops, and that I should use sys.exit() or return. The question arises, what the author meant, and why he made this -basic?- mistake? Or maybe it isn't a mistake and I'm missing something.
Could you help me grasp this concept of break/continue function with fairly similar and simple example? :)
Indentations matter in python. So it must be,
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
Cuz you miss-indented it, so do:
# Finicky Counter
# Demonstrates the break and continue statements
count = 0
while True:
count += 1
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
print(count)
input("\n\nPress the enter key to exit.")
So the lines:
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
Got all a extra tab, so it becomes:
# end loop if count greater than 10
if count > 10:
break
# skip 5
if count == 5:
continue
Note: even if you remove break and continue, there will be still a problem, it will be an infinite loop.
Related
The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.
So I have this section of code here:
count = 1
if count < 5:
print ("If 5 rounds have passed, enter any other key: ")
nextr = str(input("Do you want to continue to the next round?(1)" + "\n"))
if nextr in ("1", "(1)"):
count += 1
continue
while count == 5:
break
And I wondered: How could I do this count controlled loop without it reverting back to 1 every time. I would like the program to go through a game once, ask the user if they want to continue, then go through it 4 more times before breaking and then showing the final scores. Any help greatly appreciated!
I'm not sure what are you looking for, but it may help.
print ("If 5 rounds have passed, enter any other key")
count = 1
while count <= 5:
nextr = (input("Do you want to continue to the next round?(Yes/No)"))
print ("count = ",count)
if nextr.lower() in ("y", "yes"):
count += 1
Or maybe something like this one:
import time
def round_5():
count = 1
while count <= 5:
print ("Count = ",count)
count += 1
time.sleep(1)
nextr = "y"
print ("If 5 rounds have passed, enter any other key:")
while nextr.lower() in ("yes","y"):
round_5()
nextr = (input("Do you want to continue to the next round?(Yes/No)"))
print ("Thank you, have a nice day")
I would like to know a simple way to NOT update the counter, within a while loop, when something other than y/n is entered. Here is my code:
if yes_or_no == "y":
computer_winnings += 1
elif yes_or_no == "n":
user_winnings += 1
counter += 1
if counter > 10:
break
However, main counter is also being updated if user enters anything other than y/n. Counter should only update if y or n was entered.
Include the counter increment under a test for either y or n
if yes_or_no in ('y', 'n'):
counter += 1
if yes_or_no == 'y':
computer_winnings += 1
else:
user_winnings += 1
Let's say we iterate from 0 to 9
i = 0
while(i < 10):
#Ask for user input
foo = input()
#if foo value != yes_or_no value increment i
if foo != yes_or_no:
i+=1
You need to indent codes properly to fall under whatever statement you wish it to be in. How you have it written the if/else are 1 independent set, the counter is also an independent set, and the if counter state is also independent. So you have 3 independent statements running at the same time.
And with if statements your code will only process them once and only once, so using a while loop would be best to loop continuously until you hit an escape statement.
user_answer = (raw_input('Can you guess the word that is missing? ')).lower()
count =0
while count <=1:
if user_answer == 'brown':
print ('Well done')
break
else:
user_answer =(raw_input('Please Guess again? '))
count+=1
else:
print ("Fail Game")
I'm working on a simple game and it allows the user to input the wrong guess three times. I have been playing around with this while loop and it works, (while count <=1) but i am a little confused as too why??? (not complaining) but can anyone explain why it works as i originally though the code should be like to one below (but these uses 5 attempts)
count = 0
while count <=3:
all rest of code is same as above.
The maximum number of inputs you can get with that code is 3. Why?
The first is outside the loop.
The second is when count is 0. After the input, count will be 1.
The third (and last) is when count is 1. After the input, count will be 2. The loop will finish in the next iteration because the condition 2 <= 1 will be False.
How do I end my program if something is true?
This is my code
count=0
num=input("What would you like to do [1,2,3,4]? ")
while (num>'0' and num<'5'):
while num=='1':
Do something
while num=='2':
Do something
While num=='3':
Do something
while num=='4' and count!=1:
print("The End")
count= count+1
I want the program to end while num is '4'
First of all use integers not strings:
>>> '100' > '5'
False
And use if instead of while, if any of the conditions is True then you can use the break statement to break out of the loop.
count = 0
num = int(input("What would you like to do [1,2,3,4]? "))
while 0 < num < 5:
if num == 1:
Do something
...
if num == 4 and count != 1:
print("The End")
count += 1
break #breaks out of the `while` loop
Also note that you should use if-elif-else conditions here instead of just if's, because here all if conditions are going to be checked, but with if-elif-else conditions will short-circuit(jump to the end of if-elif-else block) as soon as one of the condition is True.
Use
if num=='4' and count!=1:
not
while num=='4' and count!=1:
Add a break statement and use numbers
while (num > 0 and num < 5):
while num == 1:
#Do something
while num == 2:
#Do something
while num == 3:
#Do something
if num == 4 and count != 1:
print ("The End"); count += 1
break
Use if in place of while loop like,
while (num>0 and num<5):
if num==1:
Do something
if num==2:
Do something
if num==3:
Do something
if num==4 and count!=1:
print("The End")
count= count+1
break