eschneide...@comcast.net wrote:

> How do I make the following program play the 'guess the number game'
> twice?
> 
> 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 = int(guess)
>     print('You have ' + str(5 - guessesTaken) + ' guesses left.')
>     guessesTaken = guessesTaken + 1
>     if guess < number:
>         print('Your guess is too low.')
>     if guess > number:
>         print('Your guess is too high.')
>     if guess == number:
>         break
> 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)


If you put everything needed to guess once into a function like in the 
following example. Once you have reorganised

#first version -- flat
guess = int(input("guess my number: "))
if guess == 42:
     print("congrats")
else:
     print("sorry, you're wrong")

into

#second version -- using a function
def guess_number():
    guess = int(input("guess my number: "))
    if guess == 42:
         print("congrats")
    else:
         print("sorry, you're wrong")

guess_number()

you can easily modify the script to invoke the guess_number() function 
inside a loop:

#third version -- calling the function from within a loop
def guess_number():
    guess = int(input("guess my number: "))
    if guess == 42:
         print("congrats")
    else:
         print("sorry, you're wrong")

for i in range(2):
    print("round", i+1)
    guess_number()




-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to