r/pythonhelp • u/Satiivas1 • Apr 07 '22
How to call a variable from a loop of another function
Hi! Just for practice purposes, I tried to call the variable "num" from one function to another, but I could not figure it out. Whatever I tried, the variable stayed not defined in the second function. Here is the code:
def main():
try:
num = int(input("Enter an integer: "))
if isinstance(num, int):
print(f"You inserted an integer {num}.")
except ValueError:
print("It is not an integer.")
main()
def second():
print(num)
main()
second()Also, could you please explain, why doesn't the following code work:
if isinstance(num, int):
print(f"You inserted number {num}.")
return numThank you!
2
Upvotes
2
u/sentles Apr 07 '22
Variable scope can be local or global. A local variable is usually defined inside a function, whereas a global isn't.
In your case, once the
mainfunction finishes executing, all local scope variables will be destroyed, includingnum. If you want to save that value, the most common way would be to return it, i.ereturn numat the end of the try block. To save the returned value, you'll need to call the function as such:n = main(). After the function has executed, the global variablenwill contain the returned value. At that point, if you need to use it in a different function, you can pass it as an argument:You'd call this as such:
second(n), assuming you saved the value inn. You could also have called the global variablenumand it would have worked in the same way.As for your second question,
isinstance(num, int)will always be true, since that point in execution will only be reached if the input is converted to an integer successfully by theintfunction. Therefore, your if statement is unnecessary. Nevertheless, it should work, so I'm not sure what you mean when you say it doesn't.Also, let me add that calling
maininside of itself is recursion, but you shouldn't use it in the way that you do. If the user inputs something that isn't an integer enough times, your program will raise a maximum recursion depth exception and crash. Instead, you should just use a loop to get new input if the given value isn't an integer.