【发布时间】:2021-02-11 07:46:39
【问题描述】:
我在第一年的编程课上有一个作业,其中一个部分是将字符串转换为整数或浮点值。但是,如果字符串不可转换,则应将值 None 传递给变量。我的教授表示,无论出于何种原因,我们都不允许使用 try/except,我能想到的唯一方法是使用 isdigit() 方法,但是,这不适用于所需的负值,因为值是用于测量温度。
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
这是我能想到的唯一方法,但是,我班的另一个学生在我们应该定义的先前函数之一中使用 is digit() 做到了
def convert_to_kelvin(temperature, units):
unit = units.lower()
if type(temperature) != float and type(temperature) != int and temperature.isdigit() == False:
return None
使用它,教授使用的自动评分器将其标记为正确,它也将我的尝试/除外标记为正确。但是我的同学代码没有给出负值,而我的没有。教授说 try/except 是不允许的。
【问题讨论】:
-
去掉负号,处理,再把负号加回去?所以如果
s的第一个字符是'-',就做isdigit(s[1:]),如果不是,就用isdigit(s)——这符合你的要求吗? -
对不起,我对编程很陌生。如何删除负号并将其添加回来?
-
您的代码是否需要与
int()和float()完全一样?
标签: python floating-point integer try-except