patternpythonMinor
Guess My Number, Classic Edition
Viewed 0 times
editionnumberclassicguess
Problem
I am learning Python at present, from several books. I am new to programming and I need assistance with knowing when my code is written with good form and style - I want to ingrain the habit of writing good clean code, which would be accepted as thus by other programmers. This is a code example from the book Python Programming for the Absolute Beginner by Michael Dawson, which I have altered in several ways - a game which picks a random number and asks the player to guess that number:
The code works, however, I feel it is slightly 'bloated' and messy. How would a more experienced programmer change my code?
# Alex Grattan
# 8/10/14
# 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
if tries == 5:
print "You failed to guess in time!"
break
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
raw_input("\n\nPress the enter key to exit.")The code works, however, I feel it is slightly 'bloated' and messy. How would a more experienced programmer change my code?
Solution
Mixing Python 2 and 3
The program is correct in neither Python 2 nor Python 3.
Your program fails to run at all in Python 3, due to the lack of parentheses when calling
Also, the
On the other hand, it's not quite correct under Python 2 either. These
would be interpreted as requests to print tuples… complete with parentheses and commas.
Initialization
The number of allowed guesses, 5, is buried in the middle of your program, and should be defined in an obvious place near the top.
The bounds, 1 and 100, are each hard-coded twice. That is a maintenance pitfall, should you ever need to change the upper bound. Again, these special numbers should be defined just once in an obvious place.
Loop
The
@MasayukiFujita and @MathiasPanda have the right idea, I think, to use the count rather than the correctness as the loop condition. I would go a step further and suggest that counting loops in Python would be more idiomatically written using
To distinguish between the winning and losing condition without using a boolean variable or retesting the correctness of the guess, you can take advantage of an obscure Python language feature: an
Newline management
You'll have a better time printing nice output if you make a habit of always putting your newlines at the end of print statements.
Suggested solution
Here is a program that works in both Python 2 and Python 3.
The program is correct in neither Python 2 nor Python 3.
Your program fails to run at all in Python 3, due to the lack of parentheses when calling
print "You failed to guess in time!"Also, the
raw_input() function does not exist in Python 3.On the other hand, it's not quite correct under Python 2 either. These
print statementsprint("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")would be interpreted as requests to print tuples… complete with parentheses and commas.
Initialization
The number of allowed guesses, 5, is buried in the middle of your program, and should be defined in an obvious place near the top.
The bounds, 1 and 100, are each hard-coded twice. That is a maintenance pitfall, should you ever need to change the upper bound. Again, these special numbers should be defined just once in an obvious place.
Loop
The
"Take a guess" prompting statement is written twice. It should be moved inside the loop, at the top of the loop.@MasayukiFujita and @MathiasPanda have the right idea, I think, to use the count rather than the correctness as the loop condition. I would go a step further and suggest that counting loops in Python would be more idiomatically written using
for counter in range(…).To distinguish between the winning and losing condition without using a boolean variable or retesting the correctness of the guess, you can take advantage of an obscure Python language feature: an
else clause on a loop. The else clause is executed only when the loop terminates "naturally", rather than due to a break.Newline management
You'll have a better time printing nice output if you make a habit of always putting your newlines at the end of print statements.
Suggested solution
Here is a program that works in both Python 2 and Python 3.
import random
BOUNDS = (1, 100)
TRIES_ALLOWED = 5
the_number = random.randint(*BOUNDS)
print("\tWelcome to 'Guess My Number'!\n")
print("I'm thinking of a number between %d and %d." % BOUNDS)
print("Try to guess it in as few attempts as possible.\n")
for tries in range(TRIES_ALLOWED):
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
else:
print("You guessed it! The number was %d" % (the_number))
print("And it only took you %d tries!\n\n" % (tries + 1))
break
else:
print("You failed to guess in time!\n\n")
# Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
input("Press the enter key to exit.")
except:
passCode Snippets
print "You failed to guess in time!"print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")import random
BOUNDS = (1, 100)
TRIES_ALLOWED = 5
the_number = random.randint(*BOUNDS)
print("\tWelcome to 'Guess My Number'!\n")
print("I'm thinking of a number between %d and %d." % BOUNDS)
print("Try to guess it in as few attempts as possible.\n")
for tries in range(TRIES_ALLOWED):
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
else:
print("You guessed it! The number was %d" % (the_number))
print("And it only took you %d tries!\n\n" % (tries + 1))
break
else:
print("You failed to guess in time!\n\n")
# Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
input("Press the enter key to exit.")
except:
passContext
StackExchange Code Review Q#65140, answer score: 7
Revisions (0)
No revisions yet.