148

I want to get a string from a user, and then to manipulate it.

testVar = input("Ask user for something.")

Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello

If the user types in Hello, I get the following error:

NameError: name 'Hello' is not defined

filler36
  • 456
  • 7
  • 13
Mike Lee
  • 1,693
  • 4
  • 14
  • 8
  • [See documentation](https://docs.python.org/2/library/functions.html#eval). As of python 2.7 `input` automatically calls `eval()` – 0x45 Apr 11 '18 at 12:26

8 Answers8

268

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
14

The function input will also evaluate the data it just read as python code, which is not really what you want.

The generic approach would be to treat the user input (from sys.stdin) like any other file. Try

import sys
sys.stdin.readline()

If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.

chuck
  • 493
  • 3
  • 9
  • 2
    also, if you are writing an interactive program, consider importing `readline` -- this will give features similar to bash (history out-of-the-box, auto-completion will require some legwork) – Foo Bah Feb 10 '11 at 17:10
  • Well done! I have used the same function for ages and it has ever worked well. – CFV Feb 16 '18 at 20:52
  • This is the best answer for both Python 2 and 3 compatibility. It works in both versions. At the end, of course, the end-of-line character is also added (in Linux is it `\n`), which does not interfere at all. In Python 3, the `raw_input` function is replaced by the `input` function, but for compatibility reasons it is a completely different function ! In Python 3, the `input` function also allows to insert a string, but in Python 2, the `input` function does not allow to insert a string (only the `raw_input` function allow the string, which is already removed in Python 3, unfortunately). – s3n0 Jan 05 '21 at 11:52
11

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

Mr. T
  • 11,960
  • 10
  • 32
  • 54
Projesh Bhoumik
  • 1,058
  • 14
  • 17
7

If you want to use input instead of raw_input in python 2.x,then this trick will come handy

    if hasattr(__builtins__, 'raw_input'):
      input=raw_input

After which,

testVar = input("Ask user for something.")

will work just fine.

Prav001
  • 343
  • 1
  • 5
  • 12
2
testVar = raw_input("Ask user for something.")
Artur Gaspar
  • 4,407
  • 1
  • 26
  • 28
0

My Working code with fixes:

import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)

correct= False
while(correct == False):
    guess1= input("Which number is the highest? "+ str(list) + ": ")
    if maxNum == guess1:
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
     print("Correct!")
     correct = True
else:
    print("Incorrect, try again")

correct= False
while(correct == False):
    guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
    if sqrtOne >= 2.0 and str(guess3) == "y":
        print("Correct!")
        correct = True
    elif sqrtOne < 2.0 and str(guess3) == "n":
        print("Correct!")
        correct = True
    else:
        print("Incorrect, try again")

print("Thanks for playing!")
st_443
  • 51
  • 1
  • 6
0

This is my work around to fail safe in case if i will need to move to python 3 in future.

def _input(msg):
  return raw_input(msg)
Derlin
  • 9,572
  • 2
  • 32
  • 53
Mak
  • 161
  • 5
-6

The issue seems to be resolved in Python version 3.4.2.

testVar = input("Ask user for something.")

Will work fine.

trinaldi
  • 2,872
  • 2
  • 32
  • 37
  • 3
    Python 3.x `input` is equivalent to Python 2.x `raw_input` (see https://docs.python.org/3.0/whatsnew/3.0.html#builtins); this is an issue specific to 2.x. – jonrsharpe Dec 16 '14 at 11:59