这段Python有什么问题?输入名称无效
def main():
print("This program generates computer usernames.n")
# get user's first and last names
first = input("Please enter your first name (all lowercase): ")
last = input("Please enter your last name (all lowercase): ")
# concatenate first initial with 7 chars of the last name
uname = first[0] + last[:7]
# output the username
print("Your username is:", uname)
main()
现在,运行程序的结果是——不知道这是怎么回事。
cd '/Users/ek/Desktop/' && '/usr/bin/pythonw' '/Users/ek/Desktop/fun.py' && echo Exit status: $? && exit 1
EKs-Mac-mini:~ ek$ cd '/Users/ek/Desktop/' && '/usr/bin/pythonw' '/Users/ek/Desktop/fun.py' && echo Exit status: $? && exit 1
This program generates computer usernames.
Please enter your first name (all lowercase): Bob
Traceback (most recent call last):
File "/Users/ek/Desktop/fun.py", line 14, in <module>
main()
File "/Users/ek/Desktop/fun.py", line 5, in main
first = input("Please enter your first name (all lowercase): ")
File "<string>", line 1, in <module>
NameError: name 'Bob' is not defined
EKs-Mac-mini:Desktop ek$
不要把input
改成raw_input
,这样你的脚本就能在Python 2中运行了,你可以添加一个shebang行,这样终端shell就能在Python 3中运行你的脚本了。
shebang行告诉shell(1)该文件是一个shell脚本,(2)使用哪个Python解释器,(3)在哪里找到这个解释器(文件路径)。
那么你应该能够在终端运行$ fun.py
。您不需要指定$ python3 fun.py
。
写shebang的两种方法
1)把这行放在你的fun.py
文件的顶部:
#! /usr/bin/env python3
这是推荐的编写shebang行的方式。它适用于类unix操作系统(包括Linux、Mac OS X等)
2)或者,指定安装Python 3的位置的完整绝对路径。在你的例子中:
#! /Library/Frameworks/Python.framework/Versions/3.5/bin/python3
如果您不知道绝对路径,请使用Terminal命令$ which python3
找到它。
注:作为替代方案,将系统上的Python默认版本从Python 2更改为Python 3也可能有效。但它有其他不好的后果,所以不要这样做。
在您的代码中,将input
(在Python 3中工作)更改为raw_input
(在Python 2中工作),看看会发生什么。
要确认你使用的是哪个Python版本,运行下面的Terminal命令:python --version