|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
例9.1 使用列表
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
--------------------------------------------------------------------------------
这个是书中的例子,因为是讲的2.X版本的,所以
这段:
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
实际似乎hi相当于3.X的:
print( 'These items are:',
for item in shoplist:
print item)
但是我实际操作的时候
>>> a
[1, 3, 5, 6, 7, 7, 8, 67, 923, 'wi', 'dags', 'agasg']
>>> print('these element are',
for i in a:
SyntaxError: invalid syntax
第一个问题:这里就直接语法错误了,是因为版本原因不能把for循环放print()里面吗?还是我自己不会用?
第二个问题:我自己又想了个办法,定义了个函数:
>>> def buy(a):
for i in a:
print(i)
>>> print('these element are',buy(a))
1
3
5
6
7
7
8
67
923
wi
dags
agasg
these element are None
结果打印出来的结果很像是系统在运行的时候,先运行了buy()函数,再运行了print()的感觉,请问
$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
要达成书中这样的输出,应该怎么弄?
把python2的程序改为3的可以这样操作。
- shoplist = ['apple', 'mango', 'carrot', 'banana']
- print('I have', len(shoplist),'items to purchase.')
- print('These items are:', end = ' ')
- for item in shoplist:
- print(item, end = ' ')
复制代码
|
|