【问题标题】:Python- need to calculate a cost based on user inputPython-需要根据用户输入计算成本
【发布时间】:2019-09-21 19:05:31
【问题描述】:

我需要根据用户输入和使用数组来计算成本。我有以下代码,但不断收到错误(指向我的“打印”括号)。

您知道我可能缺少什么,以及是否可以使用更好的数组吗?

#route type
yourUserInput = input("will you use route 1 or 2 ")

finance = 1 #
if yourUserInput == "1":
    finance = 25
elif yourUserInput == "2":
    finance = 35
else:
    print("you did not enter a valid route")

print ("total cost" (cost))
# ticket type
tickettype = input("what type of ticket would you like (single or return) ")
price = 1 #
if tickettype == "single" or tickettype == "Single":
    price = 25
elif tickettype == "return" or tickettype == "Return":
    price = 35
else:
    print("you did not enter a valid ticket type")

#cost = int( finance ) *int( price )


ar= (finance + price)
#print "the total is therefore",
print ("your total price is" int(ar))

input("press enter to exit the program")

【问题讨论】:

  • print() 语句中缺少逗号。
  • 数组在哪里?无论如何,请尝试: print ("your total price is", ar) 即在要打印的字符串和变量之间缺少逗号。
  • 如何添加数组?
  • 您应该 read this article 了解如何在 Python 中打印字符串。

标签: python arrays input calculator


【解决方案1】:

在 Python 中,当您想在输出中包含多个变量或文本时,可以使用逗号 (,) 将其添加到输出语句中。它类似于在 Java 中在输出语句中添加 + 的方式。

print ("total cost" (cost)) 应该 print ("total cost", cost)print ("your total price is" int(ar)) 应该 print ("your total price is", int(ar))

在您的代码中实现一个数组看起来像这样,其中数组中的两个值是 25 和 35。

yourUserInput = input("will you use route 1 or 2 ")

cost = 1
finance = 1
price = 1
list_values = [25,35]

if yourUserInput == "1":
    finance = list_values[0]
elif yourUserInput == "2":
    finance = list_values[1]
else:
    print("you did not enter a valid route")

print ("total cost = ", cost)
# ticket type
tickettype = input("what type of ticket would you like (single or return) ")

if tickettype == "single" or tickettype == "Single":
    price = list_values[0]
elif tickettype == "return" or tickettype == "Return":
    price = list_values[1]
else:
    print("you did not enter a valid ticket type")

cost = finance * price
ar = (finance + price)

#print "the total is therefore",
print ("your total price is", ar)

input("press enter to exit the program")

我鼓励您阅读 https://docs.python.org/3/whatsnew/3.0.html 以更好地了解 Python 基础知识。

【讨论】:

  • 您需要在程序中定义成本。它没有设置任何东西,所以你会得到一个错误。
  • 谢谢!!你或许知道我的第二个问题的答案(如何将数组嵌入到这段代码中)
  • Python 中的数组和列表是可以互换的,但您只需编写 this_list = [] 即可对其进行初始化,其中方括号将自动指示您希望创建和编辑列表。您可以使用其索引访问列表中的项目,例如this_list[index] 这是用于阅读数据结构的文档:docs.python.org/3/tutorial/datastructures.html
  • 我会在哪里实现 this_list = [] 在该代码中?是否有类似的现有示例我可以效仿?
  • 理想情况下,我尝试实现一个“sum”数组,但遇到了不断的错误。我确实尝试过发布另一个单独的问题,但无法这样做。
猜你喜欢
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多