简体   繁体   English

If 语句未按预期工作 (Python)

[英]If statement not working as intended (Python)

This code I wrote for my study on if statements in Python doesn't seem to work properly since it asks the same question twice after the first one being asked.我为研究 Python 中的 if 语句而编写的这段代码似乎无法正常工作,因为它在第一个问题被问到之后又问了两次相同的问题。

Identity = input("Who are you? ")

if Identity == "Jane":
    print("You must be John's sister.")
elif Identity != "John":
    print("My database doesn't recognise you. Who are you I wonder...")
elif Identity == "John":
    if input("What is your last name? ") != "Travolta":
        print("False! John's name is Travolta and not " + input("What is your last name? ") + ".")
    elif input("How old are you? ") == "Travolta":
        if input("How old are you? ") != "20 yo":
            print("False! John is 20 yo and not " + input("How old are you? ") + ".")
        elif input("How old are you? ") == "20 yo":
            print("You must in fact be John!")
if input("What is your last name? ") != "Travolta":
    print("False! John's name is Travolta and not " + input("What is your last name? ") + ".")

Here you aren't storing the value of the input and printing it.在这里您没有存储输入的值并打印它。 You are asking the person to input again "what is your last name?".您要求此人再次输入“您的姓氏是什么?”。

Do something like做类似的事情

last_name = input("What is your last name? ")

and use it instead of the input() in the if statement.并使用它代替 if 语句中的 input() 。

Here I am putting the snippet in the way I would've done it.在这里,我按照我会做的方式放置片段。

identity = input("Who are you? ")

if identity == "Jane":
    print("You must be John's sister.")
elif identity != "John":
    print("My database doesn't recognise you. Who are you I wonder...")
elif identity == "John":
    last_name = input("What is your last name? ")
    if last_name != "Travolta":
        print("False! John's last name is Travolta and not " + last_name + ".")
    else:
        age = input("How old are you? ")
        if age != "20 yo":
            print("False! John is 20 yo and not " + age + ".")
        else:
            print("You must in fact be John!")

It is working properly for every possibility.它适用于各种可能性。 Examples:例子:

简输入

约翰满

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM