程序不会去"如果"声明

时间:2014-02-05 10:59:48

标签: python if-statement

在我的程序中,我允许用户获取随机生成的属性,或输入自己的属性。

当用户输入的数字大于20或小于0时​​,告诉用户他们输入的数字太大或太小,但不是。< / p>

这是我的代码,主要关注我所说的部分。

if random_var2 == "yes": #if yes
    c2strength = random.randrange(1,20) #randomly generated
    c2skill = random.randrange(1,20)

    print(character2 + ", your strength is: ", c2strength, " and your skill is: ", c2skill) #print out attributes
elif random_var2 == "no": #else
    c2strength = int(input("Enter Strength attribute. Between 1 and 20: ")) #user inputs attributes between 1 and 20
    c2skill = int(input("Enter Skill attribute. Between 1 and 20: "))

    if c2strength < 1 and c2strength > 20: #checks to see if it's in bounds #HERE
        print("Please enter an attribute that is between 1 and 20. ")
        var()
    else: #if it is
        pass
    if c2skill < 1 and c2skill > 20:
        print("Please enter an attribute that is between 1 and 20. ")
        var()

有什么问题?

由于

3 个答案:

答案 0 :(得分:6)

您想要or,而不是and:变量可以小于1,大于20.绝不能同时使用。

答案 1 :(得分:3)

if c2strength < 1 and c2strength > 20if c2skill < 1 and c2skill > 20:

将测试两个条件,并且没有小于1且大于20的数字。因此,更改它or,当一个条件成功时,它将被短路。

段:

>>> -2 < 1 and -2 > 20
False
>>> -2 < 1 or -2 > 20
True
>>>

答案 2 :(得分:0)

我认为问题出在逻辑上..请试试这个

    if c2strength < 1 or c2strength > 20: #checks to see if it's in bounds #HERE
        print("Please enter an attribute that is between 1 and 20. ")
        var()
    if c2skill < 1 or c2skill > 20:
        print("Please enter an attribute that is between 1 and 20. ")
        var()