Hello,
I have this small tester program. Depending on the function location, the function behaves
differently. Here is the tester code:
def valid_number(x):
print('Number entered:', x)
if x == 45:
print('Age is ', x)
return False
else:
print('Came into secondary result')
return True
temp = valid_number(45) # Called here, works as expected
print('temp value is: ', temp)
print('')
Condition = True
while Condition == True:
age = input("Please enter your age: ")
print('The value of age is:', age)
Condition = valid_number(age) # Does not behave as expected here!
print('\nExited while loop')
Can someone please advise.
********* Update: I figured it out. *********
I had to write the question like this (type cast input to type ‘int’):
age = int(input("Please enter your age: ")) # I had to add the ‘int’ in front.
1 Like
Please format all the code so that we can easily see what you have written.
See About the Python Help category
2 Likes
input
returns a string, valid_number
always returns True if x
is a string.
The location – where or when a function is called again – can only impact the returned value if the function reads global variables, or is somehow depending on mutable global resources, if its recursive or if it somehow keeps state (for instance if it is a generator yielding results). So, there are scenarios where this can happen (and I may have forgotten some here), but in all simple functions (as here) it’s not relevant. – Long and painful experience has taught me that the first “cause” or “possible explanation” I think of when debugging something in my own code is almost never correct. So now, my second thought is always: “What if I’m wrong - again?”…
Since x
needs to be a number, you could consider modifying the code like this:
def valid_number(x: int):
if not isinstance(x, int):
raise ValueError(f"Expected an int, but got {x} ({type(x)}")
# etc
Or you could fold the cast into the function itself like this:
def valid_number(x: int):
x = int(x) # this will raise a ValueError if x cannot be converted into an int
# etc
1 Like
Hi,
thank you. I actually tried applying this. But I didn’t see the changes immediately
reflected on the accompanying right panel.
The following is only a test:
def abc(x, y):
b = x + y
print('The sum of %d and %d is: %d' % (x, y, b)
Notice, I have added three apostrophes both before and after.
*************** Update ******************
Ok, got it. It is not apostrophes. It is the small ‘wavy’ apostrophes.
Thank you again. Much appreciated.
Hello,
thank you for your detailed response. A lot of subtle nuances when
learning a new language.
Much appreciated!