'and' operator troubleshoot

Hi all, can anyone explain how this while loop is ending before both conditions = True?
I thought both had to be true but;

example: desired_fuel = 2.95 but the output stops at 0.95 instead of 2.95

cents = 0
dollar = 0

desired_fuel = float(input("Enter how much petrol you would like in dollars and cents: $"))
print("Desired fuel: ", desired_fuel)

target_cents = (desired_fuel * 100) % 100
target_dollars = desired_fuel // 1

while dollar < target_dollars and cents < target_cents:
    cents += 1
    if cents == 99:
        dollar += 1
        cents = 0

    print(f"${dollar}.{cents}")

As soon as you reach the condition of

95      <     95     == false
cents < target_cents == false

the while loop ends even though “dollar < targetValue” is still true. This is because the “and” operator requires BOTH conditions to be met in order to continue the loop.

Most likely you will need a “total” counter and check “total < target_total” as your while condition

It’s amazing how stepping away for an hour and going for a walk can really help. I’m sure it could more simple but at least it’s working now (sort of). Thanks for the feedback.

cents = 0
dollar = 0

desired_fuel = float(input("Enter how much petrol you would like in dollars and cents: $"))

target_cents = (desired_fuel * 100)  % 100
target_dollars = desired_fuel // 1

while dollar < target_dollars:

    cents += 1
    if cents == 100:
        dollar += 1
        cents = 0
    print(f"${dollar}.{cents}")

    while cents < target_cents:
        cents += 1
        print(f"${dollar}.{cents}")

Could also try this - (includes some bug fixes):

cents = 0
dollar = 0
total = 0

desired_fuel = float(input("Enter how much petrol you would like in dollars and cents: $"))
print("Desired fuel: ", desired_fuel)

target_cents = (desired_fuel * 100) % 100
target_dollars = desired_fuel // 1
target_total = target_dollars * 100 + target_cents

while total < target_total:
    total += 1
    cents += 1
    if cents == 100:
        dollar += 1
        cents = 0

    print(f"${dollar}.{str(cents).zfill(2)}")
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.