在python的while循环中使用if语句?

2024-10-01 02:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自动售货机的问题,用户有3个选择:

  1. 水2。可乐3。佳得乐

    水=1.00美元,可乐=1.50美元,佳得乐=2.00美元

在从用户那里输入了25美分、10美分、5美分和5美分之后,我用美元计算了总数。现在我要检查三种饮料的总量是否足够。如果金额小于成本,我需要提示用户再试一次,如果金额大于,那么我需要显示一条消息,显示用户的更改金额。我相信这需要while循环和if,elif,else语句。以下是我目前的计划:

import sys 
print('You have three drinks to choose from this Vending Machine: \n 1. Water \n 2. Cola \n 3. Gatorade')
water = 1.00
cola = 1.50
gatorade = 2.00
choice = 0
while not choice:
  try:
    choice = int(input('Please select any one of the three choices of drinks (1,2 or 3) from the list above'))
    if choice not in (1,2,3):
        raise ValueError
  except ValueError:
    choice = 0
    print("That is not a valid choice ! Try again")
if choice == 1:
   print("1. water = $1.00")
elif choice == 2:
   print("2. cola = $1.50")
elif choice == 3:
   print("3. gatorade = $2.00")

qrt = int(input("How many quarters did you insert ?"))
dm = int(input("How many dimes did you insert ?"))
nk = int(input("How many nickels did you insert ?"))
pn = int(input("How many pennies did you insert ?"))

total = qrt/4 + dm/10 + nk/20 + pn/100

现在,我需要检查总量(用户插入的)是否大于或小于他选择的饮料的成本。你知道吗

如果更大,我需要返回更改(显示更改金额的消息)。你知道吗

如果较小,那么我需要提示用户再次尝试插入硬币。你知道吗

我该怎么做?你知道吗


Tags: 用户youinputifnot金额manyhow
1条回答
网友
1楼 · 发布于 2024-10-01 02:34:15

我想这就是你需要做的。也可以根据您的需求使用逻辑并修改代码。你知道吗

别照搬。希望有帮助。你知道吗

import sys 
print('You have three drinks to choose from this Vending Machine: \n 1. Water \n 2. Cola \n 3. Gatorade')
water = 1.00
cola = 1.50
gatorade = 2.00
choice = 0
while not choice:
    try:
        choice = int(input('Please select any one of the three choices of drinks (1,2 or 3) from the list above: '))
        if choice not in (1,2,3):
            raise ValueError
    except ValueError:
        choice = 0
        print("That is not a valid choice ! Try again")

if choice == 1:
    print("1. water = $1.00")
    total_to_be = 1.00
elif choice == 2:
    print("2. cola = $1.50")
    total_to_be = 1.50
elif choice == 3:
    print("3. gatorade = $2.00")
    total_to_be = 2.00

qrt = int(input("How many quarters did you insert ?"))
dm = int(input("How many dimes did you insert ?"))
nk = int(input("How many nickels did you insert ?"))
pn = int(input("How many pennies did you insert ?"))

total = qrt/4 + dm/10 + nk/20 + pn/100

# total = round(total, 2)

while total != total_to_be: 

    if total >= total_to_be:
        print(total)
        break

    else:
        print("======================= Please try Again ================================")
        qrt = int(input("How many quarters did you insert ?"))
        dm = int(input("How many dimes did you insert ?"))
        nk = int(input("How many nickels did you insert ?"))
        pn = int(input("How many pennies did you insert ?"))

        total = qrt/4 + dm/10 + nk/20 + pn/100

相关问题 更多 >