Python Forum
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop confusion
#1
Hello,
I am trying to create a guessing game that chooses a random number for the player to guess, outputs the number of guesses the player made before guessing correctly, and then asks the player if they'd like to play again (doing this until the player inputs anything but "Y"). I seem to have a snag when it comes to the player choosing whether or not they want to play AGAIN. Input produces no reaction.

Thank you in advance for your help!

import random

random.seed()
count = 1
num = random.randint(1,10)

choice = input("Let's play a guessing game!  Want to play? (Y/N)\n")
guess = int(input("Guess a number between 1 and 10:\n"))

while (choice == 'Y') :

    while (guess != num) :
       guess = int(input("Guess a number between 1 and 10:\n"))
       count += 1


print("It took", count, "guesses to guess", num)
choice = input("Do you want to play again? (Y/N)\n")
Reply
#2
import random

while True:
    
    random.seed()
    count = 0
    num = random.randint(1,10)
 
 

  
    choice = input("Let's play a guessing game!  Want to play? (Y/N)\n")
    choice = choice.upper()
     
      
    while (choice == 'Y') :   
        guess = int(input("Guess a number between 1 and 10:\n"))
        count += 1
        if guess == num:
             
            print("It took", count, "guesses to guess", num)
            break
        else:
            continue
    
    else:
        break
      
This is what I thought.

Hope it helps you! Check your indent every time!

PS: This is not the perfect code!
Reply
#3
You want to indent the last two lines of code once. Then they will be part of the outer while loop, the one that tests choice.

But are you sure this is the code you are running? It doesn't produce the behavior you mention. It goes into an infinite loop because choice never changes in the loop. It never asks if you want to play again.

Note that if the player does want to play again, you need to reset num to a new random value. Otherwise the old guess will still equal the old num, and the inner while loop will never activate.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020