簡體   English   中英

如何打破這個while循環? [Python]

[英]How do I break this while loop? [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')

縮進以應用正確的break

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

我嘗試簡化代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM