【问题标题】:Not sure what my problem is, input variables cannot proceed [closed]不知道我的问题是什么,输入变量无法继续[关闭]
【发布时间】:2020-04-28 18:10:30
【问题描述】:

我还是 Python 和编程以及 StackOverflow 的新手,请原谅我缺乏正确的编码词汇。我的问题是下面的代码。我可以很好地运行两个 while True 循环,但是一旦它到达注释 #PROBLEM STARTS HERE 下的代码,我不知道我到底做错了什么。我收到的错误消息是 unsupported operand type(s) for /: 'str' and 'int'

gameName = str(input('Enter game title: '))

while True:
    basePrice = input('Enter the base price: ')
    try:
        check = float(basePrice)
        break
    except ValueError:
        print('Please enter a valid price.')
    continue

while True:
    discountPtg = input('Enter the discount(%): ')
    try:
        check = float(discountPtg)
        break
    except ValueError:
        print ('Please enter just a number for your discount.')

#PROBLEM STARTS HERE    
disctdPrice = (discountPtg / 100) * basePrice

savedCost = basePrice - disctdPrice

print ('\nSTATS\n')

print (gameName)
print ('Base price: RM' + str(basePrice))
print ('Discount: ' + str(discountPtg) + '%')
print ('Discounted price: ' + str(disctdPrice))
print ('You saved: ' + str(savedCost))

任何帮助将不胜感激。

【问题讨论】:

  • 这能回答你的问题吗? How can I read inputs as numbers?
  • 你知道discountPtg是一个字符串(因为你在赋值给check时将它转换为float),那你为什么在算术表达式中使用它呢?
  • 你需要做:basePrice = float(basePrice) and discountPtg = float(discountPtg)

标签: python python-3.x input floating-point int


【解决方案1】:

您检查了它是否是一个数字,但您从未将其转换为一个。在这一行:

disctdPrice = (discountPtg / 100) * basePrice

DicountPtg 应该变成这样的浮点数:

disctdPrice = (float(discountPtg) / 100) * basePrice

【讨论】:

  • 谢谢,我已经根据您的回复进行了一些修复。它们如下:```disctdPrice = (float(discountPtg)/100) * float(basePrice) savedCost = float(basePrice) - float(disctdPrice) ```
【解决方案2】:

谢谢大家。我通过这些修改弄明白了:

disctdPrice = (float(discountPtg)/100) * float(basePrice)
savedCost = float(basePrice) - float(disctdPrice)

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2012-05-20
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多