[Tutor] While Loop Help
Matthew Nappi
matthew.nappi at stonybrook.edu
Thu Dec 11 05:20:12 CET 2014
Hello All:
I am working on the challenges from “Python Programming for the Absolute
Beginner” Chapter 3. I am asked to modify the original code pasted below
to limit the number of guesses a player has to guess the number. I did so
(code pasted below); however if a player guesses the right number they
still receive an ending message indicating that they failed. How can I
modify the code without using any advanced techniques to have a different
message in the event of a successful guess? Thanks in advance!
*Original Code:*
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
*My Modified Code:*
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number and tries < 10:
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
else:
print("You win.")
guess = int(input("Take a guess: "))
tries += 1
print("You fail! The number was", the_number)
input("\n\nPress the enter key to exit.")
More information about the Tutor
mailing list