Reputation: 15
I have some function such as sumssqure of the range number n, if n is integer, it should return the sum value. If n is not integer, should return with some string. It must use raise ValueError("Sorry, n must be a whole number!"). My codes can works well with any integer n, but has problem when n is not integer. I don't know how to fix it. Many thanks.
def sumsquares(n):
try:
return sum(i**2 for i in range(0,n+1))
except ValueError as ve:
err = str(ve)
assert err == "Sorry, n must be a whole number!"
sumsquares(2.2)
Upvotes: 0
Views: 70
Reputation: 782315
Just return the string you want in the except
block.
Also, the exception that's raised when you give the wrong type of argument to range()
is TypeError
, not ValueError
.
def sumsquares(n):
try:
return sum(i**2 for i in range(0,n+1))
except TypeError as ve:
return "Sorry, n must be a whole number!"
Upvotes: 2
Reputation: 64
If n is a float type , you can add a simple check and return as following
if n%1 != 0:
return 'Float type'
Upvotes: 0