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

时间:2019-04-24 23:50:15

标签: python string visual-studio-code

我正在使用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,也会返回“否”。

3 个答案:

答案 0 :(得分: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,带有10070的输出是yes

答案 1 :(得分: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)

答案 2 :(得分:0)

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

因此,您需要使用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)