我想将输入从摄氏度转换为华氏度,但我不明白如何接受负数和小数输入,同时消除“abc”等非数字输入。
`temp = input('enter a temperature in C: ')
if temp.isdigit():
temp = int(temp)
print(f'{temp * 1.8 + 32} F')
else:
print('not a temp')`
你可以做这样的事情。我不知道这是否是最好的方法,但是它应该有效
def is_valid_temperature(temperature):
try:
float(temperature) # Convert the inputted temperature to a float
return True
except ValueError: # If its something like abc, this will catch the exception and return False
return False
def convert_celsius_to_fahrenheit():
temp = input('Enter a temperature in Celsius: ')
if is_valid_temperature(temp):
temp = float(temp) # Now that we know that it's valid and it will not crash, we can convert the input to float.
fahrenheit = temp * 1.8 + 32
print(f'{temp}°C is equal to {fahrenheit}°F')
else:
print('Invalid input. Please enter a valid number.')
# Call the function with our program
convert_celsius_to_fahrenheit()
如果您愿意,您可以进行改进:通过将用户输入与 convert_celsius_to_fahrenheit
函数分离来实现
关注点分离。