input string in python 3

2019-01-26 08:24发布

I have string variable test, In Python 2.7 this works fine.

test = raw_input("enter the test") 
print test

But in Python 3.3. I use

test = input("enter the test") 
print test

with the input string sdas, and I get an error message

Traceback (most recent call last):

File "/home/ananiev/PycharmProjects/PigLatin/main.py",

line 5, in test = input("enter the test")

File "", line 1, in NameError: name 'sdas' is not defined

5条回答
狗以群分
2楼-- · 2019-01-26 08:37

You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print statement would throw up a SyntaxError before it ever prompted you for input.

The result is that you're using Python 2's input, which tries to eval your input (presumably sdas), finds that it's invalid Python, and dies.

查看更多
放我归山
3楼-- · 2019-01-26 08:37

In operating systems like Ubuntu python comes preinstalled. So the default version is python 2.7 you can confirm the version by typing below command in your terminal

python -V

if you installed it but didn't set default version you will see

python 2.7

in terminal. I will tell you how to set the default python version in Ubuntu.

A simple safe way would be to use an alias. Place this into ~/.bashrc or ~/.bash_aliases file:

alias python=python3

After adding the above in the file, run the command below:

source ~/.bash_aliases or source ~/.bashrc

now check python version again using python -V

if python version 3.x.x one, then the error is in your syntax like using print with parenthesis. change it to

test = input("enter the test")
print(test)
查看更多
淡お忘
4楼-- · 2019-01-26 08:39

I'd say the code you need is:

test = input("enter the test")
print(test)

Otherwise it shouldn't run at all, due to a syntax error. The print function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?

查看更多
5楼-- · 2019-01-26 08:42

sdas is being read as a variable. To input a string you need " "

查看更多
Ridiculous、
6楼-- · 2019-01-26 08:59

I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.

查看更多
登录 后发表回答