[Tutor] unorderable types
boB Stepp
robertvstepp at gmail.com
Sun Aug 6 13:35:46 EDT 2017
On Sat, Aug 5, 2017 at 1:28 PM, Howard Lawrence <1019shaun at gmail.com> wrote:
> # this is a guess 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')
>
> while guessesTaken < 6:
> print('take a guess.')
> guess = input()
> guess_value = int(guess)
>
> guessesTaken = guessesTaken + 1
>
> print("type(guess_value)=",type(guess_value))
> print("type(number)=",type(number))
>
> if guess_value < number:
> print('your guess is too low.')
>
> if guess_value > number:
> print('your guess is too high.')
>
> if guess_value == number:
> break
If the values are equal the "break" statement will exit your while
loop and never see the following "if" block.
> if guess_value == number:
> guessesTaken = str(guessesTaken)
> print ('good job, ' + myName + '! you guessed my number in ' +
> guessesTaken + ' guesses!')
And I suspect you only want to execute the following "if" block if the
user did not guess the number in the provided six guesses.
> if guess_value != number:
> number = str(number)
> print ('nope. the number i was thinking of was ' + number)
So these final two "if" groupings should be _outside_ your while loop:
while guessesTaken < 6:
<All of your earlier code inside the while loop>
if guess_value == number:
print('good job, ' + myName + '! you guessed my number in',
guessesTaken, 'guesses!')
else:
print('nope. the number i was thinking of was', number)
Notice the differences in indentation between what is _inside_ the
while loop and what now follows _outside_ the while loop. Also
instead of two consecutive "if" blocks, I used the "if - else"
structure. If the "if" condition is not true then the code will
automatically execute the "else" block. Per what the others have
said, I did not convert "guessesTaken" and "number" to strings, The
print function will handle that for us. Also, with the print function
if items to be printed are listed as separate arguments, that is,
separated by commas, the default behavior of print is to insert a
single space in the place of each comma.
Inside your while loop you could use "if - elif - else" instead of
your chain of three "if" statements. Have you read about these yet?
If yes, then it would be more natural (Pythonic) to do things this
way:
while guessesTaken < 6:
...
if guess_value < number:
...
elif guess_value > number:
...
else:
break
Hope all of this makes sense. If not come back with questions.
Cheers!
boB
More information about the Tutor
mailing list