Programing

input () error-NameError : 이름 '…'이 (가) 정의되지 않았습니다

lottogame 2020. 5. 13. 07:59
반응형

input () error-NameError : 이름 '…'이 (가) 정의되지 않았습니다


이 간단한 파이썬 스크립트를 실행하려고 할 때 오류가 발생합니다.

input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

"dude"라고 입력하면 오류가 발생합니다.

line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <module>
NameError: name 'dude' is not defined

Mac OS X 10.9.1을 실행 중이며 Python 3.3 설치와 함께 제공된 Python Launcher 앱을 사용하여 스크립트를 실행하고 있습니다.

편집 : 어떻게 든이 스크립트를 2.7로 실행하고 있음을 깨달았습니다. 실제 질문은 버전 3.3으로 스크립트를 어떻게 실행합니까? 내 응용 프로그램 폴더의 Python 3.3 폴더 안에있는 Python Launcher 앱 위에 스크립트를 끌어서 놓으면 3.3을 사용하여 스크립트를 시작할 것이라고 생각했습니다. 이 방법으로 여전히 2.7로 스크립트를 시작합니다. 3.3을 어떻게 사용합니까?


TL; DR

inputPython 2.7의 함수는 입력 한 내용을 Python 표현식으로 평가합니다. 단순히 문자열을 읽으려면 raw_inputPython 2.7에서 함수 를 사용하십시오.이 기능은 읽은 문자열을 평가하지 않습니다.

Python 3.x를 사용하는 경우 raw_input이름이로 변경되었습니다 input. 파이썬 3.0 릴리스 노트 인용 ,

raw_input()로 이름이 변경되었습니다 input(). 즉, new input()함수는 줄을 읽어 sys.stdin후행 줄 바꿈을 제거한 상태로 반환합니다. 이 제기 EOFError입력이 조기 종료되는 경우. 의 이전 동작 얻으려면 input(), 사용eval(input())


Python 2.7 에는 사용자 입력을 받아들이는 데 사용할 수있는 두 가지 함수가 있습니다. 하나는 input다른 하나는 raw_input입니다. 당신은 다음과 같이 그들 사이의 관계를 생각할 수 있습니다

input = eval(raw_input)

이 코드를 더 잘 이해하려면 다음 코드를 고려하십시오.

>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'

input사용자로부터 문자열을 받아 현재 Python 컨텍스트에서 문자열을 평가합니다. 입력 dude으로 입력 dude하면 값에 바인딩되어 thefourtheye평가 결과가 thefourtheye되고에 할당됩니다 input_variable.

현재 파이썬 컨텍스트에없는 다른 것을 입력하면 실패합니다 NameError.

>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'dummy' is not defined

Python 2.7의 보안 고려 사항 input:

모든 사용자 유형이 평가되므로 보안 문제도 부과됩니다. 예를 들어, os프로그램을 사용하여 이미 모듈을 로드 import os한 다음 사용자는

os.remove("/etc/hosts")

이것은 파이썬에 의해 함수 호출 표현식으로 평가되어 실행될 것입니다. 높은 권한으로 Python을 실행하면 /etc/hosts파일이 삭제됩니다. 얼마나 위험한가요?

이를 설명하기 위해 input함수를 다시 실행 해 봅시다 .

>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude

이제 input("Enter your name: ")실행될 사용자 입력을 기다리며 사용자 입력은 유효한 Python 함수 호출이므로 호출됩니다. 그래서 우리는 Enter your name again:다시 프롬프트를 보게 됩니다.

따라서 다음 raw_input과 같은 기능 을 사용하는 것이 좋습니다.

input_variable = raw_input("Enter your name: ")

결과를 다른 유형으로 변환해야하는 경우 적절한 함수를 사용하여에서 반환 된 문자열을 변환 할 수 있습니다 raw_input. 예를 들어 입력을 정수로 읽으려면 이 답변에int 표시된 대로 함수를 사용하십시오 .

In python 3.x, there is only one function to get user inputs and that is called input, which is equivalent to Python 2.7's raw_input.


You are running Python 2, not Python 3. For this to work in Python 2, use raw_input.

input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)

Since you are writing for Python 3.x, you'll want to begin your script with:

#!/usr/bin/env python3

If you use:

#!/usr/bin/env python

It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #! (aka the shebang).

If your scripts just start with:

#! python

Then you can change it to:

#! python3

Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.

The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.


You should use raw_input because you are using python-2.7. When you use input() on a variable (for example: s = input('Name: ')), it will execute the command ON the Python environment without saving what you wrote on the variable (s) and create an error if what you wrote is not defined.

raw_input() will save correctly what you wrote on the variable (for example: f = raw_input('Name : ')), and it will not execute it in the Python environment without creating any possible error:

input_variable = raw_input('Enter Your Name : ')
print("Your Name Is  : " + (input_variable))

You could either do:

x = raw_input("enter your name")
print "your name is %s " % x

or:

x = str(input("enter your name"))
print "your name is %s" % x

For python 3 and above

s = raw_input()

it will solve the problem on pycharm IDE if you are solving on online site exactly hackerrank then use:

s = input()

input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

You have to enter input in either single or double quotes

Ex:'dude' -> correct

    dude -> not correct

For anyone else that may run into this issue, turns out that even if you include #!/usr/bin/env python3 at the beginning of your script, the shebang is ignored if the file isn't executable.

To determine whether or not your file is executable:

  • run ./filename.py from the command line
  • if you get -bash: ./filename.py: Permission denied, run chmod a+x filename.py
  • run ./filename.py again

If you've included import sys; print(sys.version) as Kevin suggested, you'll now see that the script is being interpreted by python3


We are using the following that works both python 2 and python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))

I also encountered this issue with a module that was supposed to be compatible for python 2.7 and 3.7

what i found to fix the issue was importing:

from six.moves import input

this fixed the usability for both interpreters

you can read more about the six library here


Good contributions the previous ones.

import sys; print(sys.version)

def ingreso(nombre):
    print('Hi ', nombre, type(nombre))

def bienvenida(nombre):
    print("Hi "+nombre+", bye ")

nombre = raw_input("Enter your name: ")

ingreso(nombre)
bienvenida(nombre)

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
Enter your name: Joe
('Hi ', 'Joe', &lttype 'str'>)
Hi Joe, bye 

Your name: Joe
Joe

Thanks!


You can change which python you're using with your IDE, if you've already downloaded python 3.x it shouldn't be too hard to switch. But your script works fine on python 3.x, I would just change

print ("your name is" + input_variable)

to

print ("your name is", input_variable)

Because with the comma it prints with a whitespace in between your name is and whatever the user inputted. AND: if you're using 2.7 just use raw_input instead of input.

참고URL : https://stackoverflow.com/questions/21122540/input-error-nameerror-name-is-not-defined

반응형