python中的输入语句

2024-09-29 05:22:27 发布

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

我正在学习python。我创建了一个与贷款相关的简单应用程序。问题陈述是这样的

If the applicant has a high income and good credit, he/she is eligible for a loan. Else not. Here is the code

has_high_income = input("Is your income high (Y/N): ")
has_good_credit = input("Is your good credit (Y/N): ")

if has_high_income and has_good_credit == "Y":
    print("Eligible for the loan")
else:
    print("Not eligible for a loan")

如果我在这两种情况下都做Y,那么它将显示我有资格获得贷款,这是正确的。如果我做了第一个Y和第二个N,则表明我没有资格获得贷款,这也是正确的,但当我做了第一个N和第二个Y,则表明我有资格获得贷款,这应该是不正确的。请告诉我我在代码中做错了什么。如果你能解决我的问题,我将非常高兴


Tags: andtheforinputishasgoodcredit
3条回答

您需要确保检查两个输入,而不是一个输入

你什么时候有这个密码

if has_high_income and has_good_credit == "Y":
    print("Eligible for the loan")

如果第一个检查if has_high_incomeTrue而不是内容为==“Y”,则会检查它


has_high_income = input("Is your income high (Y/N): ")
has_good_credit = input("Is your good credit (Y/N): ")

if has_high_income == "Y" and has_good_credit == "Y":
    print("Eligible for the loan")
else:
    print("Not eligible for a loan")

在python中,当您有如下语句时:

if has_high_income and has_good_credit == "Y":

您在这里检查两个语句:

if has_high_income:

if has_good_credit == "Y":

当您检查没有等号的if语句时,您正在检查该变量是否不等于零,换句话说,任何非空值都将返回true。在另一种情况下,它正常检查等式

另一件需要记住的事情是,“and”关键字将它们转换为两个完全独立的语句,换句话说,您不能执行以下操作:

if thisVariable > 10 and < 50:

但你必须做到:

if thisVariable > 10 and thisVariable < 50

您需要检查两个变量是否都等于“Y”。现在,您正在检查has_good_credit是否等于“Y”,以及has_high_income是否为“true”。即使它等于“N”,它也是

这是正确的代码:

has_high_income = input("Is your income high (Y/N): ")
has_good_credit = input("Is your good credit (Y/N): ")

if has_high_income == "Y" and has_good_credit == "Y":
    print("Eligible for the loan")
else:
    print("Not eligible for a loan")

只要字符串变量不是空的,它就是真的。因为您将“N”放在has_high_income中,所以它不是空的,因此是真的

这就是为什么bool(高收入)会回归现实

相关问题 更多 >