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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With