首页 > 解决方案 > 打印订单+总成本

问题描述

所以,我对 Python 还是很陌生,但是我遇到了很大的麻烦,因为随着代码的移动,它不再打印出总数。因此,在要求三明治并输入三个选项之一之后,它直接进入下一个问题。我不明白它为什么这样做......但我的代码的开头看起来像这样。

order = ("**** YOUR ORDER INCLUDES \n ")
totalCost = 0.00
comboStatus = 0

这基本上就是三明治、饮料和薯条每个部分的样子。

while true:
    sandChoice = input("Select your sandwich! Please enter 1, 2, or 3.")
    if sandChoice not in ('1', '2', '3'):
       print("Your response is invalid. Try again.")
    else:
        sandChoice = str(sandChoice)
        break

if (sandChoice == 1):
    print("You chose Chicken!")
    totalCost += 5.25
    print("Your total is now $" + str(totalCost))
    order += ("CHICKEN SANDWICH  \n")
    comboStatus += 1

if (sandChoice == 2):
    print("You chose Tofu!")
    totalCost += 5.75
    print("Your total is now $" + str(totalCost))
    order += ("TOFU SANDWICH \n")
    comboStatus += 1 

if (sandChoice == 3):
    print("You chose Steak!")
    totalCost += 6.25
    print("Your total is now $" + str(totalCost,2))
    order += ("STEAK SANDWICH \n")
    comboStatus += 1

但是最后,这就是我的代码的样子

print('The total cost of your order is $' + str(totalCost) + '. \n')

如果有人可以给我任何提示以改进功能并使代码正常工作,那肯定会有所帮助。

标签: python

解决方案


我假设您的代码中还有其他一些问题,格式与您发布的相同,并且您的脚本似乎没有输出 if 语句中提供的答案。

发生这种情况的原因是,在有效答案的情况下,您已指定 that sandChoice = str(sandChoice),从而将其转换为string。但是,在您的 if 语句中,您将 sandChoice 与integer进行比较。

记住'1'不等于1

要解决它,sandChoice = int(sandChoice)请在 if 语句中设置或比较字符串,例如:if (sandChoice == '1'):

在下面找到您发布的总代码的工作版本

order = ("**** YOUR ORDER INCLUDES \n ")
totalCost = 0.00
comboStatus = 0

while True:
    sandChoice = input("Select your sandwich! Please enter 1, 2, or 3.")
    if sandChoice not in ('1', '2', '3'):
       print("Your response is invalid. Try again.")
    else:
        sandChoice = int(sandChoice)
        break

if (sandChoice == 1):
    print("You chose Chicken!")
    totalCost += 5.25
    print("Your total is now $" + str(totalCost))
    order += ("CHICKEN SANDWICH  \n")
    comboStatus += 1
if (sandChoice == 2):
    print("You chose Tofu!")
    totalCost += 5.75
    print("Your total is now $" + str(totalCost))
    order += ("TOFU SANDWICH \n")
    comboStatus += 1 
if (sandChoice == 3):
    print("You chose Steak!")
    totalCost += 6.25
    print("Your total is now $" + str(totalCost,2))
    order += ("STEAK SANDWICH \n")
    comboStatus += 1

print('The total cost of your order is $' + str(totalCost) + '. \n')

推荐阅读