【问题标题】:Code worked until more was added - now getting a NameError代码一直有效,直到添加更多代码 - 现在得到一个 NameError
【发布时间】:2016-11-14 23:38:31
【问题描述】:
# -*- coding: utf-8 -*-
#displays title

print ("          H___________________________________________   ")
print ("/========/| █░█ █▀▀█ █▀▀█ █░░ █▀▀█ █▀▀▄ █▀▀▄ \ ")
print ("|||||||||||-█̶▀̶▄̶ ̶█̶░̶░̶█̶ ̶█̶░̶░̶█̶ ̶█̶░̶░̶ ̶█̶▄̶▄̶█̶ ̶█̶░̶░̶█̶ ̶█̶░̶░̶█̶ -\ ")
print ("\========\|_▀̲░̲▀̲ ̲▀̲▀̲▀̲▀̲ ̲▀̲▀̲▀̲▀̲ ̲▀̲▀̲▀̲ ̲▀̲░̲░̲▀̲ ̲▀̲░̲░̲▀̲ ̲▀̲▀̲▀̲░̲ __\ ")
print ("          H ")
print ("          = ")

#intro
print ("Welcom to the land of kool")

#asks your name
name = input ("Can you tell me your name!")

#says hello
print ("Well hello",name,"!")

错误显示:

NameError: name '______' is not defined

【问题讨论】:

  • 我看不懂你的代码,也不懂你的问题。
  • 你用的是什么版本的 Python?
  • 另外,请展示一个示例运行。您可以从控制台复制并粘贴它。确保在输出的每行开头包含四个空格。
  • 我没有例外。
  • @nawi 这可能是因为您使用的是 Python 3.x 而 OP 使用的是 Python 2.x。这意味着OP需要使用raw_input()而不是input()

标签: python canopy


【解决方案1】:

根据您使用的 Python 版本,您可能需要使用..

name = raw_input("Can you tell me your name!")

查看此内容以供参考。 What's the difference between raw_input() and input() in python3.x?

【讨论】:

    【解决方案2】:

    TL;DR

    在 Python 2.x 中使用raw_input() 而不是input(),因为input()eval(raw_input)) 的“简写”。


    在 Python 2.7 中,您需要使用 raw_input() 而不是 input()raw_input() 允许您将用户输入作为字符串读取,而 input()eval(raw_input()) 的“简写”,它试图将您的用户输入评估为文字 Python 代码

    这在 python 2.x 文档中有记录:

    [input() is] 等价于eval(raw_input(prompt))

    此函数不会捕获用户错误。如果输入在语法上无效,则会引发 SyntaxError。如果评估期间出现错误,可能会引发其他异常。

    如果 readline 模块已加载,则 input() 将使用它来提供精细的行编辑和历史记录功能。

    考虑将raw_input() 函数用于用户的一般输入。

    然而,这后来在 Python 3.x 中进行了更改。在 Python 3.x 中,raw_input() 变成了input(),并且旧的输入(eval(raw_input()))被删除了。这记录在What's new in Python 3:

    PEP 3111:raw_input() 已重命名为 input()。也就是说,新的input() 函数从sys.stdin 中读取一行并将其返回,并去掉尾随的换行符。如果输入过早终止,它会引发EOFError。要获取 input() 的旧行为,请使用 eval(input())

    (强调我的)


    所以在 Python 2.x 中使用raw_input() 而不是input(),因为input()eval(raw_input)) 的“简写”。例如。变化:

    name = input ("Can you tell me your name!")

    name = raw_input ("Can you tell me your name!")

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多