简体   繁体   中英

I'm new to python and my coding class is starting with “Tracy” turtle graphics, my code isn't working

Don't worry about the functions, they are perfectly functional. I'm having trouble with this while loop as whenever I run the code it continuously repeats the check_mark(), up_arrow(), and down_arrow() functions. I know its something wrong with my while loop, and I need to use an if/elif/else statement, I'm just not sure how to do it. Any help would be appreciated.

speed(0)
secret_number = 7
user_number = int(input("Guess the secret number(1-10): "))
while secret_number == 7:
        if secret_number > user_number:
                down_arrow()
        elif secret_number < user_number:
                up_arrow()
        else:
                check_mark()

If I understand correctly what you're trying to do here, I think you meant something like this:

speed(0)
secret_number = 7
while True:
        user_number = int(input("Guess the secret number(1-10): "))
        if secret_number > user_number:
                down_arrow()
        elif secret_number < user_number:
                up_arrow()
        else:
                check_mark()
                break

I made three changes:

  1. Changed secret_number == 7 to True in the while loop condition. It does the same thing because secret_number is always equal to 7, but it's easier to understand this way.
  2. The while loop never ends because the condition is always True . I think you'd want to exit the loop when the user guesses the number. So I added a break in the final else branch.
  3. Moved the input of user_number into the while loop so that the question is asked again and again as long as the answer is wrong, instead of only once.

While functions will keep iterating, as long as the statement is true. In your code, the secret number is set at 7, so the statement in the while loop is true. However, because the secret number remains 7, the while loop will keep repeating infinitely.

secret_number is 7, and never changes in the code you've provided.

Your while loop continues executing for as long as secret_number == 7

Therefore it will execute forever. It keeps asking "is the secret number 7?" and the answer is always "yes"

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