python同时具有多个条件

时间:2015-12-15 19:18:14

标签: python loops

我是python 2.7的基本用户。我的查询就是这个

x = raw_input(...:)

if len(x) != 6

    re enter x

if x(1:2) < 0 or x(1:2) > 20

    re enter x 

if x(1:2) < 0 or x(1:2) > 20

    re enter x  

上述过程的问题在于它逐个检查条件。例如,如果在第3 if我输入4位而不是6位仍然是错误但不显示正确的错误。

我尝试在if语句存在的开头使用while循环,但是同样的问题出现了:它捕获错误但没有正确的错误消息。

我真的很感激任何帮助。我想要的是,无论我在哪里重新输入x,它都应该检查所有if语句。

3 个答案:

答案 0 :(得分:2)

从非常流畅的请求中我只能提取4件事;

你想:

  1. 在x满足条件之前应重新提示的输入x。
  2. x的长度应不同于6?
  3. 如果让x说123456,你想要2大于0且小于20吗?

    while True: #This is a while loop. True could be replaced with a boolean. But for now, we will keep it True to run until break. 
        x=raw_input() #Get some input
        if len(x) != 6 or 0<x[1:2]<20: #I used or because I don't know if you want both to be True, or 1 to be True, in order for the input to be invalid. Switch to and for both.      
            print "wrong please try again" 
            continue #Continue takes the code back to the beginning where we prompted for input. 
        else: #If the else is not satisfied...
            break #Break out of the loop and stock asking for input. 
    
  4. 您应该从自己的代码中学到一些东西:

    x = raw_input(...:)
    
    if len(x)!=6 #This one I understand, but still, should use while loop.
    
     re enter x #Unneccesary if you switch to while loop and use keyword continue. 
    
    if x(1:2)<0 or x(1:2)>20 #x(1:2) I am guessing you want to slice, you need [] not ()
    
    re enter x #Unneccesary if you switch to while loop and use keyword continue.
    
    if x(1:2)<0 or x(1:2)>20 #Why do you even have this here? Same as line above
    
    re enter x  #Unneccesary if you switch to while loop and use keyword continue.
    
    #Did you want your conditions to BOTH be True and reenter, or only 1? 
    #This is important for boolean logic. 
    #This is what determines if you will use AND or OR boolean operators. 
    

答案 1 :(得分:0)

只需使用if...else代码:

if condition_1:
    ...do something...
elif condition 2:
    ...do something else...
else:
    ...do something else again...

每次用户输入内容后,您都必须检查这些情况。

此外,您可以使用变量来检测valir输入:

valid = False
while valid == False:
    valid = True
    input = raw_input()
    if error_condition:
        valid = False
        ...do_something...

答案 2 :(得分:0)

使用any

while True:
    x = raw_input(prompt)
    if any([len(x) != 6, x[1:2] < 0,  x[1:2] > 20]):
        continue
    break