I have an assignment for my first year programming class in which one of the parts is to convert a string to an integer or float value. However, if the string is not convertible it should pass a value of None to the variable. My professor indicated that we are not allowed to use try/except for whatever reason and the only way I can think of doing this is using the isdigit() method, however, this will not work for negative values which are required as the value is being used for a temperature.
temp = input('What is the temperature value? Enter a numeric value: ')
try:
temp = float(input('What is the temperature value? Enter a numeric value: '))
except ValueError:
temp = None
This is the only way I can think of doing this, however, another student in my class did it using the is digit() in one of the previous functions we are supposed to define
def convert_to_kelvin(temperature, units):
unit = units.lower()
if type(temperature) != float and type(temperature) != int and temperature.isdigit() == False:
return None
Using this, the autograder that the professor uses marks it as correct and it also marks my try/except correct as well. But my classmate code gives none for negative values and mine does not. The professor said that try/except is not allowed.