如何在 Python 中使用 except AssertionError 在 while 循环中继续工作

How to work with continue in a while loop with except AssertionError in Python

大家好,我需要一些帮助。

我正在做这个练习。我需要什么以及发生了什么?

当我进入 except ValueError 循环回到开头时,我不一定需要向它写入 continue发生了,好吧(这是一个愿望)。

但是当我进入 except AssertionError 时,无论我是否写入 continue,循环都会停止,这就是问题所在.当我进入 except AssertionError.

时,我需要循环回到开头

你能帮帮我吗?

prompt="\nWould you like to get a ticket?"  
prompt+="\nPlease write your age: "

age= 0    
while age >= 0:


try:       
    age=int(input(prompt))
    assert age > 0             
  
except ValueError:
    print(f"This option is not valid. You need to input an integer number. Try it again.")
   
    
except AssertionError: 
    print("Wow that can't be possible!! Try it again")
    continue
        
           
else:      
    
                
    if age >= 0 and age <3:
        print(f"You are {age} years old, your ticket is free!")
        break        
        
    elif age >=3 and age<=12:
        print(f"You are {age} years old, your ticket price is .")
        break 
        
    elif age > 75 and age <121:        
        print(f"You are {age} years old, your ticket price is .")
        break
   
    else:
        print(f"You are {age} years old, your ticket price is .")
        break
  
finally:
    print("Fim da execução")

==============

输出

你想买票吗?
请写下您的年龄:一
此选项无效。您需要输入一个整数。再试一次。
Fim da execução

你想买票吗?
请填写您的年龄:-45
哇,这不可能!再试一次
Fim da execução

==============

我的循环到此停止
但我需要它再次询问我:

你想买票吗?
请写下您的年龄:

您的 while 循环终止条件是倒退的,您对 finally 的使用似乎不合适,并且您确实需要在 except 块之后使用 continue 语句。但是,总的来说,你们非常接近。下面的示例修复了您遇到的问题,但尽量保持整体逻辑与您所​​遇到的相同。

编辑:意识到您在成功处理每个案例后都在使用 break,因此无需使用基于年龄的 while 循环条件。

示例:

prompt="\nWould you like to get a ticket?"
prompt+="\nPlease write your age: "

while True:

    try:       
        age = int(input(prompt))
        assert age > 0             
  
    except ValueError:
        print(f"This option is not valid. You need to input an integer number. Try it again.")
        continue

    except AssertionError: 
        print("Wow that can't be possible!! Try it again")
        continue
                    
    if age >= 0 and age <3:
        print(f"You are {age} years old, your ticket is free!")
        break        
        
    elif age >=3 and age<=12:
        print(f"You are {age} years old, your ticket price is .")
        break 
        
    elif age > 75 and age <121:        
        print(f"You are {age} years old, your ticket price is .")
        break
   
    else:
        print(f"You are {age} years old, your ticket price is .")
        break
  
print("Fim da execução")

输出:

Would you like to get a ticket?
Please write your age:  one
This option is not valid. You need to input an integer number. Try it again.

Would you like to get a ticket?
Please write your age:  -45
Wow that can't be possible!! Try it again

Would you like to get a ticket?
Please write your age:  10
You are 10 years old, your ticket price is .
Fim da execução