Python用户名、密码if-else嵌套问题

问题描述 投票:0回答:2

我正在学习Python并且有一个任务要解决。 在任务中写道,代码应该如下所示:

if [selection]:
    [code]
    
    if [selection]:
        [code]
    else:
        [code}
else:
    [code]

输出应该是:

Give name: Peter
The given name is wrong.

Give name: John
Give password: Monkeys?
The password is incorrect.

Give name: John
Give password: ABC123
Both inputs are correct!

到目前为止,我想出的最好的办法是:

name = input("Give name:")
password = input("Give password:")
if name == "John":
    if password == "ABC123":
        print("Both inputs are correct!")
    else:
        print("The given password is incorrect.")
else:
    print("The given name is wrong.")

但是到目前为止,当我输入正确的数据时,一切正常,但如果我输入错误的名称,它不会告诉我名称错误,而是立即要求输入密码,然后告诉我名称错误。它应该立即告诉我该名称是错误的,如果正确则继续要求输入密码。到目前为止,教程并没有真正帮助我。

python-3.x if-statement nested
2个回答
1
投票

你应该多花一点时间了解 python 代码是如何运行的,顺便说一句

name = input("Give name:")
if name == "John":
    password = input("Give password:")
    if password == "ABC123":
        print("Both inputs are correct!")
    else:
        print("The given password is incorrect.")
else:
    print("The given name is wrong.")


0
投票

A = 某物 如果 A == “某物”: 打印(“欢迎”) 别的: print("错误陈述")

© www.soinside.com 2019 - 2024. All rights reserved.