如何中断while循环? [蟒蛇]

时间:2020-06-22 05:45:08

标签: python loops while-loop

我想这样做,所以当您在while循环中输入数字值时,循环结束,程序也是如此。但是,当我键入“ break”时,我得到了一个无效的语法错误:(。对不起,不好的编码,这是我第一次。

print('Hello, world!')
print('What is your name?')
myName = input()
print('It is nice to met you, '+ myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge=input()
if myAge.isdigit():print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else: print('that is not a number. Lets try again, what is your age?')
C = 0
while (C<=3):
    myAge2=input()
    C+=1
    if myAge2.isdigit():print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
    break
    else: print('Try again')

3 个答案:

答案 0 :(得分:2)

缩进以应用正确的break

 if myAge2.isdigit():
    print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
    break
 else: 
    print('Try again')

答案 1 :(得分:0)

我尝试简化代码:

print('Hello, world!\nWhat is your name')
myName = input()
print('It is nice to met you, {}.\nThe length of your name is: {}'.format(myName, len(myName)))
print('What is your age?')
myAge=input()
if myAge.isdigit():
  print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else: 
  print('that is not a number. Lets try again, what is your age?')

myAge2=input()
while myAge2.isdigit():
  print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
  break
else:  
  print('Try again')

答案 2 :(得分:0)

代码缩进的问题,否则一切都会正常工作。

print('Hello, world!')
print('What is your name?')
myName = input()
print('It is nice to met you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge = input()
if myAge.isdigit():
    print('You will be ' + str(int(myAge) + 1) + ' in "one" year')
else:
    print('that is not a number. Lets try again, what is your age?')
C = 0
while (C <= 3):
    myAge2 = input()
    C += 1
    if myAge2.isdigit():
        print('You will be ' + str(int(myAge2) + 1) + ' in "one" year')
        break
    else:
        print('Try again')

Output