Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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()
question from:https://stackoverflow.com/questions/66048050/im-new-to-python-and-my-coding-class-is-starting-with-tracy-turtle-graphics

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...