【发布时间】:2020-11-11 10:47:38
【问题描述】:
我目前正在编写一个简单的温度转换程序,需要满足以下条件:
- 检查用户输入的是摄氏温度还是华氏温度
- 接受大写或小写的指定值(例如,c 或 C 代表摄氏温度)
- 如果用户未输入摄氏度或华氏度,则打印错误消息
- 转换为备用
- 打印值,指定是摄氏度还是华氏度
目前一切正常,除了打印出错误消息。例如,我只是输入 0 而没有温度约定。程序只显示: degree = int(temp[:-1]) #所有字符串,除了最后一个字符 ValueError: int() 以 10 为底的无效文字:''
我想做的是,即使我在提示输入时输入 0,它也只会在 else 语句中显示“输入正确约定”消息。
我正在使用的代码:
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
degree = int(temp[:-1]) #all of the string except for its last character
input_type = temp[-1] #get the last character
print("You entered: ", temp)
print("The degree entry is: ", degree)
print("The degree type is: ", input_type)
# Add code here
output_type = 0
result = 0
if input_type.upper() == "C":
result = int(round((9 * degree) / 5 + 32))
output_type = "F"
print("The temperature in", output_type, "is", result, "degrees.")
elif input_type.upper() == "F":
result = int(round((degree - 32) * 5 / 9))
output_type = "C"
print("The temperature in", output_type, "is", result, "degrees.")
else:
print("Input proper convention.")
【问题讨论】:
-
一个简单的解决方法是在
if和elif块内计算degree。 -
不要检查最后不是“C”或“F”,而是检查开头
标签: python python-3.x