如何使用if-else检查两个变量的值,如果其中一个错误,打印出哪个变量错误?

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

在任务中写道,代码应该如下所示:

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 python-3.x if-statement nested-if
2个回答
1
投票

外部

if
应检查
name
,然后内部
if
应检查密码。

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.")

-1
投票

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

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