On 10/03/2017 06:29 PM, Alan Gauld via Tutor wrote:
> On 03/10/17 22:49, steve.lett...@gmail.com wrote:
> 
>> That is guessesTaken. It reads 0 when it should be a larger number.
> 
> What makes you think so?
> You never increase it from its initial value so, quite correctly it
> stays at zero.

Adding some optimization thoughts below in addition:

> 
>> I am a beginner having another try to get it!
> 
> Remember the computer just does what you tell it and nothing more.
> It has no idea what you are trying to do so it needs you to tell it
> exactly what to do. Every single thing.
> 
> And in this case you need to add 1 to guessesTaken each time
> the user makes a guess.
> 
>> # This is a Guess the Number game.
>> import random
>>
>> guessesTaken = 0
>>
>> print('Hello! What is your name?')
>> myName = input()
>>
>> number = random.randint(1, 20)
>> print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
>>
>> for i in range(6):
>>     print('Take a guess.') # Four spaces in front of "print"
>>     guess = input()
>>     guess = int(guess)
> 
> you probably should have a line here like:
> 
>       guesesTaken += 1
> 
>>     if guess < number:
>>         print('Your guess is too low.') # Eight spaces in front of "print"
>>
>>     if guess > number:
>>         print('Your guess is too high.')
>>
>>     if guess == number:
>>         break

This sequence doesn't feel ideal: if guess == number you break out of
the script, then the first thing thereafter is you do the same check
again.  Why not move that work up to the first check inside the for loop?

>> if guess == number:
>>     guessesTaken = str(guessesTaken)
>>     print('Good job, ' + myName + '! You guessed my number in ' +
>>       guessesTaken + ' guesses!')
>>
>> if guess != number:
>>     number = str(number)
>>    print('Nope. The number I was thinking of was ' + number + '.')

Second, you need to still detect the case where you exited the loop
without ever matching.  But it doesn't have to be a disconnected test
like this one which risks at some time becoming detached - maybe you add
some code in front of it, then later change it, then change it some more
and at some point guess becomes changed and the test is invalid.  It
sounds silly here, but this happens in real code that is more complex.

Python has a syntax feature to help you out here: the for statement can
take an else clause, which means "finished the loop without otherwise
breaking out of it".  This would make the conceptual flow look like:

for i in maximum-guesses:
    # prompt for guess
    # guidance if wrong
    if correct:
        # congratulate
        break
else:
    # guesses ran out, commiserate



_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to