程序不去“如果”的州

2024-10-05 14:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的程序中,我允许用户要么获得随机生成的属性,要么输入自己的属性。你知道吗

当用户输入一个大于20或小于0的数字时,它应该告诉用户他们输入的数字太大或太小,但事实并非如此

这是我的代码,主要集中在我说过的部分。你知道吗

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()

有什么问题?你知道吗

谢谢


Tags: and用户if属性isattribute数字random
3条回答

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

    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()

您想要的是or,而不是and:变量可以小于1,大于20。决不能两者同时发生。你知道吗

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
>>>

相关问题 更多 >