deffunc(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c=24)
func(c=50, a=100)
输出:
a is3and b is7and c is10
a is25and b is5and c is24
a is100and b is5and c is50
可变参数//以后再说
文档字符串
defprint_max(x, y):'''Prints the maximum of two numbers.打印两个数值中的最大数。
The two values must be integers.这两个数都应该是整数'''#第一行以句号结束# 如果可能,将其转换至整数类型
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
print_max(3, 5)
print(print_max.__doc__)
数据结构
列表
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'items to purchase.')
print('These items are:', end=' ')
#end=''过一个空格来结束输出工作,而不是通常的换行
for item in shoplist:
print(item,end='')
# 我会推荐你总是使用括号
# 来指明元组的开始与结束
# 尽管括号是一个可选选项。
# 明了胜过晦涩,显式优于隐式。
zoo = ('python', 'elephant', 'penguin')
print('Numberof animals in the zoo is', len(zoo))
new_zoo = 'monkey', 'camel', zoo
print('Numberof cages in the new zoo is', len(new_zoo))
print('All animals innew zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Numberof animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))
输出:
Number of cages in the new zoo is3All animals innew zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is5
# “ab”是地址(Address)簿(Book)的缩写
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print("Swaroop's address is", ab['Swaroop'])
# 删除一对键值—值配对
del ab['Spammer']
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
for name, address in ab.items():
print('Contact {} at {}'.format(name, address))
# 添加一对键值—值配对
ab['Guido'] = 'guido@python.org'if'Guido'inab:
print("\nGuido's address is", ab['Guido'])form
输出:
Swaroop's address is swaroop@swaroopch.com
There are 3 contacts in the address-book
Contact Swaroop at swaroop@swaroopch.com
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Guido's address is guido@python.org