【问题标题】:Understanding Global Names and Python2 and 3了解全局名称和 Python2 和 3
【发布时间】:2013-02-12 08:46:47
【问题描述】:

作为 Python 的新手,我正在学习 Python2 和 3 之间的一些区别。在完成 Python 课程时,似乎需要在代码中进行一些更改才能使其正常工作3. 下面是代码;

def clinic():
    print "In this space goes the greeting"
    print "Choose left or right"
    answer = raw_input("Type left or right and hit 'Enter'.")
    if answer == "LEFT" or answer == "Left" or answer == "left":
        print "Here is test answer if you chose Left."
    elif answer == "RIGHT" or answer == "Right" or answer == "right":
        print "Here is the test answer if you chose Right!"
    else:
        print "You didn't make a valid choice, please try again."
        clinic()

clinic()

要在 Python 3 中进行这项工作,需要更改打印语法(添加括号),但出现的另一个问题是错误“NameError: global name 'raw_input' is not defined”。我在学习中经常看到这个问题。当我在 Python2 中运行它时似乎没有出现,但在 3 中似乎需要将它声明为全局。但是,当我将“global raw_input”添加到函数中时,它似乎不起作用(在其他情况下,每次我这样做时它都起作用。)有人能告诉我我做错了什么吗?另外,我听说声明全局变量是在不必要时养成的坏习惯,那么处理它们的最佳方法是什么?

【问题讨论】:

标签: python python-2.7 python-3.x


【解决方案1】:

raw_input() 已在 Python 3 中重命名,请改用 input()(旧的 Python 2 input() 已被删除)。见PEP 3111

请参阅What's new in Python 3.0 了解详尽的概述。还有Dive into Python 3 overview

【讨论】:

  • 我绝对知道 input() 的作用。非常感谢!
【解决方案2】:

修改Martijn's answer,您可以针对这些小的不兼容性采取以下通用技巧:

try:
    input_func = raw_input
except NameError:
    raw_input = input

之后,您可以在 Py2 和 Py3 的脚本中使用 raw_inputunicodebyte 类型可能需要类似的东西。

既然您表示有兴趣从 >=Py2.7 迁移到 Py3,那么您应该知道 Python 2.7 主要是 Python 2.6,其中向后移植了很多 Py3 的东西。

所以,虽然 print 函数在技术上仍然是 Py2.7 中的一个语句,而在 Py3 中是一个函数,但 Py2.7 print 确实接受元组。这使得一些 Py3 语法在 Py2.7 中工作。简而言之,您可以只使用括号:

print("Here is the test answer if you chose Right!")

要打印一个空行,在两个版本中工作的最佳方法是

print("")

默认情况下不添加换行符的打印我求助于write(),例如:

import sys
sys.stdout.write("no newline here")
sys.stdout.write(" -- line continued here, and ends now.\n")

另一方面,对于很多 Py3 的东西,你实际上可以通过从 the future 导入东西来在 Py2.7 中启用完整的 Py3 语法:

from __future__ import print_function

那么你就不需要在write()print()之间切换了。

在实际应用程序中,这完全取决于您是否以及如何与其他人的代码(包、团队中的其他开发人员、代码发布要求)进行交互,以及您的 Python 版本更改路线图是什么。

【讨论】:

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