运行代码python2 / python3的差异(我需要在Python2中显式加载模块?)

时间:2016-07-24 17:13:43

标签: python python-3.x input module

我正在尝试学习python,我正在阅读“用python自动化无聊的东西”一书,我发现当我尝试使用ubuntu的'python hello.py'(python 2)执行下面的代码时,它会出错如果我使用'python3 hello.py'我根本没有问题。

我想了解为什么以及如果在较旧的python2中我必须在我的代码顶部显式“导入”任何内容才能使错误消失?另外如果python3包含一些“内置”导入的模块,我不需要再导入哪里可以找到它们的列表?

以下是代码:

# this program asks for my name and tells me the lenght of my name

print("Hello world!")
print('What is your name? ')
myName = input()
print('It is good to meet you, ' + myName)
print('The lenght of your name is: ')
print(len(myName))
print('What is your age? ')
myAge = input()
print('You will be ' + str(int(myAge) +1) + ' in a year.')

这是我观察到的:

xubuntu:~/Documents$ python hello.py
Hello world!
What is your name?
Test
Traceback (most recent call last):
  File "hello.py", line 5, in <module>
    myName = input()
  File "<string>", line 1, in <module>
NameError: name 'Giovanni' is not defined
xubuntu:~/Documents$ python3 hello.py
Hello world!
What is your name?
Test
It is good to meet you, Test
The lenght of your name is:
4
What is your age?
22
You will be 22 in a year.

感谢您帮助淘汰了一个菜鸟:)

0 个答案:

没有答案