How to make for loop faster in python?

How do I stop a while-loop?

  • I have tried to make a console-based calculator, and everything works, except I cannot set the while-loop to False. :/ I started learning Python again today, (not that I had that much experience earlier), and started using Codecademy today, again. from math import * again = True while again == True: number1 = raw_input("Tell me the first number, please.") number2 = raw_input("Tell me the second number, please.") wayToAdd = raw_input("Plus, minus, multiplication, divide, or would you like to set it to a power? Maybe square it?") def TrueAnswer(): daTrueAnswer = raw_input("Would you like to do this again?") if daTrueAnswer == "yes": again = True elif daTrueAnswer == "no": again = False else: print("What?") again = False if wayToAdd == "plus": total = long(number1) + long(number2) print long(total) TrueAnswer() elif wayToAdd == "minus": total = long(number1) - long(number2) print long(total) TrueAnswer() elif wayToAdd == "multiplication": total = long(number1) * long(number2) print long(total) TrueAnswer() elif wayToAdd == "divide": if(number1 == "0" or number2 == "0"): print("You cannot divide by zero!") TrueAnswer() else: total = long(number1) / long(number2) print long(total) TrueAnswer() elif wayToAdd == "to a power": total = long(number1) ** long(number2) print long(total) TrueAnswer() elif wayToAdd == "square it": total = sqrt(long(number1)) total2 = sqrt(long(number2)) print float(total) print float(total2) TrueAnswer() else: print("You did not input a number, nor did you input the other thing.")

  • Answer:

    just use break

Montassar ben Hadj Abdallah at Quora Visit the source

Was this solution helpful to you?

Other answers

You can't change a variable's value from inside a function. Trying to do that, will only create a new variable with the same name as the one you are trying to change, but distinct from it, and local to the function, that is, not accessible from outside it. I would modify your function in such a way that it *returns* either True or False, and then I would modify the calls to the function from TrueAnswer() to again=TrueAnswer() Also, I would move the function definition outside the loop, as here's no reason why it should stay inside. Using 'global' as advised by Anonymous will also work, but any programmer will advise you against using it.

Andrea Manno

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.