我目前正在编写一个简单的温度转换程序,需要满足以下要求:
目前,除了打印错误消息外,一切正常。比如说,我只输入了0,没有温度约定。程序仅显示:degree=int(temp[:-1])#除最后一个字符值之外的所有字符串错误:以10为基数的int()的文本无效:“”
我想做的是,即使在提示输入时只输入0,它也只会在else语句中显示“input-property-convention”消息。
我使用的代码:
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
块中
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
if temp.endswith("C") or temp.endswith("F"):
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.")
您可以检查用户输入是否有效,如下所示:
def check_user_input(user_input):
valid_units = ['c', 'C', 'F', 'f']
for unit in valid_units:
if unit in str(user_input) :
return True
return False
或者简单地如果str(user_input)[-1]不在{'c','C','f','F'}中:做某事
我没有能力评论@bigbounty的帖子。因此,使用修改后的代码进行更新。通过使用此选项,可以减少行数。
您可以直接使用温度[-1]检查C和F。如果你使用的话。upper(),则始终检查“C”和“F”。
另外,现在您已经检查了C或F,您知道其中的条件将是C或F。因此您可以使用if和else。
temp = input("Input the temperature you like to convert? (e.g., 45F, 102C etc.) : ")
if temp[-1].upper() in ('C','F'):
degree = int(temp[:-1]) #all of the string except for its last character
print("You entered: ", temp)
print("The degree entry is: ", degree)
print("The degree type is: ", temp[-1])
if temp[-1].upper() == 'C':
result = int(round((9 * degree) / 5 + 32))
output_type = 'F'
else: #will be '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.")
谢谢你给我机会回答你的问题。很有趣。