我的代码表现得很怪异,如果不告诉用户,它正在提取if语句的信息

时间:2019-07-09 18:04:33

标签: python python-3.x

我最近开始学习Python,并且经验非常好,但是,昨晚,我试图编写一个简单的程序,它的运行非常奇怪

我试图更改变量的位置以及它们存储/处理的内容,但我尝试的一切似乎都不起作用

def RF():

    user_type = input("Are you a new user? ")

    if user_type is "Yes" or "yes":
        ID = random.randrange(1, 999999)
        print("Your new ID Number is: " + str(ID))
        name = input("Please enter your name: ")
        password = input("Password: ")
        ID = input("Account ID: ")
        writtingID = open('Acc info.txt', 'w')

        writtingID.write("ID: " + str(ID) + " | NAME: " + name + " | PASS: " + password)
        writtingID.close()
    elif user_type is "No" or "no":
        name = input("Please enter your name: ")
        password = input("Password: ")
        ID = input("Account ID: ")


RF()

运行代码后,我希望它会直接跳到询问名称,但是当我键入“ No”或“ no”时,由于某种原因,它会从另一个{{1 }}声明

2 个答案:

答案 0 :(得分:1)


    user_type = input("Are you a new user? ")

    if user_type in ("Yes", "yes"):
        ID = random.randrange(1, 999999)
        print("Your new ID Number is: " + str(ID))
        name = input("Please enter your name: ")
        password = input("Password: ")
        ID = input("Account ID: ")
        writtingID = open('Acc info.txt', 'w')

        writtingID.write("ID: " + str(ID) + " | NAME: " + name + " | PASS: " + password)
        writtingID.close()
    elif user_type in ("No", "no"):
        name = input("Please enter your name: ")
        password = input("Password: ")
        ID = input("Account ID: ")


RF()

检查单词是否在元组中。对于更简单的方法,只需使用str.lower()方法即可消除额外的复杂性。

又名:

if user_type.lower() == "yes":
    code

请参见how to test multiple variables against a value

答案 1 :(得分:1)

语句 password => '<encrypted password>', 将始终返回true。

这样做的原因是该语句的评估方式与以下方式相同:

if user_type is "Yes" or "yes":

第二个括号(if (user_type is "Yes") or ("yes"): )将始终返回true。正如@ Error-SyntacticalRemorse指出的那样,您想使用"yes"而不是==(请参阅Is there a difference between "==" and "is"?)。

解决方案1:

is

解决方案2:

if user_type in ["Yes", "yes"]: