python - 打印订单+总成本
问题描述
所以,我对 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')
如果有人可以给我任何提示以改进功能并使代码正常工作,那肯定会有所帮助。
解决方案
我假设您的代码中还有其他一些问题,格式与您发布的相同,并且您的脚本似乎没有输出 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')
推荐阅读
- sql-server - 如何在 Python 中将 Web 表单连接到 SQL Server?
- react-native-android - react-native-fbsdk 在 ios 端工作但在 android 端不工作 我已经完全设置了 facebook 应用程序
- r - 在 R 的 grep 函数中使用字符
- python - 如何在 Pyspark 中迭代数组(字符串)以检查 Null/Blank 值
- terraform - azurerm_function_app 上的 Terraform use_msi
- flutter - 设置状态后flutter_webview_plugin监听器(onHttpError)不起作用
- python - 如何在 pre_ hooks 中修改 python eve 请求
- logging - 根记录器级别和控制台处理程序级别
- video - 如何在 UWP WebView 中配置视频/音频自动播放策略?
- asp.net-core - Swagger Resolver 错误,无法解析参考: