目录
控制流
if语句
if 条件一:
执行一
elif 条件二:
执行二
else:
执行三
while语句
while 条件:
else:
for循环
for i in range(1,5):
else:
break语句
中止循环用,任何相应循环内中的else块都不会再执行。
continue语句
跳过本次循环剩下语句,继续下一次循环。
函数
def print_max(a,b):
if a > b:
print('The max is', a)
elif a = b:
print(a, 'is equal to', b)
else:
print('The max is', b)
关键字参数
def func(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 is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
可变参数
定义的函数内的参数数量是可变的,可通过星号实现。
*param :从此处开始直到结束的所有位置参数( Positional Arguments) 都将被收集并汇集成一个称为“param”的元组( Tuple) 。
**param : 从此处开始直至结束的所有关键字参数都将被收集并汇集成一个名为 param 的字典( Dictionary) 。
def total(a=5, *numbers, **phonebook):
print('a', a)
#遍历元组中的所有项目
for single_item in numbers:
print('single_item', single_item)
#遍历字典中的所有项目
for first_part, second_part in phonebook.items():
print(first_part,second_part)
print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))
a 10
single_item 1
single_item 2
single_item 3
Jack 1123
John 2231
Inge 1560
模块
import sys
from math import sqrt
print("Square root of 16 is", sqrt(16))
数据结构
列表 List
方括号括起,逗号分隔,可变。
# Define my shopping list
shopping_list = ['apple', 'orange', 'banana', 'watermelon']
print('I need to buy these things:', end=' ')
for item in shopping_list:
print(item, end=' ')
shopping_list.append('pear')
print('\n', shopping_list)
shopping_list.sort()
print('\n', shopping_list)
I need to buy these things: apple orange banana watermelon
['apple', 'orange', 'banana', 'watermelon', 'pear']
['apple', 'banana', 'orange', 'pear', 'watermelon']
元组 Tuple
括号括起,逗号隔开,不可变。
old_zoo = ('tiger', 'lion', 'kangaroo')
print(old_zoo, len(old_zoo))
new_zoo = 'camel', 'monkey', old_zoo
print(new_zoo, len(new_zoo))
print(new_zoo[2])
print(new_zoo[2][0])
('tiger', 'lion', 'kangaroo') 3
('camel', 'monkey', ('tiger', 'lion', 'kangaroo')) 3
('tiger', 'lion', 'kangaroo')
tiger
字典 Dictionary
链接键值(Keys)和值(Values),只能使用不可变的对象( 如字符串) 作为字典的键值, 但可以使用可变或不可变的对象作为字典中的值。
格式:
d = {key : value1 , key2 : value2}
ads = {'Violaine': 'vio@outlook.com', 'Guillaume': 'gui@gmail.com'}
print('The address of Guillaume is:', ads['Guillaume'])
del(ads['Violaine'])
print(len(ads))
ads['Violaine'] = 'vio@outlook.com'
for name, address in ads.items():
print('The address of {} is: {}:'.format(name, address))
The address of Guillaume is: gui@gmail.com
1
The address of Guillaume is: gui@gmail.com:
The address of Violaine is: vio@outlook.com:
序列 Sequence
列表、 元组和字符串可以看作序列( Sequence) 的某种表现形式。
序列的主要功能是资格测试( Membership Test) ( 也就是 in 与 not in 表达式) 和索引操作( Indexing Operations)。
切片( Slicing) 运算:(适用于列表、元组、字符串)
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation #
# 索引或“下标( Subscription) ”操作符 #
print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])
# Slicing on a list #
print('Item 1 to 3 is', shoplist[1:3])
print('Item 1 to end is', shoplist[1:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])
Item 0 is apple
Item 1 is mango
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 1 to end is ['mango', 'carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
name = 'swaroop'
print('Character 0 is', name[0])
# 从某一字符串中切片 #
print('characters 1 to 3 is', name[1:3])
print('characters 2 to end is', name[2:])
print('characters 1 to -1 is', name[1:-1])
print('characters start to end is', name[:])
Character 0 is s
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
shoplist = ['apple', 'mango', 'carrot', 'banana']
print(shoplist[::1])
print(shoplist[::2])
['apple', 'mango', 'carrot', 'banana']
['apple', 'carrot']
集合 Set
集合是简单对象的无序collection,只关心集合中的项目存在与否。
country = set(['China', 'France', 'US'])
print('China' in country)
print('Germany' in country)
True
False
引用
如果仅仅是将一个变量名赋予给另一个名称, 那么它们都将“查阅”同一个对象。
希望创建一份诸如序列等复杂对象的副本( 而非整数这种简单的对象( Object) ) , 必须使用切片操作来制作副本。
country = ['China', 'France', 'US']
# pays 只是指向同一对象的另一种名称
pays = country
del country[0]
print(country, pays)
# 通过生成一份完整的切片制作一份列表的副本
pays = country[:]
del pays[0]
print(country, pays)
['France', 'US'] ['France', 'US']
['France', 'US'] ['US']
字符串
name = 'Violaine'
if name.startswith('Vio'):
print('Yes, it starts with "Vio".')
if 'laine' in name:
print('Yes, it contains "laine".')
if name.find('io') != -1:
print('Yes, it contains "io".')
delimiter = '***'
namelist = ['Violaine', 'Guillaume']
print(delimiter.join(namelist))
Yes, it starts with "Vio".
Yes, it contains "laine".
Yes, it contains "io".
Violaine***Guillaume