1

I have the following code:

def funct():
    print("beggining function")
    a = int(input)
    if a == 1:
        return True
    else:
        return False

while funct():
    #Rest of the code

Every time the while loop repeats it executes the function, so it prints "beggining function". I want to avoid this, what can I do?

4
  • 2
    Remove the print statement? Put it somewhere else? Commented Apr 7, 2015 at 12:50
  • while int(input) == 1: Commented Apr 7, 2015 at 12:51
  • @fedorqui please fix the code in an answer, not in an edit of the question. Commented Apr 7, 2015 at 12:54
  • @райтфолд Ops sorry! I was working on the original post in a file and didn't notice I did change it. Thanks for notifying. Commented Apr 7, 2015 at 12:56

2 Answers 2

3

A while <condition> loop works as follows:

  1. it checks condition.
  2. if condition evaluates to True, it executes the upcoming code one time. Then it goes back to 1.
  3. if condition evaluates to False, it skips the upcoming code and goes through the rest of the code.

So what you are seeing here is the intended way for while to work.

To prevent this header from being printed every time, just move it out of the while:

def funct():
    a = int(input)
    if a == 1:
        return True
    return False    # no need to check anymore

print("beggining function")  # here
while funct():
    #Rest of the code
Sign up to request clarification or add additional context in comments.

4 Comments

The thing is that the function in my code is a sudoku solver, so it prints the mistakes and returns true, and if the sudoku is solved it returns false, so i want to use only what the function returns to define if the program repeats or finishes.
i dont know if you want to see the whole code (is a bit long and in spanish), but you would do me a big favor
Paste it in pastebin.com and I'll have a look.
I would move line 188 print("Bienvenido a la experiencia Sudoku en Python",'\n') above line 186 while cond:. This should be enough.
0

Try to this

def funct():
    print("beggining function")
    a = int(input())
    if a == 1:
        return True
    else:
        return False
while funct() == 1:
    funct()

you enter input 1 loop will continue...

2 Comments

function is return true than call the function and repeat the loop.
This will not only still print beggining function for every function call, it will now be called twice for each loop. You should actually read the question.

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.