RedbeardShanks RedbeardShanks - 7 months ago 16
Python Question

Guess the number game, error.

This is a game I am currently trying to make. I am coding this game in python 3.4. it doesn't run.

# this is a guess the number game!

import random
guesses = 0
name = input("what is your name?")
number = random.randint(1, 20)
print = name + ", I am thinking of a number between 1 and 20..."
while guesses << 7:
guess = int(raw_input("Take a guess."))
guesses = guesses + 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:
guesses = str(guesses)
print ("Good job," + name + "you guessed my number in" +guesses +"guesses!")
if guess != number:
number = str(number)
print ("Nah dude, better luck next time!")

Answer

I think you meant to use < instead of <<. << and >> are bit shift operators to the left and right respectively.

Your last two if conditions are also outside your loop, and don't make much sense. You're already checking if guess == number once and breaking if that condition is met. if guess != number your already checking this by using < and > respectively.

print = ...? print syntax is print(some_stuff, ...). Indentation is also off at the top, but assuming that's just due to posting your first question.

Also, raw_input is for python2 it's just input in python3. You could clean the print statements up some with % formatters or using .format.

Fixed code: (Python 3 version since that's whats tagged in the question...)

import random

name = input("what is your name?")
number = random.randint(1, 20)
#print("%s I am thinking of a number between 1 and 20..." % name)
print(name + " I am thinking of a number between 1 and 20...")

guesses = 0
while guesses < 7:
    guess = int(input("Take a guess."))
    guesses += 1

    if guess < number:
        print ("your guess is too low!")

    elif guess > number:
        print ("your guess is too high!")

    else:
        #print("Good job %s you guessed my number in %d guesses" % (name, guesses))
        print ("Good job, " + name + " you guessed my number in " + str(guesses) + " guesses!")
        break
Comments