简体   繁体   中英

Incorrect code is being called in 'if/elif/else' statement

I'm making an interest calculator that does compound and simple interest. However, the if statement always runs the simple interest script regardless of input.

I have tried changing variables to strings, integers, and floats. I have tried changing variable names, I have tried removing the first block of code entirely. What the heck is wrong with it???

start = input("simple or compound: ")

if start == "simple" or "Simple":
    a = float(input('Starting balance: '))
    b = float(input('Rate: '))
    c = int(input('Years: '))

    final = int(a+((a*b*c)/100))
    print(final)
elif start == "compound" or "Compound":
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final2 = int(d*(1+(e/100))**f)
    print(final2)
else:
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final3 = int(d*(1+(e/100))**f)
    print(final3)

If I input Starting balance as 5000, rate as 5, and years as six into simple it gives 6500. But the same result occurs when I call compound.

This expression is not correct:

start == "simple" or "Simple"

should be

start == "simple" or start "Simple"

code below worked:

start = input("simple or compound: ")

if start == "simple" or start == "Simple":
    # print("simple")
    a = float(input('Starting balance: '))
    b = float(input('Rate: '))
    c = int(input('Years: '))

    final = int(a+((a*b*c)/100))
    print(final)
elif start == "compound" or start == "Compound":
    # print("compound")
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final2 = int(d*(1+(e/100))**f)
    print(final2)
else:
    # print("unknown")
    d = float(input('Starting balance: '))
    e = float(input('Rate: '))
    f = int(input('Years: '))

    final3 = int(d*(1+(e/100))**f)
    print(final3)

Because of operator precedence

if start == "simple" or "Simple"

is evaluated as

if (start == "simple") or "Simple"

The (...) part is True if the user entered "simple", but the "Simple" part is always True.

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