4

When I enter

username = str(input("Username:"))

password = str(input("Password:"))

and after running the program, I fill in the input with my name and hit enter

username = sarang

I get the error

NameError: name 'sarang' is not defined

I have tried

username = '"{}"'.format(input("Username:"))

and

password = '"{}"'.format(input("Password:"))

but I end up getting the same error.

How do I convert the input into a string and fix the error?

vaultah
  • 44,105
  • 12
  • 114
  • 143
sarang.g
  • 53
  • 1
  • 1
  • 6

3 Answers3

8

Use raw_input() in Python 2.x and input() in Python 3.x to get a string.

You have two choices: run your code via Python 3.x or change input() to raw_input() in your code.

Python 2.x input() evaluates the user input as code, not as data. It looks for a variable in your existing code called sarang but fails to find it; thus a NameError is thrown.

Side note: you could add this to your code and call input_func() instead. It will pick the right input method automatically so your code will work the same in Python 2.x and 3.x:

input_func = None
try:
    input_func = raw_input
except NameError:
    input_func = input

# test it

username = input_func("Username:")
print(username)

Check out this question for more details.

jDo
  • 3,962
  • 1
  • 11
  • 30
0

You have to explicitly use raw_input(prompt), instead of just using input(prompt). As you are currently using Python 2.x which supports this type of formatting for receiving an input from user.

0

In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.

Since getting a string was almost always what you wanted, Python 3 does that with input().

Akash Kandpal
  • 3,126
  • 28
  • 25