如何打破这个while循环?[python]

2024-09-30 04:40:28 发布

您现在位置:Python中文网/ 问答频道 /正文

当你在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')

Tags: nameyouinputageyourifiswhat
3条回答

我试图简化代码:

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')

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

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

缩进以应用正确的break

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

相关问题 更多 >

    热门问题