-2
\$\begingroup\$

I am writing a simple code testing try: / except clause in Python. My code does what is expected but I don’t understand return/print behavior when I loop that code.

With print statement while loop behaves as expected. It asks the user to put the correct value and it stops only when corrected value is entered.

def div():
    while True:
        try:
            user_digit_1 = int(input("Enter a first digit: "))
            user_digit_2 = int(input("Enter a second digit: "))
            result = user_digit_1/ user_digit_2   
            return result


        except ValueError:
            print ("Please try again. This is not a digit")
        except ZeroDivisionError:
            print ("Please try again. Don't divide by 0")

With return statement in except clause there is no loop at all. The code simple returns the error information and stops there.

    def div():
    while True:
        try:
            user_digit_1 = int(input("Enter a first digit: "))
            user_digit_2 = int(input("Enter a second digit: "))
            result = user_digit_1/ user_digit_2   
            return result


        except ValueError:
            return ("Please try again. This is not a digit")
        except ZeroDivisionError:
            return ("Please try again. Don't divide by 0")

I'd like to understand why?

\$\endgroup\$

closed as off-topic by 200_success, Ludisposed, Graipher, πάντα ῥεῖ, jonrsharpe Feb 10 at 15:46

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Authorship of code: Since Code Review is a community where programmers improve their skills through peer review, we require that the code be posted by an author or maintainer of the code, that the code be embedded directly, and that the poster know why the code is written the way it is." – 200_success, Ludisposed, Graipher, πάντα ῥεῖ, jonrsharpe
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ Unfortunately, explaining the behavior of your code is outside the scope of this site (see the help center). We can suggest how to improve your code, but in that case you should show your entire program so that we can give you the proper advice. \$\endgroup\$ – 200_success Feb 10 at 13:19
  • \$\begingroup\$ @200_success, This is the entire program, and my goal was to ask about that code performance. Please advise how questions about code performance should be written? \$\endgroup\$ – Marcel Feb 10 at 16:25

Browse other questions tagged or ask your own question.