Spiro Cromwell
Spiro Cromwell

Reputation: 99

Why am I getting "NameError" from input()?

I am new and trying to create a simple "guess the number game":

import random
class Randgame :

    def __init__(self):
        pass

    def restart(self):
        response = input("Type Yes To Play Again!").lower()
        if response == "yes":
            self.play()
        else:
            print("Thanks for playing!")
            pass

    def play(self):
        guess = int(input("What's your guess?"))
        num = random.randint(0, 10)

        if guess == num:
            print("Correct!")
        else:
            print("Nope!")
        self.restart()


fun = Randgame()

fun.play()

All is well until I get to the restart() method. If I type "yes" into the console I get this response:

NameError: name 'yes' is not defined

I cannot figure this out to save my life and I don't know what to look up. Please help!

Upvotes: 0

Views: 58

Answers (1)

Luke B
Luke B

Reputation: 2121

In Python 2, getting input as plain text is done via raw_input instead of input. Python 3 changed the name of the function to input. The Python 2 version of input does eval(raw_input(prompt)), so it is trying to actually access a variable called yes, when you just want to get the string "yes".

Python 2 Docs

Upvotes: 1

Related Questions