If the number is 1 want it to print 1 is a number
but instead it prints <function num> is a number
. How do I fix this?
def num():
int(input("number: "))
try:
num()
except ValueError:
print(f"{num} is not a number")
else:
print(f"{num} is a number")
CodePudding user response:
You need to have an input and output in your function. you can try something like:
def is_one(num):
#if number is 1 return True otherwise return False
return num == 1
if is_one(num):
print(f"{num} is a number")
CodePudding user response:
do below:
def num():
try:
input_value = input("number: ")
input_value = int(input_value)
except ValueError:
print(f"{input_value} is not a number")
else:
print(f"{input_value} is a number")
num()
from your query it seems like you are not intereseted in any return value from your metgod hence move your exception handle within your function and you should be good else return a input value from your method and then do exception handle. Hope this makes sense.
CodePudding user response:
Functions as Value
In python functions are also values, so name num
is bound to the function that you defined in the def statement. That's why when you print(num)
you get <function num>
. Assigning the return value of your function call to num()
will solve the problem for the print statement you asked:
def num():
int(input("number: "))
a = num()
print(f"{a} is a number")
Exception Handling
However, as you can see you, if you use the same try except
structure that you used and assigned a
under the try:
statement, you wouldn't be able to access it under the except
statement. Why? Because this is very bad exception handling design. The exception is raised by the call to int
with a "non integer convertible" value, and thus it makes a lot more sense for you to handle it under the definition for num where call to int()
is made:
def num():
a = input("number: ")
try:
b = int(a)
print(f"{a} is a number")
return b
except ValueError:
print(f"{a} is not a number")
num()
Although this fits your needs, exception handling under the same function is not absolute, and in many cases you might want to pass exceptions around in the program.