Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - 'Break' outside loop

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?

question from:https://stackoverflow.com/questions/65940602/break-outside-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...