(初学者问题)为什么我的格式化字符串不能正常工作?

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

我正在使用Vs Code软件来练习我的编码技巧。如果两项投入都高于100(收入)和70(信用评分),我试图让结果出来'是'。它似乎只担心信用评分的范围,而不是收入。因此,无论收入有多高或多低,它都只根据信用评分输入给出结果。任何人都可以指出我的代码中的任何错误?此外,没有语法错误提醒我任何错误。有人能搞清楚吗?

P.s我明白我可以用另一种方式编写代码,但我正在尝试使用格式化字符串,因为我认为从长远来看,当我开始更复杂的项目时,这将是有益的。我是编码的新手,所以我不确定格式化的字符串是否真的有必要,但我更喜欢它们。

customer_income = input("Annual Salary: ")
customer_credit = input("Credit Score?: ")

good_income = customer_income >= "100"
good_credit = customer_credit >= "70"

message = "Yes" if good_income and good_credit else "No"

print(message)

如果两项投入都高于100(收入)和70(信用评分),我试图让结果出来'是'。结果忽略收入输入,仅关注信用评分。但如果信用评分高于99,也会返回'否'。

python string visual-studio-code
3个回答
1
投票

哦,我知道,如果你使用int,你必须将它转换为input

customer_income = input("Annual Salary: ")
customer_credit = input("Credit Score?: ")

good_income = int(customer_income) >= 100
good_credit = int(customer_credit) >= 70

message = "Yes" if good_income and good_credit else "No"

print(message)

9970的输出是no,与10070yes


0
投票

您正在尝试比较字符串而不是整数。它将运行,但比较基于ASCII顺序。

while True:
    customer_income = input("Annual Salary: ")
    try:
        good_income = int(customer_income) >= 100
        break
    except ValueError:
        print('Please type a number.')

while True:
    customer_credit = input("Credit Score?: ")
    try:
        good_credit = int(customer_credit) >= 70
        break
    except ValueError:
        print('Please type a number.')

message = "Yes" if good_income and good_credit else "No"

print(message)

0
投票

您正在尝试比较字符串,而您实际期望的是比较这些字符串表示的ints。

因此,您需要使用int函数将这些字符串解析为int()

customer_income = input("Annual Salary: ")
customer_credit = input("Credit Score?: ")

good_income = int(customer_income) >= "100"
good_credit = int(customer_credit) >= "70"

message = "Yes" if good_income and good_credit else "No"

print(message)
© www.soinside.com 2019 - 2024. All rights reserved.