[英]Raising an exception
This is a homework problem. 这是一个作业问题。 I've been trying to solve it but couldn't get the right result. 我一直在尝试解决问题,但无法获得正确的结果。
This is the question: 这是问题:
Write a function string2int that attempts to convert a string to an integer. 编写一个函数string2int,尝试将字符串转换为整数。 If the string does represent a positive integer then that integer should be returned. 如果该字符串确实表示一个正整数,则应返回该整数。 If the string does not represent a positive integer then you should raise a syntax exception (
raise SyntaxError('not an integer')
). 如果字符串不代表正整数,则应引发语法异常(raise SyntaxError('not an integer')
)。You may choose to use the (already defined) function
all_digits
that takes a string and returnsTrue
if all the characters of the string are digits andFalse
otherwise. 您可以选择使用(已定义)函数all_digits
,该函数采用字符串,如果字符串的所有字符均为数字,则返回True
否则返回False
。
What I've got so far is: 到目前为止,我得到的是:
try all_digits is True:
return int(num)
except all_digits is False:
raise SyntaxError('not an integer')
Because I'm using an already defined function, I didn't define a function (or did I get it wrong?). 因为我使用的是已经定义的函数,所以我没有定义一个函数(或者我弄错了吗?)。 Can anyone have a look at my code please? 任何人都可以看看我的代码吗? Much appreciated. 非常感激。
I can guess, but you might want to tell us what kind of error you get when you execute the code (just a heads up for the next time you ask a question). 我可以猜测,但是您可能想告诉我们在执行代码时遇到什么样的错误(下次您提一个问题时请注意)。
There's a couple of mistakes: 有几个错误:
1) The syntax of 1)的语法
try all_digits is True:
is wrong. 是错的。 The "try" statement should look like this: “ try”语句应如下所示:
try:
<your code>
except <type of exception to catch>:
<error handling code>
2) You said "all_digits" is a function. 2)您说“ all_digits”是一个函数。 Therefore, the code 因此,代码
all_digits is True
should be 应该
if all_digits(num):
Putting it all together: 放在一起:
def string2int(num):
if all_digits(num):
return int(num)
raise SyntaxError('not an integer')
In addition to Rawing's excellent answer, note that the usual time to use try/except
is when you can handle the error thrown in the try
block and continue as usual. 除了Rawing的出色答案外,请注意,通常使用try/except
是可以处理try
块中引发的错误并照常继续的时间。 For instance: 例如:
def add_three(x) -> int:
try:
return x + 3
except TypeError:
# someone passed a non-int/float to the function!
# let's try and coerce it.
return int(x) + 3
# if this still throws an exception, we'll let it
# raise its own TypeError exception!
In your case it looks like you're just doing regular conditionals, so use if all_digits(num): return int(num) else: raise TypeError('not an integer')
在您的情况下,您似乎只是在执行常规条件,因此, if all_digits(num): return int(num) else: raise TypeError('not an integer')
all_digits(string)
function: all_digits(string)
函数:
First, it's good to understand what does the pre-defined all_digits(string)
function do. 首先,最好了解预定义的all_digits(string)
函数的功能。 Following is a sample implementation of that function, which works as desired by your description. 以下是该功能的示例实现,可以根据您的描述进行操作。 It checks whether each letter of the string is a digit and returns a boolean, True
or False
, accordingly: 它检查字符串的每个字母是否都是数字,并相应地返回boolean, True
或False
:
def all_digits(string):
''' only returns True if all characters of the string are Integers '''
for l in string:
if l.isdigit(): pass
else: return False
return True
string2num(string)
function with raise
statement: 带raise
语句的string2num(string)
函数:
Now, we can use this function in our error handling block of the string2num(string)
function. 现在,我们可以在string2num(string)
函数的错误处理块中使用此函数。 Since your problem requires you to only raise
a specific exception and not to continue with an alternate block of code, you do not need the try: ... except:
block. 由于您的问题仅要求您raise
特定的异常,而无需继续执行备用代码块,因此您不需要try: ... except:
块。
With the proper syntax of the raise
statement , we can write: 使用raise
语句的正确语法,我们可以编写:
def string2num( string = '-23'):
if all_digits(string):
return int('23')
raise SyntaxError("not an integer")
and we get: 我们得到:
>>> string2num()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in string2num
SyntaxError: not an integer
with try: ... except: ...
block: try: ... except: ...
块:
But if you do want to execute an alternate block of code when the exception is raised, you can use the try: ... except:
block syntax. 但是,如果确实要在引发异常时执行备用代码块,则可以使用try: ... except:
块语法。 You may need it, for instance, if you want to further check if the string is a negative integer and if so then return the negative integer: 例如,如果您想进一步检查字符串是否为负整数,则可能需要它,如果是,则返回负整数:
def string2num( string = '-23'):
try:
if all_digits(string):
return int(string)
raise SyntaxError("not an integer")
except SyntaxError:
#alternate code goes here#
try:
return int(string)
except ValueError:
print "string contains an alphabet"
This will produce: 这将产生:
>>> string2num()
-23
>>> string2num('ab2')
string contains an alphabet
Style for if
statement: if
语句的样式:
As a side note on your style, you don't have to explicitly write whether an expression evaluates to True
or False
in an if statement, like so: 作为样式的附带说明,您不必在if语句中显式编写表达式的计算结果为True
还是False
,如下所示:
if all_digits(string) is True:
Since all_digits(string)
returns a boolean, you can equivalently just say if True
, like so: 由于all_digits(string)
返回一个布尔值,因此您可以等效地只说if True
,如下所示:
if all_digits(string):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.