简体   繁体   中英

Why does my output execute multiple print functions?

I'm working on a guessing game where the user inputs a number until they get it correct. I'm trying to understand why my output creates multiple print functions if I don't guess in the first try. But if I guess the answer correctly on first try, it prints correctly.

ans = 5

def function(guess, ans):
    if ans != guess:
        if ans < guess:
            print("Guess lower")
            return False
        elif ans > guess:
            print("Guess higher")
            return False
    elif ans == guess:
        print("Correct!")

def init():
    print("Guess a number between 1 and 10: ")
    guess = int(input())
    main(guess)

def main(guess):
    while function(guess, ans) == False:  
        init()
        function(guess, ans)
        break

init()

Outputs:

Correct guess on first attempt:

Guess a number between 1 and 10:
5
Correct!

Correct guess on third attempt:

Guess a number between 1 and 10:
4
Guess higher
Guess a number between 1 and 10:
6
Guess lower
5
Correct!
Guess lower
Guess higher

It is because of this:

  1. The answer is incorrect. So you go to init()
  2. The init() again passes the argument to main() function. So, it has become a sort of recursion where the function is executed again.

Here is what your code is doing.

main()
|__init()
|  |
|  main()
|  |
|  function()
|
function()

That is why you are getting that output. Also, this hierarchy increases 1 level with each incorrect answer.

Instead, here is what you can do:

ans = 5
guess=0
def function(guess, ans):
    if ans != guess:
        if ans < guess:
            print("Guess lower")
            return False
        elif ans > guess:
            print("Guess higher")
            return False
    elif ans == guess:
        print("Correct!")
        return True
def init(guess):
    while True:
        print("Guess a number between 1 and 10: ")
        guess = int(input())
        if function(guess, ans):
            break

init(guess)

All explanations were given by @Sujay.

This is an alternative with local variable.

ans = 5

def guess_my_number(guess, ans):  # <- choose a meaning function name
    if ans != guess:
        if ans < guess:
            print("Guess lower")
            return False
        elif ans > guess:
            print("Guess higher")
            return False
    elif ans == guess:
        print("Correct!")
        return True  # <- It's important to return True

def main():
    # If user guessed the answer, this variable is set to True
    good_answer = False
    # So while the user has not found, continue to ask him a number
    while good_answer != True:
        print("Guess a number between 1 and 10: ")
        guess = int(input())
        good_answer = guess_my_number(guess, ans)

main()

The answer to your question is that when your input isn't correct the first time, your code is entering into a recursive call because of the main(guess) line that you've put in the init() function which later is returning those extra lines of output that you don't want to see. (For n incorrect tries, you'll be seeing n such extra lines after your code prints out Correct! depending on whether your previous inputs were higher or lower.)

First, there is no need of ans != guess , you can simply make a conditional with if-elif-else condition like:

def function(guess, ans):
    if ans < guess:
        print("Guess lower")
        return False
    elif ans > guess:
        print("Guess higher")
        return False
    else: # This will automatically be ans = guess case 
        print("Correct!")
        return True # You weren't returning any value here and I suppose you wanted to exploit this

You'll need to remove the main(guess) line from your init() function to avoid recursive-call and add a line to return guess ie user input so that you can pass it on to the main() function.

def init():
    print("Guess a number between 1 and 10: ")
    guess = int(input())
    return guess

Now, you need to modify your main function like-

def main():
    while True:  
        guess = init()
        if function(guess, ans):
            break

You can call the main function as shown below and it'll work-

main()

PS- There are many ways to fix your code into the one which does what you wish to do and this is just one of those ways.

Just remove function(guess, ans) in the main() function. you are already using while loop and returning bool values from function()

在函数function()中,当满足value时返回true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM