【问题标题】:Simple change calculator with while-loop validation带有 while 循环验证的简单更改计算器
【发布时间】:2021-01-23 02:34:03
【问题描述】:

我正在创建一个简单的零钱计算器。但是我不确定为什么我的 while 循环没有检查用户输入。我希望程序只接受 1 到 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)

谢谢!

【问题讨论】:

  • 应该是while total &gt; 100 or total &lt;= 0:。谢谢!
  • 绝对!谢谢!很好很容易修复。

标签: python function while-loop calculator


【解决方案1】:

您必须将 while 条件中的“and”更改为“or”,因为一个数字不能同时大于 100 和小于 1。

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)

【讨论】:

    【解决方案2】:

    您只需将“and”更改为“or”即可解决您的问题。

        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)
    

    【讨论】:

      猜你喜欢
      • 2014-05-27
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 2022-10-24
      • 2010-12-16
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多