Guess the Number Repeat

E

eschneider92

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)
 
P

Peter Otten

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top