python - 'str' 对象不能解释为整数(Python 3.8)
问题描述
我知道这个问题之前已被多次问过,但我无法弄清楚我的代码存在什么问题以及如何解决它。
这是一个温度转换器
import sys
import time
print('This program will convert different units of temperature.')
unit1 = input('What unit do you want to convert from?\nAnswer with the letter C, F or K.\n')
unit2 = input('And what unit to?\nUse the same ruling as the previous question.\n')
temp1 = input('What temperature do you want to convert?.\n')
temp2 = 0
if unit1 == ('C'):
symbo1one = ('°C')
if unit1 == ('K'):
symbolone = ('°K')
if unit1 == ('F'):
symbolone = ('°F')
if unit2 == ('C'):
symbo12 = ('°C')
if unit2 == ('K'):
symbol2 = ('°K')
if unit2 == ('F'):
symbol2 = ('°F')
if unit1 == ('C') and unit2 == ('K'):
temp2 = ((int(temp1)) + 273.15)
unitname1 = ('Celsius')
unitname2 = ('Kelvin')
if unit1 == ('C') and unit2 == ('F'):
temp2 = ((int(temp1) * (9/5)) + 32)
unitname1 = ('Celsius')
unitname2 = ('Farhenheit')
if unit1 == ('K') and unit2 == ('C'):
temp2 = ((int(temp1)) - 273.15)
unitname1 = ('Kelvin')
unitname2 = ('Celsius')
if unit1 == ('K') and unit2 == ('F'):
temp2 = ((((int(temp1)) - 273.15) * (9/5)) + 32)
unitname1 = ('Kelvin')
unitname2 = ('Farhenheit')
if unit1 == ('F') and unit2 == ('C'):
temp2 = (((int(temp1)) + 32) * (5/9))
unitname1 = ('Farhenheit')
unitname2 = ('Celsius')
if unit1 == ('F') and unit2 == ('K'):
temp2 = ((((int(temp1)) + 32) * (5/9)) + 273.15)
unitname1 = ('Farhenheit')
unitname2 = ('Kelvin')
if unit1 == unit2:
temp2 = temp1
dp = ('To how many decimal places would you like your result given?')
print(('Original Temperature: ') + (str(temp1)) + (symbolone))
time.sleep(1)
print(('Converted Temperature: ') + (round(temp2, (dp))) + (symbol2))
time.sleep(10)
sys.exit()
它出现了错误:
File "C:\Users\rdmor\AppData\Local\Programs\Python\Python38\Temperature.py", line 59, in <module>
print(('Converted Temperature: ') + (round(temp2, (dp))) + (symbol2))
TypeError: 'str' object cannot be interpreted as an integer
我已经尽力了,而且我对编程还比较陌生,所以我们将不胜感激
解决方案
两件事情。在您的最后几行中,您忘记添加input
到您的dp
并且您无法round
为字符串添加值,因此您需要转换为字符串。
这将起作用
dp = int(input('To how many decimal places would you like your result given?'))
print(('Original Temperature: ') + (str(temp1)) + (symbolone))
time.sleep(1)
print(('Converted Temperature: ') + (str(round(temp2, (dp)))) + (symbol2))
推荐阅读
- java - 将图像上传到 Firebase
- android - 拇指图像略位于拇指左侧
- c# - Xamarin.Forms TimePicker 是否支持行为?
- python-3.x - 导入张量流时出错。DLL 加载失败
- android - 是否可以强制 AlertDialog 的按钮始终垂直显示?
- bash - Bash 脚本更改目录不返回这样的文件或目录
- swift - 如何在 Core Data 托管对象上跟踪“发送到实例的无法识别的选择器”
- android - Android ListView 回复其值
- delphi - 以编程方式更新 TListView 列标题?
- javascript - 为什么它输出未定义?