2016-12-20 33 views
0

问题出在标题中:你如何转到else部分的if语句的开头?你如何去到else部分的if语句的开始处? Python 3.2

代码:循环中的

p1 = int(input()) 
if p1 <= 9 and p1 >= 1: 
    pass 
else: 
    print('ERROR 404. Invalid input. Please try again.') 
    p1 = input() 
+1

听起来像你需要'循环'? – corn3lius

+1

我通常在这种情况下使用循环。如果输入有效继续。其他循环。我不认为你可以像Python中的goto一样在python中跳转语句 –

回答

5

运行,从不打出来,直到输入符合标准。

while True: 
    p1 = int(input("input something: ")) 
    if p1 <= 9 and p1 >= 1: 
     break 

    print('ERROR 404. Invalid input. Please try again.') 

如果输入无法转换为int和终止程序的值。此代码会抛出异常。

为了避免这种情况发生,并继续进行。

while True: 
    try: 
     p1 = int(input("input something: ")) 

     if p1 <= 9 and p1 >= 1: 
      break 
    except ValueError: 
     pass 

    print('ERROR 404. Invalid input. Please try again.')