r/pythonhelp • • 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 num

Thank you!

2 Upvotes

4 comments sorted by

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 main function finishes executing, all local scope variables will be destroyed, including num. If you want to save that value, the most common way would be to return it, i.e return num at 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 variable n will contain the returned value. At that point, if you need to use it in a different function, you can pass it as an argument:

def second(num):
    print(num)

You'd call this as such: second(n), assuming you saved the value in n. You could also have called the global variable num and 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 the int function. 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 main inside 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.

1

u/Satiivas1 Apr 08 '22

Thank you for your reply!

  1. Sorry for not being clear with my second question. What I meant was, that I can't get the return num function to work, the isinstance part works well. For example, in the following code, the(num) is not defined in print(num), although I return the num from the function. Why?

def main():
try:
    num = int(input("Enter an integer: "))
    if isinstance(num, int):
        print(f"You inserted number {num}.")
        return num
except ValueError:
    print("It is not an integer.")
    main()


main()
print(num)

2. How should I write the code without the if statement? When the input is invalid, for example "abc", the code goes to except, right? Whereas if the input is an integer, isinstance will be true and the code under the if statement gets executed. I am a complete beginner, so I would be very grateful if you could let me know if I am making some very basic mistake here or complicating things unnecessarily.

3. How would I loop the function without calling main() after the code reads the except block?

Thank you in advance!

1

u/Satiivas1 Apr 08 '22

The pasted code has an error with indents, I noticed it now. But one more problem occured with the code: if I correct the indentation, so:

def main():
    try:
        num = int(input("Enter an integer: "))
        if isinstance(num, int):
            print(f"You inserted number {num}.")
            return num
    except ValueError:
        print("It is not an integer.")
        main()


main()
print(num)

The code works when I enter an integer. BUT, when I enter an invalid input, f.e "abc" and then enter an integer, the print(num) comes back as None. Why?

2

u/sentles Apr 08 '22 edited Apr 08 '22
  1. You're returning the value, but not saving it anywhere. When you call a function, any returned result will substitute the function call after function execution has ended. In your example, you need to call your function as such: n = main(). Once execution of the function ends, main() is substituted by the return value, which is then saved in n. As I mentioned, you can also call num = main() and then your value will be saved in num, globally. In your case, you didn't save it at all, so of course, it doesn't exist.

  2. The if statement is unnecessary. There are two cases to be examined: the input either is, or is not, a value that can be converted to an integer. By examining each case, we get the following. If the value can be converted to an integer, then the if condition is true. You print the message indicating as such and return the value. If the value cannot be converted to an integer, then the if statement is never even reached; instead, code execution is transferred straight to the beginning of the except block, at which point you print an error message and proceed with getting input again. By analyzing it as I did above, you can understand that the if statement can only ever be true. Of course, such an if statement is useless and can be skipped completely.

  3. Simply use a loop, as shown below:

def main():
    while True:
        try:
            num = int(input("Enter an integer: "))
            print(f"You inserted {num}")
            return num
        except ValueError:
            print("Expected an integer")

If the user inputs a valid integer, the int function will not raise any exceptions. Execution will continue to the next print call. Finally, the value will be returned, effectively ending function execution and exiting the loop.

If int cannot convert the given value to an integer, it will raise a ValueError, which will be caught by the try-except statement. At that point, execution is transferred to the except block, which prints an error message ("Expected an integer"). Finally, execution is trasferred to the beginning of the loop again, at which point the user is prompted to type in an integer again. Obviously, you can also use a bare except clause (without the ValueError), but that is generally considered bad practice.

Obviously, if you wanted to do more after the loop, before returning the value, you'd simply use break instead of return num to break out of the loop, without exiting the function.

Hopefully this will clear things up.