Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #44328

Re: Guess the Number Repeat

From Peter Otten <__peter__@web.de>
Subject Re: Guess the Number Repeat
Date 2013-04-25 11:22 +0200
Organization None
References <de1835ee-ef97-4d0c-99f8-f6cb348a252c@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1053.1366881761.3114.python-list@python.org> (permalink)

Show all headers | View raw


eschneider92@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()



Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Guess the Number Repeat eschneider92@comcast.net - 2013-04-25 01:47 -0700
  Re: Guess the Number Repeat Peter Otten <__peter__@web.de> - 2013-04-25 11:22 +0200

csiph-web