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.
0
solved My code doesn’t print what I want it to print