Hi,

I'm new to python and I am trying to write a 'Guess the number program'. I am however getting the following error message:

Traceback (most recent call last):
  File "C:\Users\fdama\Documents\python\GuessMyNumber.py", line 8, in <module>
    guess = false
NameError: name 'false' is not defined

I don't know why I am getting this error message. Are there such things as boolean variables in python?

Here is the code:

#Guess my Number game Ch 3

import random 
attempts = 1

number = random.randint(1,100)

guess = false

while guess == false:
    guess = input("Take a guess: ")
    if guess == number:
        print(" You guessed it! The number was " ,number)
        break
    elif guess < number:
        print("Higher...")
        attempts += 1
    elif guess > number:
        print("Lower...")
        attempts += 1
input("\n\n Press the enter key to exit")           

Thanks for your help.

Recommended Answers

All 3 Replies

In python there is a boolean type, but its states are True and False (note the capitalisation of the first letters)

So in your program all occurrences of false should be False.

Also, you are defining guess as a bool and then later you are using it as an int. I think you mean to use two variables here rather than one.
So 'guess' would probably be a good name for the int variable used to store the users current guess. But perhaps the boolean should be called something like 'isCorrect'

So the start of your program will look something like this:

#Guess my Number game Ch 3
import random
attempts = 1
number = random.randint(1,100)
isCorrect = False

while isCorrect == False:
    #... The rest of your code ...

Thanks for your help. And thanks for spotting my error. It works now.

But I believe that this is not the best way of writing the program. If you look at the while loop, the condition will never evaluate to true. Is this right?

But I believe that this is not the best way of writing the program. If you look at the while loop, the condition will never evaluate to true. Is this right?

Yes that loop will not work,only way that will work if you guess right on first attempt.
It better/clearer to use !=(not equal).
As long as guess !=(not equal) secret_number,the while loop will run.

So then it can look like this,see also that i use int(input("")).
so that we compare integer with integer(not string with integer).

#Python 3.x
import random

secret_number = random.randint(1,100)
attempts = 0
guess = 0
while guess != secret_number:
    guess = int(input("Enter Guess Here: ")) 
    if guess > secret_number:
        print('Lower...')
    elif guess < secret_number:
        print('Higher...')
    attempts += 1

print("You guessed it! The number was {0} in {1} attempts".format(secret_number, attempts))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.