简体   繁体   中英

Python code not printing the desired result

I'm very new to Python, Just as a way of learning i tasked myself with this problem but no matter what i do the result still comes up to 100000 even when the value is less than the (first condition or second condition) and should print 200000. Please, help.

price = 1000000
credit_score = 300
income  = 70000


if credit_score and income:
    credit_score > 700 and income > 80000
    downpayment = price * 0.10
    print(f"Downpayment:  {downpayment}")
elif credit_score or income:
    credit_score < 700 or income < 80000
    downpayment = price * 0.20
    print(f"Downpayment:  {downpayment}")
else: 
    downpayment = price * 0.30
    print(f"Downpayment:  {downpayment}")

You're putting the conditions that you want to test after the if statements, not in them where they belong.

if credit_score > 700 and income > 80000:
    downpayment = price * 0.10
    print(f"Downpayment:  {downpayment}")
elif credit_score < 700 or income < 80000:
    downpayment = price * 0.20
    print(f"Downpayment:  {downpayment}")
else: 
    downpayment = price * 0.30
    print(f"Downpayment:  {downpayment}")

Instead of

if credit_score and income:
    credit_score > 700 and income > 80000

Do

if credit_score > 700 and income > 80000:

Putting a variable directly as the clause in an if statement (ie if credit_score ) tries to coerce that variable into a boolean. Any nonzero number or any non-empty string registers as true, which means your code is always taking the first branch.

Instead, what you should be doing is checking the condition credit_score > 700 and the condition income > 80000 .

I hope you're already clear about how it works now. I'll just provide another way of doing this:

downpayment = price * 0.10 if (credit_score > 700 and income > 80000) else (price * 0.20 if credit_score < 700 or income < 80000 else price * 0.30) 
print(f"Downpayment:  {downpayment}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM