Python 2にinputが現れるname「xxx」is not defined問題の原因と解決方法

1813 ワード

# coding=UTF-8
'''
Created on 2017 10 22 

@author: Dyna
'''
str_1 = input("Enter a string:")
str_2 = input("Enter another string:")

print ("str_1 is:"+str_1+" str_2 is:"+str_2)
print "str_1 is {} ,str_2 is {}".format(str_1, str_2)
以上はPythonの入力関数inputをテストするために使用されますが、次のような場合があります.
Enter a string:hello
Traceback (most recent call last):
  File "/Users/Dyna/Documents/workspace/TeachingPython/Test_IO_Format.py", line 7, in 
    str_1 = input("Enter a string:")
  File "/Users/Dyna/Downloads/Eclipse.app/Contents/Eclipse/plugins/org.python.pydev_4.5.5.201603221110/pysrc/pydev_sitecustomize/sitecustomize.py", line 141, in input
    return eval(raw_input(prompt))
  File "", line 1, in 
NameError: name 'hello' is not defined

helloを入力したとき、エラーを報告しました.
NameError: name 'hello' is not defined.
Pythonの公式サイトでドキュメントを検索しました.理由は以下の通りです.
Python 2.Xのinput関数では、文字列を入力するときに「」で拡張しなければならない合法的なPython式が読み取られます.私のPythonバージョンは2.7なので、この問題が発生します.Python 3では、inputはstrタイプをデフォルトで受け入れています.
解決方法:1、コンソールでパラメータを入力する時、それを1つの合法的なPython式に変えて、“”でそれを拡張します
2、raw_を使うinput、raw_inputは、すべての入力を文字列と見なし、文字列タイプを返します.
1、
Enter a string:"hello"
Enter another string:"Python"
str_1 is:hello str_2 is:Python
str_1 is hello ,str_2 is Python
2、
# coding=UTF-8
'''
Created on 2017 10 22 

@author: Dyna
'''
str_1 = raw_input("Enter a string:")
str_2 = raw_input("Enter another string:")

print ("str_1 is:"+str_1+" str_2 is:"+str_2)
print "str_1 is {} ,str_2 is {}".format(str_1, str_2)