简体   繁体   中英

Python Numbers Guessing Game

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)
  1. How do I alert the player of a guess that they've already previously guessed before?
  2. How do I make sure that the player can only input numbers as their guess? I'm stumped. Thanks!

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM