Reputation:
I'm a beginner programmer learning Python (using version 2.7.4) and I've made this number guessing game. Here's my code so far for it:
import random
name = raw_input("Hi there! What\'s your name?\n")
print "Well, " + name + ", I am thinking of a number between 1 and 100"
number = random.randint(1,100)
guess = int(raw_input("Take a guess:\n"))
count = 1
while guess != number:
if guess < number:
print "Sorry, your guess is too low."
if guess > number:
print "Sorry, your guess is too high."
count += 1
guess = int(raw_input("Take another guess\n"))
print "Good job, %s! You guessed my number in %d guesses!" % (name ,count)
Upvotes: 1
Views: 1114
Reputation: 370
The answer for question one make a list:
while run:
geusslist = []
number = raw_input("Make A Geuss")
geusslist.extend((number))
if print_nums:
print "You Have Guessed:"
print geusslist
If this code is ran and the player guesses 10, 20, 30, 40, 50 it should return
>>> You Have Geussed:
>>> [10, 20, 30, 40, 50]
As for question two i think 'Raymond Hettinger' answered that above ^ very well.
Upvotes: 0
Reputation: 226544
For the first question, use a set to track the previous input values:
seen = set()
while guess != number:
if guess < number:
print "Sorry, your guess is too low."
if guess > number:
print "Sorry, your guess is too high."
count += 1
while True:
guess = int(raw_input("Take another guess\n"))
if guess in seen:
print "Oops, you have guess than one before"
continue
else:
seen.add(guess)
break
For the second question, you could use the isinstance() function, but there isn't much of a need. The int() function will check the input for you and will raise an exception if you did not get an integer input. If you would like, you could catch that exception and add a nice error message:
try:
guess = int(raw_input("Take another guess\n"))
except ValueError:
print "Sorry, I expected an integer"
Upvotes: 2