1
name = input(str('Please enter your name'))
names= ('name1','name2','nameetc')
if name in names:
    print "hi",name

If I use this code and user inputs name1, I get an error name1 is not defined. If the user puts "name1" in quotes then it works. I could ask the user to put the name in quotes, but then how do I check to ensure that it was before continuing. Preferably I would only have to ask for the name though. If I replace each str in the list with an int the code works fine. How do I make it work with a str in a list?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Medullan
  • 55
  • 1
  • 2
  • 8

2 Answers2

3

You need to use raw_input(). In Python 2, input() tries to evaluate the entered string.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2

In python2 input evaluates the string the user types. So when you input name1, python tries to find the value of the variable name1. The variable doesn't exist and you get the not defined exception. Use raw_input instead that just returns the string:

name = raw_input('Please enter your name')
if name in ('name1', 'name2', 'nameetc'):
    print "hi",name
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57