0

i have this function that works as intended except for the fact that the last print instruction outside the while cycle (print("why don't you print?")) never get executed and i don't understand why. after the break, the code execution should move forward.

def eval_cycle():
    done = 'done'
    last_expression = ' '
    while True:
        dato = eval(input('Insert an expression: '))
        if dato == done:
            print("Last expression is: ", last_expression)
            return dato
            break
        last_expression = dato
        print(dato)
    print("why don't you print?")
2
  • 2
    return returns immediately, before break can execute. Commented Jan 9, 2023 at 18:30
  • oh right, i'm so stupid :( Commented Jan 9, 2023 at 18:40

1 Answer 1

1

When you return it immediately returns control flow out of the function.

Nothing in the function after that is executed.

As a sidenote, you may want to read the expression in as a string and then execute it. That way you can store it in last_expression rather than just the result of evaling the expression.

Sign up to request clarification or add additional context in comments.

3 Comments

you right, i didn't though about it. i'm stupid :( anyway what do you mean "you may want to read the expression in as a string"?
You read the expression in as a string and then immediately eval it. As a result, you no longer have access to that input string: just the result of evaling it.
do you mean something like this? last_expression = 'nothing' while True: expression = input('Insert an expression: ') if expression == 'done': print('Last expression is: ', last_expression) return last_expression print(eval(expression)) last_expression = eval(expression)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.