Reputation: 3
I'm new to python and I'm using the book called "Automate the Boring Stuff with Python". I was entering the following code (which was the same as the book):
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
And I got a 'break outside loop' error. I found out that a break could only be used within loops.
Then I tried entering the following:
while True:
print('Please type your name.')
name = input()
while name == 'your name':
break
print('Thank you!')
But it didn't work, it kept asking for a name.
What do you think there was a mistake in the book or something?
Upvotes: 0
Views: 185
Reputation: 1
The code is correct. Until the if condition is satisfied, it will keep on asking you to type your name. Once the name you entered as input matches with the name in if condition, the loop will come to an end.
Input
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
Output
Please type your name.
hello
Please type your name.
hi
Please type your name.
your name
Thank you!
Upvotes: 0
Reputation: 258
Replace string your name with your actual name in if name == 'your name':
This name is what you enter as input, Since your input is not matching with if condition it will fail and break statement is never executed
while True:
print('Please type your name.')
name = input()
if name == 'ajay':
break
print('Thank you!')
Output
Please type your name.
ajay
Thank you!
Upvotes: 0
Reputation: 546
I think it's because of an indentation's mistake. copy & paste the code below and check if it solves your problem or not.
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
indentations are so critical in python programming. you should always check them precisely.
Upvotes: 0