简体   繁体   中英

Simple change calculator with while-loop validation

I am creating a simple change calculator. However I am not certain why my while loop is not checking the user input. I would like the program to only accept numbers between 1 and 99.

    total = int(input('How much change do you need? '))
    while total > 100 and total <= 0:
        print('The change must be between 1 cent and 99 cents.')
        total = int(input('How much change do you need? '))


    def change(total):
        print(total//25, 'Quarters')
        total = total%25
        print(total//10, 'Dimes')
        total = total%10
        print(total//5, 'Nickels')
        total = total%5
        print(total//1, 'Pennies')

    change(total)

Thank you!

You must change the "and" in your while conditional to "or" because a number cannot be greater than 100 and less than 1 at the same time.

total = int(input('How much change do you need? '))
while total > 100 or total <= 0:
    print('The change must be between 1 cent and 99 cents.')
    total = int(input('How much change do you need? '))


def change(total):
    print(total//25, 'Quarters')
    total = total%25
    print(total//10, 'Dimes')
    total = total%10
    print(total//5, 'Nickels')
    total = total%5
    print(total//1, 'Pennies')

change(total)

You just have to change "and" to "or" and you will solve your problem.

    total = int(input('How much change do you need? '))
while total > 100 or total <= 0:
    print('The change must be between 1 cent and 99 cents.')
    total = int(input('How much change do you need? '))


def change(total):
    print(total//25, 'Quarters')
    total = total%25
    print(total//10, 'Dimes')
    total = total%10
    print(total//5, 'Nickels')
    total = total%5
    print(total//1, 'Pennies')

change(total)

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