了解全局名称和Python2和3

Kim*_*aru 2 python python-2.7 python-3.x

作为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()
Run Code Online (Sandbox Code Playgroud)

为了在Python 3中工作,需要更改打印语法(添加parens),但出现的另一个问题是错误"NameError:全局名称'raw_input'未定义".我在学习中经常看到这个问题.当我在Python2中运行它时似乎没有出现,但在3中它似乎需要将它声明为全局.但是,当我向函数添加"global raw_input"时,它似乎不起作用(在其他情况下,每次我都这样做时它都有效.)有人可以告诉我我做错了什么吗?另外,我听说声明全局变量是一种不习惯的坏习惯,那么处理它们的最佳方法是什么?

Mar*_*ers 7

raw_input()已经在Python 3中重命名,使用input()(而旧的Python 2 input()已被删除).见PEP 3111.

有关详尽的概述,请参阅Python 3.0中的新增功能.还有Dive into Python 3概述.