伙计们和女孩们, 我刚开始学习使用python进行编码,并且正在构建一个非常基本的百分比计算器,以使思维方式发生变化。
我在运行程序成功通过时遇到问题:
#Percentage Calculator
print('Enter value of percent: ') #prompt user for input of percent value
percent = input() #gain user input about percent *stored as 'str'
percent = int(percent) #store and convert user input into an 'int' from 'str' for use in line 11
print('Enter value of percentaged number: ') #prompt user for input of percentaged number value
percentagedNum = input() #gain user input on percentaged number *stored as 'str'
percentagedNum = int(percentagedNum) #store and convert value from 'str' into 'int'
answer = percent / percentagedNum #calculate percentage formula
print(percent + '% of ' + percentagedNum + ' is ' + answer) #prompt user with answer
此外,回溯:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1438, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Custom/PycharmProjects/PercentageCalculator/main", line 12, in <module>
print(percent + '% of ' + percentagedNum + ' is ' + answer)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我觉得这是在最终的print()函数调用中混合使用字符串,整数和浮点数的连接问题。
对此深表感谢,非常感谢,感谢你们为帮助社区所做的一切。很多爱。
答案 0 :(得分:1)
您需要首先将数字转换为字符串。您可以明确地做到这一点:
print(str(percent) + '% of ' + str(percentagedNum) + ' is ' + str(answer))
或者您可以让Python f字符串来处理它:
print(f'{percent} % of {percentagedNum} is {answer}')
您尝试的操作不起作用的原因是+
运算符根据给出的内容而得出不同的结果。如果两侧都有字符串,则将其串联:
>>> "foo" + "bar"
"foobar"
如果两边都有整数,则将它们相加:
>>> 5 + 3
8
混合输入类型时,不确定应该做什么。
答案 1 :(得分:0)
在您的print
语句中,确保使用str()
:str(percent)
等将包含数字的变量转换为字符串。
实际上,这是开始使用Python时的经典错误。