[Tutor] Question

Mark Lawrence breamoreboy at gmail.com
Sat Oct 3 19:26:42 EDT 2020


On 03/10/2020 22:14, Aaron Klein via Tutor wrote:
> Hi,
> I'm learning Python and am confused by nesting 'while' loops. My program should ask the user if they'd like to play again after guessing the number correctly. I'm not sure what variables to use in the outer loop. Do I create new ones? Thankd in advance for any suggestions!
> 
> 
> import random
> #seed random numberrandom.seed()
> #prime loopcount = 1
> 
> while():    #prime nested loop    guess = int(input('Guess a number between 1 and 10\n'))    num = random.randint(1, 10)    while(guess != num):        guess = int(input('Guess a number between 1 and 10\n'))        count+=1    print('It took', count, 'guesses to guess correctly.')playAgain = str(input('Would you like to play again?\n'))
> 

Let's see if we can correct that formatting.

while():    #prime nested loop

The while() will never run as the () is actually an empty tuple which 
always tests as false.

     guess = int(input('Guess a number between 1 and 10\n'))
     num = random.randint(1, 10)
     while guess != num: # we'll remove the unwanted brackets, no idea 
why people like typing them.

         guess = int(input('Guess a number between 1 and 10\n'))
         count+=1

The above will fail as 'count' doesn't yet exist, you'll need to 
initialise it outside the inner loop.

     print('It took', count, 'guesses to guess correctly.')
     playAgain = str(input('Would you like to play again?\n'))

'playAgain' should be tested at the outer loop instead of the empty 
tuple.  'input' always returns a string so no need for the call to 'str'.

I think as I'm knackered, chronic fatigue syndrome is a bummer :-(

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list