【问题标题】:Error Message: TypeError: unsupported operand type(s) for -: 'str' and 'float' [closed]错误消息:TypeError:不支持的操作数类型 -:'str' 和 'float' [关闭]
【发布时间】:2014-12-18 05:39:57
【问题描述】:

我正在为我的 GCSE 课程编写一个程序,它的工作原理类似于自动售货机。我试图从重写的变量中减去一个变量,但由于某种原因它不起作用。帮忙?

This is my code:
credit=raw_input("Please input your change, CAREFUL! This Machine only accepts 10p,20p,50p and £1: ")
list1= ["1", "2", "3", "4", "5"]
price1=0.65
price2=0.70
price3=0.50
price4=0.70
price5=0.80
while (credit) == 0:
   (credit)=raw_input("Please input your change: ")
products = (" 1) Kinder Bueno\n 2) Doritos Chilli Heatwave\n 3) Nestle Yorkie Bar\n 4) Coca Cola(Can)\n 5) Volvic Stawberry Water")
print (credit)
print ("The product selection is the following")
print (products)
(selection)=raw_input("Please select a product: ")
if (selection) == (list1[0]):
   (new_credit)=int(credit-price1)
   print (new_credit)

【问题讨论】:

    标签: python python-2.7 typeerror


    【解决方案1】:

    在 python 中,你所有的 ( ) 都是多余的,我相信你真正的意思是。

    credit = raw_input("Please input your change, CAREFUL! This Machine only accepts 10p,20p,50p and £1: ")
    list1= ["1", "2", "3", "4", "5"]
    price1 = 0.65
    price2 = 0.70
    price3 = 0.50
    price4 = 0.70
    price5 = 0.80
    while credit == 0:
       credit = raw_input("Please input your change: ")
    products = " 1) Kinder Bueno\n 2) Doritos Chilli Heatwave\n 3) Nestle Yorkie Bar\n 4) Coca Cola(Can)\n 5) Volvic Stawberry Water"
    print credit
    print "The product selection is the following"
    print products
    selection = raw_input("Please select a product: ")
    if selection == list1[0]:
       new_credit = int(credit) - price1  # NOTE THE CHANGE HERE :)
       print new_credit
    

    请注意上面的更改(除了删除多余的括号)。演员应该只关注功劳,而不是功劳不计价格。

    注意

    为了与 Python3 兼容,可能值得将括号放入您的 print 语句(因为 print 现在是一个函数),但对于 if / else / while 等控制流语句绝对不需要它们

    【讨论】:

    • 非常感谢 :) 对这类东西的新手,但这是一个很大的帮助谢谢。
    • @BradleyOnyett 太棒了,如果这有帮助,请不要忘记投票/标记为答案:) 以便其他人可以找到它!
    • 我想知道您是否可以再次帮助我编写代码,因为我遇到了另一个问题?
    • @BradleyOnyett 如果您愿意,可以发布另一个问题并将其链接到此处或类似内容。这样其他有类似问题的人可以提供帮助。
    • 问题是,我被限制每 90 分钟 1 个问题,所以我需要帮助。
    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2022-12-03
    • 2019-01-27
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多