GitHub项目地址
https://github.com/Asabeneh/30-Days-Of-Python
Day1-介绍
介绍python历史及安装操作
1. 注释
- 单行注释使用 ‘’#’’ 符号
- 多行注释:
''' '''或""" """
使用三个引号(注意:长字符串也可以用三引号来定义)
2. 数据类型
数字型(Number)
整数(正,负,零);0,1,2,-2,-3
浮点数;1.1,3.4,-3.4,-5.54,0.0
复数;1+j,2+2j,-3+-2j
字符串(Strings)
单引号或双引号下的一个或多个字符的集合,如果不只一个句子则使用三引号
'abc' "abc" """ a b v """ ''' a b c '''
布尔值(Booleans)
True:正确 False:错误
列表(list)
是一个有序集合,允许存储不同的数据类型,允许重复成员
[1,2,3,4,5,5] ['a','b','c','d'] [3.2,45.1,5.4] [1,'a',True,9.3]
字典(Dictionary)
字典对象是键值对格式的无序数据的集合,不允许重复成员
{ 'sky':'blue', 'cloudy':'max', 'data':12, 'status':True, 'age':1.2, 'name':['first_name','last_name'] }
元组(Tuple)
存储不同数据类型的有序集合,元组一旦创建不可修改,允许重复成员
(1,'a',True)
集合(Set)
类似于数学定义上的集合,拥有,唯一性,无序性,确定性
只能存储不可变数据类型,如整数,浮点数,字符串,元组等,无法存储列表,字典等可变类型
因为集合是无序的,所以无法使用下标的方式进行索引,只能通过循环的方式进行读取
{1,2,'4'} 空集合的定义方式:a=set([])
- ==数据类型的检测使用python自带的
type()
函数==
3. 数据类型强制转换
int(), str(), float(), list(), set()
Day2-变量,内置函数
1. 内置函数
内置函数全局可用,无需导入或配置,常用内置函数如下
2. 变量
变量的作用是将数据暂存在内存中
变量命名规则
- 必须以字母或下划线开头
- 不能以数字开头
- 只能包含字母数字和下划线(A-z、0-9、_)
- 变量名区分大小写
python标准的命名法是“蛇形命名法”,即多个单词之间用 ’ _ ‘ 分割
可以在一行中同时声明多个变量
a,b,c=1,2,3
Day3-运算符
1. 赋值运算符
2. 算术运算符
# Arithmetic Operations in Python
# Integers
print('Addition: ', 1 + 2) # 3
print('Subtraction: ', 2 - 1) # 1
print('Multiplication: ', 2 * 3) # 6
print ('Division: ', 4 / 2) # 2.0 Division in Python gives floating number
print('Division: ', 6 / 2) # 3.0
print('Division: ', 7 / 2) # 3.5
print('Division without the remainder: ', 7 // 2) # 3, gives without the floating number or without the remaining
print ('Division without the remainder: ',7 // 3) # 2
print('Modulus: ', 3 % 2) # 1, Gives the remainder
print('Exponentiation: ', 2 ** 3) # 9 it means 2 * 2 * 2
# Floating numbers
print('Floating Point Number, PI', 3.14)
print('Floating Point Number, gravity', 9.81)
# Complex numbers
print('Complex number: ', 1 + 1j)
print('Multiplying complex numbers: ',(1 + 1j) * (1 - 1j))
3. 比较运算符
print(3 > 2) # True, because 3 is greater than 2
print(3 >= 2) # True, because 3 is greater than 2
print(3 < 2) # False, because 3 is greater than 2
print(2 < 3) # True, because 2 is less than 3
print(2 <= 3) # True, because 2 is less than 3
print(3 == 2) # False, because 3 is not equal to 2
print(3 != 2) # True, because 3 is not equal to 2
print(len('mango') == len('avocado')) # False
print(len('mango') != len('avocado')) # True
print(len('mango') < len('avocado')) # True
print(len('milk') != len('meat')) # False
print(len('milk') == len('meat')) # True
print(len('tomato') == len('potato')) # True
print(len('python') > len('dragon')) # False
# Comparing something gives either a True or False
print('True == True: ', True == True)
print('True == False: ', True == False)
print('False == False:', False == False)
- is 如果两个变量是同一个对象,返回true
- is not 如果两个变量不是同一个对象,返回true
- in 如果查询的列表包含某个项目,返回true
- not in 如果查询的列表没有包含某个项目,返回true
print('1 is 1', 1 is 1) # True - because the data values are the same
print('1 is not 2', 1 is not 2) # True - because 1 is not 2
print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
print('B in Asabeneh', 'B' in 'Asabeneh') # False - there is no uppercase B
print('coding' in 'coding for all') # True - because coding for all has the word coding
print('a in an:', 'a' in 'an') # True
print('4 is 2 ** 2:', 4 is 2 ** 2) # True
4. 逻辑运算符
print(3 > 2 and 4 > 3) # True - because both statements are true
print(3 > 2 and 4 < 3) # False - because the second statement is false
print(3 < 2 and 4 < 3) # False - because both statements are false
print('True and True: ', True and True)
print(3 > 2 or 4 > 3) # True - because both statements are true
print(3 > 2 or 4 < 3) # True - because one of the statements is true
print(3 < 2 or 4 < 3) # False - because both statements are false
print('True or False:', True or False)
print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False
print(not True) # False - Negation, the not operator turns true to false
print(not False) # True
print(not not True) # True
print(not not False) # False
Day4-字符串
1. 创建字符串
文本是字符串数据类型,任何以文本形式写入的数据类型都是字符串。
单、双、三引号下的任何数据都是字符串
a='a'
b="b"
c="""c"""
d='''d'''
2. 字符串连接
使用“+”字符进行连接
a='a'
b='b'
c=a+b
print(c) #输出“ab”
3. 字符串中的转义字符
在python和其他编程语言中,\ 后面跟一个字符就是转义字符
- \n 换行
- \t 制表符(八个空格)
- \\ 反斜杠
- \‘ 单引号
- \“ 双引号
print('I hope everyone is enjoying the Python Challenge.\nAre you ?') # line break
print('Days\tTopics\tExercises') # adding tab space or 4 spaces
print('Day 1\t3\t5')
print('Day 2\t3\t5')
print('Day 3\t3\t5')
print('Day 4\t3\t5')
print('This is a backslash symbol (\\)') # To write a backslash
print('In every programming language it starts with \"Hello, World!\"') # to write a double quote inside a single quote
# output
I hope every one is enjoying the Python Challenge.
Are you ?
Days Topics Exercises
Day 1 5 5
Day 2 6 20
Day 3 5 23
Day 4 1 35
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
4. 字符串格式
python中有多种格式化字符串的方法
旧字符串格式
“%”运算符用于格式化一组包含在“元组”中的变量以及格式化字符串,其中包含普通文本和“参数说明符”,特殊符号,如“%s”,”%d”,”%f”,”%.num of” 官方文档:https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html
# Strings only first_name = 'Asabeneh' last_name = 'Yetayeh' language = 'Python' formated_string = 'I am %s %s. I teach %s' %(first_name, last_name, language) print(formated_string) # Strings and numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the point python_libraries = ['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas'] formated_string = 'The following are python libraries:%s' % (python_libraries) print(formated_string) # "The following are python libraries:['Django', 'Flask', 'NumPy', 'Matplotlib','Pandas']"
新字符串格式化(python3中引入)
使用format
first_name = 'Asabeneh' last_name = 'Yetayeh' language = 'Python' formated_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language) print(formated_string) a = 4 b = 3 print('{} + {} = {}'.format(a, b, a + b)) print('{} - {} = {}'.format(a, b, a - b)) print('{} * {} = {}'.format(a, b, a * b)) print('{} / {} = {:.2f}'.format(a, b, a / b)) # limits it to two digits after decimal print('{} % {} = {}'.format(a, b, a % b)) print('{} // {} = {}'.format(a, b, a // b)) print('{} ** {} = {}'.format(a, b, a ** b)) # output 4 + 3 = 7 4 - 3 = 1 4 * 3 = 12 4 / 3 = 1.33 4 % 3 = 1 4 // 3 = 1 4 ** 3 = 64 # Strings and numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of a circle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal print(formated_string)
“ f ”表达式(python3.6+新特性)
-
a = 4 b = 3 print(f'{a} + {b} = {a +b}') print(f'{a} - {b} = {a - b}') print(f'{a} * {b} = {a * b}') print(f'{a} / {b} = {a / b:.2f}') print(f'{a} % {b} = {a % b}') print(f'{a} // {b} = {a // b}') print(f'{a} ** {b} = {a ** b}') #output 4 + 3 = 7 4 - 3 = 1 4 * 3 = 12 4 / 3 = 1.33 4 % 3 = 1 4 // 3 = 1 4 ** 3 = 64
-
5. python字符串作为字符序列
python中的字符串是由字符序列组合而成,并和其他有序对象序列(如列表和元组)共享基本访问方法
language = 'Python' a,b,c,d,e,f = language # 将序列字符解包成变量 print(a) # P print(b) # y print(c) # t print(d) # h print(e) # o print(f) # n
按索引访问字符串中的字符
正索引 language = 'Python' first_letter = language[0] print(first_letter) # P second_letter = language[1] print(second_letter) # y last_index = len(language) - 1 last_letter = language[last_index] print(last_letter) # n
负索引 language = 'Python' last_letter = language[-1] print(last_letter) # n second_last = language[-2] print(second_last) # o
切片
用于分割字符串
language = 'Python' first_three = language[0:3] # starts at zero index and up to 3 but not include 3 print(first_three) #Pyt last_three = language[3:6] print(last_three) # hon # Another way last_three = language[-3:] print(last_three) # hon last_three = language[3:] print(last_three) # hon
字符串反转
greeting = 'Hello, World!' print(greeting[::-1]) # !dlroW ,olleH
切片时跳过某些字符
language = 'Python' pto = language[0:6:2] # print(pto) # Pto
6. 字符串方法
capitalize():将字符串的第一个字符转换为大写字母
count():返回字符串中子字符串的出现次数,count(substring, start=.., end=..)。start 是计数的起始索引,end 是要计数的最后一个索引。
endswith():检查字符串是否以指定的结尾结尾
expandtabs():用空格替换制表符,默认制表符大小为8。它需要制表符大小参数
find():返回子字符串第一次出现的索引,如果没有找到返回-1
rfind():返回子串最后一次出现的索引,如果没有找到返回-1
index():返回子字符串的最低索引,附加参数指示开始和结束索引(默认 0 和字符串长度 - 1)。如果未找到子字符串,则会引发 valueError。
rindex():返回子字符串的最高索引,附加参数指示开始和结束索引(默认 0 和字符串长度 - 1)
isalnum():检查字母数字字符
isalpha():检查是否所有字符串元素都是字母字符(az 和 AZ)
isdecimal():检查字符串中的所有字符是否都是十进制 (0-9)
isdigit():检查字符串中的所有字符是否都是数字(0-9 和其他一些用于数字的 unicode 字符)
isnumeric():检查字符串中的所有字符是否都是数字或数字相关(就像 isdigit(),只是接受更多的符号,比如 ½)
isidentifier():检查一个有效的标识符——它检查一个字符串是否是一个有效的变量名
islower():检查字符串中的所有字母字符是否都是小写的
isupper():检查字符串中的所有字母字符是否都是大写的
join():返回一个连接的字符串
strip():从字符串的开头和结尾删除所有给定的字符
replace():用给定的字符串替换子字符串
split():拆分字符串,使用给定的字符串或空格作为分隔符
title():返回标题大小写的字符串
swapcase():将所有大写字符转换为小写,将所有小写字符转换为大写字符
startswith():检查字符串是否以指定的字符串开头
Day5-列表
1. 创建列表方法
使用list方法
a=list() #定义一个空列表
使用“ [] ”
a=[] #定义一个空列表
非空列表
a=list((1,2,3)) b=list([1,2,3,4]) c=[1,2,3,4,5]
查询列表长度
#列表的长度为列表中的元素个数 fruits = ['banana', 'orange', 'mango', 'lemon'] # list of fruits vegetables = ['Tomato', 'Potato', 'Cabbage','Onion', 'Carrot'] # list of vegetables animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products web_techs = ['HTML', 'CSS', 'JS', 'React','Redux', 'Node', 'MongDB'] # list of web technologies countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] # Print the lists and its length print('Fruits:', fruits) print('Number of fruits:', len(fruits)) print('Vegetables:', vegetables) print('Number of vegetables:', len(vegetables)) print('Animal products:',animal_products) print('Number of animal products:', len(animal_products)) print('Web technologies:', web_techs) print('Number of web technologies:', len(web_techs)) print('Countries:', countries) print('Number of countries:', len(countries)) output Fruits: ['banana', 'orange', 'mango', 'lemon'] Number of fruits: 4 Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] Number of vegetables: 5 Animal products: ['milk', 'meat', 'butter', 'yoghurt'] Number of animal products: 4 Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] Number of web technologies: 7 Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] Number of countries: 5
2.列表索引
正索引
正索引从0开始
下图表示列表索引开始的位置
fruits = ['banana', 'orange', 'mango', 'lemon'] first_fruit = fruits[0] # we are accessing the first item using its index print(first_fruit) # banana second_fruit = fruits[1] print(second_fruit) # orange last_fruit = fruits[3] print(last_fruit) # lemon # Last index last_index = len(fruits) - 1 last_fruit = fruits[last_index]
反索引
负索引从-1开始,
fruits = ['banana', 'orange', 'mango', 'lemon'] first_fruit = fruits[-4] last_fruit = fruits[-1] second_last = fruits[-2] print(first_fruit) # banana print(last_fruit) # lemon print(second_last) # mango
列表展开(list unpacking)
*+一个变量在python中表示返回一个列表
当使用列表展开时,出现类似于
*a或**a这样的变量后还有变量,则后面的变量的值的索引从-1开始
# First Example fruits = ['banana', 'orange', 'mango', 'lemon','lime','apple'] first_fruit, second_fruit, third_fruit, *rest = lst print(first_fruit) # banana print(second_fruit) # orange print(third_fruit) # mango print(rest) # ['lemon','lime','apple'] # Second Example about unpacking list first, second, third,*rest, tenth = [1,2,3,4,5,6,7,8,9,10] print(first) # 1 print(second) # 2 print(third) # 3 print(rest) # [4,5,6,7,8,9] print(tenth) # 10 # Third Example about unpacking list countries = ['Germany', 'France','Belgium','Sweden','Denmark','Finland','Norway','Iceland','Estonia'] gr, fr, bg, sw, *scandic, es = countries print(gr) print(fr) print(bg) print(sw) print(scandic) print(es)
3. 列表切片
正索引切片
通过指定开始和结束位置以及跨度值来进行切片,切片的结果为一个新的切片
fruits = ['banana', 'orange', 'mango', 'lemon'] all_fruits = fruits[0:4] # it returns all the fruits # this will also give the same result as the one above all_fruits = fruits[0:] # if we don't set where to stop it takes all the rest orange_and_mango = fruits[1:3] # it does not include the first index orange_mango_lemon = fruits[1:] orange_and_lemon = fruits[::2] # here we used a 3rd argument, step. It will take every 2cnd item - ['banana', 'mango']
负索引切片
开始位置为-1
fruits = ['banana', 'orange', 'mango', 'lemon'] all_fruits = fruits[-4:] # it returns all the fruits orange_and_mango = fruits[-3:-1] # it does not include the last index,['orange', 'mango'] orange_mango_lemon = fruits[-3:] # this will give starting from -3 to the end,['orange', 'mango', 'lemon'] reverse_fruits = fruits[::-1] # a negative step will take the list in reverse order,['lemon', 'mango', 'orange', 'banana']
4. 修改列表
通过索引来修改列表中的值
fruits = ['banana', 'orange', 'mango', 'lemon'] fruits[0] = 'avocado' print(fruits) # ['avocado', 'orange', 'mango', 'lemon'] fruits[1] = 'apple' print(fruits) # ['avocado', 'apple', 'mango', 'lemon'] last_index = len(fruits) - 1 fruits[last_index] = 'lime' print(fruits) # ['avocado', 'apple', 'mango', 'lime']
5. 检查列表中是否包含某个元素
通过“ in ”运算符检查某个值是否是列表成员
fruits = ['banana', 'orange', 'mango', 'lemon'] does_exist = 'banana' in fruits print(does_exist) # True does_exist = 'lime' in fruits print(does_exist) # False
6. 添加元素到列表
使用append,会添加到现有列表的尾部
# syntax lst = list() lst.append(item) fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.append('apple') print(fruits) # ['banana', 'orange', 'mango', 'lemon','apple'] fruits.append('lime') # ['banana', 'orange', 'mango', 'lemon','apple','lime'] print(fruits)
insert()
方法插入数据在列表的指定索引处插入单个数据,同时从原本索引到结尾的数据右移一个位置
# syntax语法 lst = ['item1', 'item2'] lst.insert(index, item) fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.insert(2, 'apple') # insert apple between orange and mango print(fruits) # ['banana', 'orange', 'apple', 'mango','lemon'] fruits.insert(3, 'lime') # ['banana', 'orange', 'apple', 'lime', 'mango', 'lemon'] print(fruits)
7. 从列表中删除数据
使用
remove()
方法# syntax lst = ['item1', 'item2'] lst.remove(item) fruits = ['banana', 'orange', 'mango', 'lemon', 'banana'] fruits.remove('banana') print(fruits) # ['orange', 'mango', 'lemon', 'banana'] - this method removes the first occurrence of the item in the list fruits.remove('lemon') print(fruits) # ['orange', 'mango', 'banana']
使用
pop()
方法通过指定索引来进行删除,如果未指定索引则删除最后一项
# syntax lst = ['item1', 'item2'] lst.pop() # last item lst.pop(index) fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.pop() print(fruits) # ['banana', 'orange', 'mango'] fruits.pop(0) print(fruits) # ['orange', 'mango']
使用
del()
方法可以删除指定的索引,也可以删除指定的索引范围,还可以完全删除列表
# syntax lst = ['item1', 'item2'] del lst[index] # only a single item del lst # to delete the list completely fruits = ['banana', 'orange', 'mango', 'lemon', 'kiwi', 'lime'] del fruits[0] print(fruits) # ['orange', 'mango', 'lemon', 'kiwi', 'lime'] del fruits[1] print(fruits) # ['orange', 'lemon', 'kiwi', 'lime'] del fruits[1:3] # this deletes items between given indexes, so it does not delete the item with index 3! print(fruits) # ['orange', 'lime'] del fruits print(fruits) # This should give: NameError: name 'fruits' is not defined
使用
clear()
方法清空列表
# syntax lst = ['item1', 'item2'] lst.clear() fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.clear() print(fruits) # []
8. 列表拼接
“ + ”拼接
# syntax list3 = list1 + list2 positive_numbers = [1, 2, 3, 4, 5] zero = [0] negative_numbers = [-5,-4,-3,-2,-1] integers = negative_numbers + zero + positive_numbers print(integers) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] fruits = ['banana', 'orange', 'mango', 'lemon'] vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] fruits_and_vegetables = fruits + vegetables print(fruits_and_vegetables ) # ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
extend()
方法拼接# syntax list1 = ['item1', 'item2'] list2 = ['item3', 'item4', 'item5'] list1.extend(list2) num1 = [0, 1, 2, 3] num2= [4, 5, 6] num1.extend(num2) print('Numbers:', num1) # Numbers: [0, 1, 2, 3, 4, 5, 6] negative_numbers = [-5,-4,-3,-2,-1] positive_numbers = [1, 2, 3,4,5] zero = [0] negative_numbers.extend(zero) negative_numbers.extend(positive_numbers) print('Integers:', negative_numbers) # Integers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] fruits = ['banana', 'orange', 'mango', 'lemon'] vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] fruits.extend(vegetables) print('Fruits and vegetables:', fruits ) # Fruits and vegetables: ['banana', 'orange', 'mango', 'lemon', 'Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
9. 计算列表中的项目
count()
方法返回某一个数据在列表中出现的次数# syntax lst = ['item1', 'item2'] lst.count(item) fruits = ['banana', 'orange', 'mango', 'lemon'] print(fruits.count('orange')) # 1 ages = [22, 19, 24, 25, 26, 24, 25, 24] print(ages.count(24)) # 3
10. 查找列表中某个数据对应的索引下标
index()
方法返回列表中的索引# syntax lst = ['item1', 'item2'] lst.index(item) fruits = ['banana', 'orange', 'mango', 'lemon'] print(fruits.index('orange')) # 1 ages = [22, 19, 24, 25, 26, 24, 25, 24] print(ages.index(24)) # 2, the first occurrence
11. 反转列表
reverse()
方法反转列表顺序# syntax lst = ['item1', 'item2'] lst.reverse() fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.reverse() print(fruits) # ['lemon', 'mango', 'orange', 'banana'] ages = [22, 19, 24, 25, 26, 24, 25, 24] ages.reverse() print(ages) # [24, 25, 24, 26, 25, 24, 19, 22]
12. 列表排序
sort()
按照升序重新排序列表项并修改原始列表,如果sort中的reverse参数为“true”,则降序排序# syntax lst = ['item1', 'item2'] lst.sort() # ascending lst.sort(reverse=True) # descending fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.sort() print(fruits) # sorted in alphabetical order, ['banana', 'lemon', 'mango', 'orange'] fruits.sort(reverse=True) print(fruits) # ['orange', 'mango', 'lemon', 'banana'] ages = [22, 19, 24, 25, 26, 24, 25, 24] ages.sort() print(ages) # [19, 22, 24, 24, 24, 25, 25, 26] ages.sort(reverse=True) print(ages) # [26, 25, 25, 24, 24, 24, 22, 19]
sorted()
返回一个排序后的列表,不修改原列表的值fruits = ['banana', 'orange', 'mango', 'lemon'] print(sorted(fruits)) # ['banana', 'lemon', 'mango', 'orange'] # Reverse order fruits = ['banana', 'orange', 'mango', 'lemon'] fruits = sorted(fruits,reverse=True) print(fruits) # ['orange', 'mango', 'lemon', 'banana']
Day6-元组
元组是有序且不可更改的不同数据类型的集合,元组使用()
进行包裹,创建一个元组后,我们不能够更改它的值
1. 创建元组
空元组
# syntax empty_tuple = () # or using the tuple constructor empty_tuple = tuple()
含有初始值的元组
# syntax tpl = ('item1', 'item2','item3') fruits = ('banana', 'orange', 'mango', 'lemon')
2. 元组长度
len()
方法获取元组内元素个数# syntax tpl = ('item1', 'item2', 'item3') len(tpl) #3
3.访问元组项
正索引
# Syntax tpl = ('item1', 'item2', 'item3') first_item = tpl[0] second_item = tpl[1] fruits = ('banana', 'orange', 'mango', 'lemon') first_fruit = fruits[0] second_fruit = fruits[1] last_index =len(fruits) - 1 last_fruit = fruits[las_index]
负索引
# Syntax tpl = ('item1', 'item2', 'item3','item4') first_item = tpl[-4] second_item = tpl[-3] fruits = ('banana', 'orange', 'mango', 'lemon') first_fruit = fruits[-4] second_fruit = fruits[-3] last_fruit = fruits[-1]
4. 切片元组
切片后会产生一个新的元组
正向切片
fruits = ('banana', 'orange', 'mango', 'lemon') all_fruits = fruits[0:4] # all items all_fruits= fruits[0:] # all items orange_mango = fruits[1:3] # doesn't include item at index 3 orange_to_the_rest = fruits[1:] #output ('banana', 'orange', 'mango', 'lemon') ('banana', 'orange', 'mango', 'lemon') ('orange', 'mango') ('orange', 'mango', 'lemon')
反向切片
fruits = ('banana', 'orange', 'mango', 'lemon') all_fruits = fruits[-4:] # all items orange_mango = fruits[-3:-1] # doesn't include item at index 3 orange_to_the_rest = fruits[-3:] #output ('banana', 'orange', 'mango', 'lemon') ('orange', 'mango') ('orange', 'mango', 'lemon')
5. 将元组修改为列表
fruits = ('banana', 'orange', 'mango', 'lemon')
fruits = list(fruits)
fruits[0] = 'apple'
print(fruits) # ['apple', 'orange', 'mango', 'lemon']
fruits = tuple(fruits)
print(fruits) # ('apple', 'orange', 'mango', 'lemon')
6. 检查元组是否包含某个数据
使用in
字符
fruits = ('banana', 'orange', 'mango', 'lemon')
print('orange' in fruits) # True
print('apple' in fruits) # False
fruits[0] = 'apple' # TypeError: 'tuple' object does not support item assignment
7. 元组连接
使用+
进行连接
fruits = ('banana', 'orange', 'mango', 'lemon')
vegetables = ('Tomato', 'Potato', 'Cabbage','Onion', 'Carrot')
fruits_and_vegetables = fruits + vegetables
8. 删除元组
无法删除元组中的单个元素,但可以删除整个元组
fruits = ('banana', 'orange', 'mango', 'lemon')
del fruits
Day7-集合(set)
集合的数学定义也可以在python中使用;集合是无序且无索引的,可以包含不同种类型的数据的;可以进行集合间的运算;
补充:列表不可作为集合的一部分:集合具有唯一性,所以是可哈希的,但列表是不可哈希的,所以创建这样的列表时会报错
1. 创建一个集合
#空集
# syntax
st = {}
# or
st = set()
#包含初始项的集合
st = {'item1', 'item2', 'item3', 'item4'}
2. 获取集合的长度
fruits = {'banana', 'orange', 'mango', 'lemon'}
len(fruits)
3. 访问集合中的项目
需要通过循环来进行访问,因为集合的无序性,所以每次循环输出的结果都不一样
a = {1, '2', 4, 3, 6, 7, 5}
for i in a:
print(i)
4. 检查集合中的项目
使用in()
字符
fruits = {'banana', 'orange', 'mango', 'lemon'}
print('mango' in fruits ) # True
5. 添加项目到集合
添加一项,使用
add()
方法fruits = {'banana', 'orange', 'mango', 'lemon'} fruits.add('lime')
添加多项,使用
update()
方法fruits = {'banana', 'orange', 'mango', 'lemon'} vegetables = ('tomato', 'potato', 'cabbage','onion', 'carrot') fruits.update(vegetables) #output {'mango', 'banana', 'carrot', 'cabbage', 'orange', 'tomato', 'onion', 'potato', 'lemon'}
6. 从集合中移除项目
remove()
方法;从集合中删除一个项目,但如果该项目不存在而使用这个方法会报错fruits = {'banana', 'orange', 'mango', 'lemon'} fruits.remove('banana') print(fruits)
discard()
方法;和remove类似,但删除不存在的值的时候不会报错fruits = {'banana', 'orange', 'mango', 'lemon'} fruits.discard('a') print(fruits) #output {'orange', 'banana', 'lemon', 'mango'}
pop()
删除集合中的一个随机项,并返回这个项的值a = {424, 'd', 3, 4, 5, 6, 67, 7} print(a.pop())
clear()
清空集合,但不删除fruits = {'banana', 'orange', 'mango', 'lemon'} fruits.clear() print(fruits) # set()
del()
删除集合,即在内存中删除该集合fruits = {'banana', 'orange', 'mango', 'lemon'} del fruits
7. 列表转集合
在列表转换为集合时,会删除列表中的重复项
fruits = ['banana', 'orange', 'mango', 'lemon','orange', 'banana']
fruits = set(fruits) # {'mango', 'lemon', 'banana', 'orange'}
8. 集合的连接
union()
返回一个新的集合a = {424, 'd', 3, 4, 5, 6, 67, 7} b = {'a', 'b', 'v'} print(a.union(b))
update()
将一个集合插入给定的集合a = {424, 'd', 3, 4, 5, 6, 67, 7} b = {'a', 'b', 'v'} a.update(b) print(a)
9. 集合相关运算
交集
intersection()
whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} even_numbers = {0, 2, 4, 6, 8, 10} whole_numbers.intersection(even_numbers) # {0, 2, 4, 6, 8, 10} python = {'p', 'y', 't', 'h', 'o','n'} dragon = {'d', 'r', 'a', 'g', 'o','n'} python.intersection(dragon) # {'o', 'n'}
子集
issubset()
st1 = {'item1', 'item2', 'item3', 'item4'} st2 = {'item2', 'item3'} st2.issubset(st1) # True
父集
issuperset()
st1 = {'item1', 'item2', 'item3', 'item4'} st2 = {'item2', 'item3'} st1.issuperset(st2) # True
返回一个集合,其中包含仅存在于集合 x 中而不存在于集合 y 中的项目:
x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.difference(y) print(z) whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} even_numbers = {0, 2, 4, 6, 8, 10} whole_numbers.difference(even_numbers) # {1, 3, 5, 7, 9} python = {'p', 'y', 't', 'o','n'} dragon = {'d', 'r', 'a', 'g', 'o','n'} python.difference(dragon) # {'p', 'y', 't'} - the result is unordered (characteristic of sets) dragon.difference(python) # {'d', 'r', 'a', 'g'}
symmetric_difference()
方法返回两个集合中不重复的元素集合,即会移除两个集合中都存在的元素。whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} some_numbers = {1, 2, 3, 4, 5} whole_numbers.symmetric_difference(some_numbers) # {0, 6, 7, 8, 9, 10} python = {'p', 'y', 't', 'h', 'o','n'} dragon = {'d', 'r', 'a', 'g', 'o','n'} python.symmetric_difference(dragon) # {'r', 't', 'p', 'y', 'g', 'a', 'd', 'h'}
isdisjoint()
查询两个集合中是否存在相同的元素,没有返回True,有返回Falseeven_numbers = {0, 2, 4 ,6, 8} even_numbers = {1, 3, 5, 7, 9} even_numbers.isdisjoint(odd_numbers) # True, because no common item python = {'p', 'y', 't', 'h', 'o','n'} dragon = {'d', 'r', 'a', 'g', 'o','n'} python.isdisjoint(dragon) # False, there are common items {'o', 'n'}
Day8-字典(dict)
字典是无序但可修改的数据类型,具体形式为:{‘键’:’值’}
1. 创建字典
空字典
a={}
直接赋值创建
dict={'a':1,'b':2,'c':3}
通过关键字
dict()
和关键字参数创建a = dict(b=1, c=2, d=3) print(a) #output {'b': 1, 'c': 2, 'd': 3}
通过二元组列表创建
a = [['a', 1], ['b', 2], ['c', 3]] a1=[('a', 1), ('b', 2), ('c', 3)] b = dict(a) b1=dict(a1) print(b) print(b1) #output {'a': 1, 'b': 2, 'c': 3}
dict和zip结合创建
a = dict(zip('abc', [1, 2, 3])) print(a) #output {'a': 1, 'b': 2, 'c': 3}
通过字典推导式创建
dic = {i: i*2 for i in range(3)} print(dic) #output {0: 0, 1: 2, 2: 4}
通过
dict.fromkeys()
创建,第一个参数为键,第二个参数为预设的value
值,固定的不会变的a = dict.fromkeys(range(3), 'value') print(a) #output {0: 'value', 1: 'value', 2: 'value'}
2. 检查一个字典中的键值对的个数
person = {
'first_name':'Asabeneh',
'last_name':'Yetayeh',
'age':250,
'country':'Finland',
'is_marred':True,
'skills':['JavaScript', 'React'],
'address':{
'street':'Space street',
'zipcode':'02210'
}
}
print(len(person)) # 7
3. 访问字典的项目
通过引用键名来获取对应值
如果键不存在,则按键名访问项目会引发错误。为了避免这个错误,首先我们必须检查一个键是否存在,或者我们可以使用get方法。如果键不存在,get 方法返回 None,它是一个 NoneType 对象数据类型。
person = { 'first_name':'Asabeneh', 'last_name':'Yetayeh', 'age':250, 'country':'Finland', 'is_marred':True, 'skills':['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], 'address':{ 'street':'Space street', 'zipcode':'02210' } } print(person['first_name']) # Asabeneh print(person['country']) # Finland print(person['skills']) # ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'] print(person['skills'][0]) # JavaScript print(person['address']['street']) # Space street print(person['city']) # Error
4. 添加项目到字典中
即添加新的键值对
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key5'] = 'value5'
5. 修改字典中的值
# syntax
dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
dct['key1'] = 'value-one'
6. 删除字典中的键值对
pop()
删除指定键名的项目popitem()
删除最后一项del
删除指定键名的项目# syntax dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct.pop('key1') # removes key1 item dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct.popitem() # removes the last item del dct['key2'] # removes key2 item
7. 字典与其他数据类型操作
字典更改为元组列表
items()
方法dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4} print(dic.items()) #output dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
字典键作为列表获取
- 使用
keys()
方法
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4} print(dic.keys()) #output dict_keys(['a', 'b', 'c', 'd'])
- 使用
获取字典值作为列表形式
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4} print(dic.values()) #output dict_values([1, 2, 3, 4])
8. 字典自身操作
清除(字典本身还在,但里面的数据全没了)
# syntax dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} print(dct.clear()) # None
删除
# syntax dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} del dct
复制
# syntax dct = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} dct_copy = dct.copy() # {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
Day9-条件
1. 条件句
if,else,elif
# syntax
if condition:
code
elif condition:
code
else:
code
a = 0
if a > 0:
print('A is a positive number')
elif a < 0:
print('A is a negative number')
else:
print('A is zero')
也可以写在一行中,类似于==列表解析式==的写法
a = 3
print('A is positive') if a > 0 else print('A is negative')
# first condition met, 'A is positive' will be printed
2. 嵌套条件
a = 0
if a > 0:
if a % 2 == 0:
print('A is a positive and even integer')
else:
print('A is a positive number')
elif a == 0:
print('A is zero')
else:
print('A is a negative number')
3.条件和逻辑运算搭配
and
a = 0 if a > 0 and a % 2 == 0: print('A is an even and positive integer') elif a > 0 and a % 2 != 0: print('A is a positive integer') elif a == 0: print('A is zero') else: print('A is negative')
or
user = 'James' access_level = 3 if user == 'admin' or access_level >= 4: print('Access granted!') else: print('Access denied!')
Day10-循环
1. while
count = 0
while count < 5:
print(count)
count = count + 1
#prints from 0 to 4
while还可以与else进行搭配使用
count = 0
while count < 5:
print(count)
count = count + 1
else:
print(count)
2. break
想退出或停止循环时使用break
count = 0
while count < 5:
print(count)
count = count + 1
if count == 3:
break
3. continue
跳过循环中剩下的代码,开始下一次循环
count = 0
while count < 5:
if count == 3:
continue
print(count)
count = count + 1
4. for
for除了用作循环,还用于迭代序列(即列表,元组,字典,集合或字符串)
#列表
a = [1, 2, 3, 4, 5, 6]
for i in a:
print(i)
#1 2 3 4 5 6
#元组
a = (1, 2, 3, 4, 5, 6)
for i in a:
print(i)
#1 2 3 4 5 6
#字典
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key in dic:
print(i)
#a b c d
#集合
dic = {1, 2, 3, 4, 5, 6}
for i in dic:
print(i)
#1 2 3 4 5 6
#字符串
dic = 'greagagarg'
for i in dic:
print(i)
#g r e a g a g a r g
for可以和else结合在一起使用,当循环结束后就执行else中的内容
5. pass
当循环体内暂时不写语句时,可以写pass充当占位功能,本身不执行
for number in range(6):
pass
Day11-函数
1. 声明和调用函数
# syntax
# Declaring a function
def function_name():
codes
codes
# Calling a function
function_name()
2. 带参函数
单参数
# syntax # Declaring a function def function_name(parameter): codes codes # Calling function print(function_name(argument))
多参数
# syntax # Declaring a function def function_name(para1, para2): codes codes # Calling function print(function_name(arg1, arg2))
通过指定参数的值
# syntax # Declaring a function def function_name(para1, para2): codes codes # Calling function print(function_name(para1 = 'John', para2 = 'Doe')) # the order of arguments does not matter here
默认值参数
当我们不向参数提供值,参数可以使用预先赋予的默认值
# syntax # Declaring a function def function_name(param = value): codes codes # Calling function function_name() function_name(arg)
任意数量的参数
当我们不知道接收参数的数量时,我们可以在参数前加一个
*
,来创建一个可以接收任意数量参数的函数def sum_all_nums(*nums): total = 0 for num in nums: total += num # same as total = total + num return total print(sum_all_nums(2, 3, 5)) # 10
函数作为另一个函数的参数
#You can pass functions around as parameters def square_number (n): return n * n def do_something(f, x): return f(x) print(do_something(square_number, 3)) # 27
Day12-模块
1.模块是什么
模块是简单的代码文件(比如只包含变量的,)或者是复杂的代码文件(实现了功能的)
2. 导入模块
import xxxx(模块名)
3. 从模块导入函数
from xxx(模块) import yyy(函数名)
4. 重命名导入的函数
from xxx(模块) import yyy(函数名) as zzz(别名)
5. 导入内置模块
操作系统模块
os
用于访问操作系统功能的模块,通用功能为获取平台信息,对目录的操作,判断操作(比如是否是目录,文件是否存在)
# import the module import os # Creating a directory os.mkdir('directory_name') # Changing the current directory os.chdir('path') # Getting current working directory os.getcwd() # Removing directory os.rmdir()
系统模块
sys
用于操作 Python 运行时环境的不同部分的函数和变量
import sys #print(sys.argv[0], argv[1],sys.argv[2]) # this line would print out: filename argument1 argument2 print('Welcome {}. Enjoy {} challenge!'.format(sys.argv[1], sys.argv[2])) #input python script.py Asabeneh 30DaysOfPython #output Welcome Asabeneh. Enjoy 30DayOfPython challenge! #常用的sys命令 # to exit sys sys.exit() # To know the largest integer variable it takes sys.maxsize # To know environment path sys.path # To know the version of python you are using sys.version
统计模块(statistics)
提供数值数据的数理统计功能。该模块中定义的流行统计函数:均值、中位数、众数、标准差等。
from statistics import * # importing all the statistics modules ages = [20, 20, 4, 24, 25, 22, 26, 20, 23, 22, 26] print(mean(ages)) # ~22.9 print(median(ages)) # 23 print(mode(ages)) # 20 print(stdev(ages)) # ~2.3
数学模块(math)
from math import pi, sqrt, pow, floor, ceil, log10 print(pi) # 3.141592653589793 print(sqrt(2)) # 1.4142135623730951 print(pow(2, 3)) # 8.0 print(floor(9.81)) # 9 print(ceil(9.81)) # 10 print(math.log10(100)) # 2
Day13-列表深入
1. 列表推导式
# One way
language = 'Python'
lst = list(language) # changing the string to list
print(type(lst)) # list
print(lst) # ['P', 'y', 't', 'h', 'o', 'n']
# Second way: list comprehension
lst = [i for i in language]
print(type(lst)) # list
print(lst) # ['P', 'y', 't', 'h', 'o', 'n']
# Generating numbers
numbers = [i for i in range(11)] # to generate numbers from 0 to 10
print(numbers) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# It is possible to do mathematical operations during iteration
squares = [i * i for i in range(11)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# It is also possible to make a list of tuples
numbers = [(i, i * i) for i in range(11)]
print(numbers) # [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
# Generating even numbers
even_numbers = [i for i in range(21) if i % 2 == 0] # to generate even numbers list in range 0 to 21
print(even_numbers) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Generating odd numbers
odd_numbers = [i for i in range(21) if i % 2 != 0] # to generate odd numbers in range 0 to 21
print(odd_numbers) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Filter numbers: let's filter out positive even numbers from the list below
numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10]
positive_even_numbers = [i for i in range(21) if i % 2 == 0 and i > 0]
print(positive_even_numbers) # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
# Flattening a three dimensional array
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [ number for row in list_of_lists for number in row]
print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 匿名函数(lambda)
单独的
# Named function def add_two_nums(a, b): return a + b print(add_two_nums(2, 3)) # 5 # Lets change the above function to a lambda function add_two_nums = lambda a, b: a + b print(add_two_nums(2,3)) # 5 # Self invoking lambda function (lambda a, b: a + b)(2,3) # 5 - need to encapsulate it in print() to see the result in the console square = lambda x : x ** 2 print(square(3)) # 9 cube = lambda x : x ** 3 print(cube(3)) # 27 # Multiple variables multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c print(multiple_variable(5, 5, 3)) # 22
在另一个函数中使用
def power(x): return lambda n : x ** n cube = power(2)(3) # function power now need 2 arguments to run, in separate rounded brackets print(cube) # 8 two_power_of_five = power(2)(5) print(two_power_of_five) # 32
Day14-高阶函数
1. 函数作为函数的参数
def sum_numbers(nums): # normal function
return sum(nums) # a sad function abusing the built-in sum function :<
def higher_order_function(f, lst): # function as a parameter
summation = f(lst)
return summation
result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5])
print(result) # 15
2. 函数作为返回值
def square(x): # a square function
return x ** 2
def cube(x): # a cube function
return x ** 3
def absolute(x): # an absolute value function
if x >= 0:
return x
else:
return -(x)
def higher_order_function(type): # a higher order function returning a function
if type == 'square':
return square
elif type == 'cube':
return cube
elif type == 'absolute':
return absolute
result = higher_order_function('square')
print(result(3)) # 9
result = higher_order_function('cube')
print(result(3)) # 27
result = higher_order_function('absolute')
print(result(-3)) # 3
3. 闭包
https://zhuanlan.zhihu.com/p/341376218
https://www.cnblogs.com/BlueSkyyj/p/8884236.html
闭包条件:
- 在一个外函数中定义了一个内函数
- 内函数中运用了外函数的临时变量
- 外函数的返回值是内函数的引用
def add_ten():
ten = 10
def add(num):
return num + ten
return add
closure_result = add_ten()
print(closure_result(5)) # 15
print(closure_result(10)) # 20
4. 装饰器
https://www.jianshu.com/p/ee82b941772a
# Normal function
def greeting():
return 'Welcome to Python'
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
g = uppercase_decorator(greeting)
print(g()) # WELCOME TO PYTHON
## Let us implement the example above with a decorator
'''This decorator function is a higher order function
that takes a function as a parameter'''
def uppercase_decorator(function):
def wrapper():
func = function()
make_uppercase = func.upper()
return make_uppercase
return wrapper
@uppercase_decorator
def greeting():
return 'Welcome to Python'
print(greeting()) # WELCOME TO PYTHON
def decorator_with_parameters(function):
def wrapper_accepting_parameters(para1, para2, para3):
function(para1, para2, para3)
print("I live in {}".format(para3))
return wrapper_accepting_parameters
def print_full_name(first_name, last_name, country):
print("I am {} {}. I love to teach.".format(
first_name, last_name, country))
g=decorator_with_parameters(print_full_name)
print(g("Asabeneh", "Yetayeh", 'Finland'))
#使用装饰器
def decorator_with_parameters(function):
def wrapper_accepting_parameters(para1, para2, para3):
function(para1, para2, para3)
print("I live in {}".format(para3))
return wrapper_accepting_parameters
@decorator_with_parameters
def print_full_name(first_name, last_name, country):
print("I am {} {}. I love to teach.".format(
first_name, last_name, country))
print_full_name("Asabeneh", "Yetayeh",'Finland')
5. 内置高阶函数
map()
接受一个表达式和一个可迭代的数据
#1 numbers = [1, 2, 3, 4, 5] # iterable def square(x): return x ** 2 numbers_squared = map(square, numbers) print(list(numbers_squared)) # [1, 4, 9, 16, 25] # Lets apply it with a lambda function numbers_squared = map(lambda x : x ** 2, numbers) print(list(numbers_squared)) # [1, 4, 9, 16, 25] #2 numbers_str = ['1', '2', '3', '4', '5'] # iterable numbers_int = map(int, numbers_str) print(list(numbers_int)) # [1, 2, 3, 4, 5] #3names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # iterable def change_to_upper(name): return name.upper() names_upper_cased = map(change_to_upper, names) print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM'] # Let us apply it with a lambda function names_upper_cased = map(lambda name: name.upper(), names) print(list(names_upper_cased)) # ['ASABENEH', 'LIDIYA', 'ERMIAS', 'ABRAHAM']
filter()
为可迭代对象通过表达式返回布尔值,返回结果为真的数据numbers = [1, 2, 3, 4, 5] # iterable def is_odd(num): if num % 2 != 0: return True return False odd_numbers = filter(is_odd, numbers) print(list(odd_numbers)) # [1, 3, 5] # Filter long name names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] # iterable def is_name_long(name): if len(name) > 7: return True return False long_names = filter(is_name_long, names) print(list(long_names)) # ['Asabeneh']
reduce()
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。numbers_str = ['1', '2', '3', '4', '5'] # iterable def add_two_nums(x, y): return int(x) + int(y) total = reduce(add_two_nums, numbers_str) print(total) # 15
Day15-错误类型
1. 语法错误(SyntaxError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
File "<stdin>", line 1
print 'hello world'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello world')?
>>>
2. 名称错误(NameError)
一般是变量名称定义相关问题
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(age)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
>>>
3. 索引错误(IndexError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
4. 模块错误(ModuleNotFoundError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>>
5. 属性错误(AttributeError)
要使用的库或类中没有某个方法或属性时报错
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
>>> import math
>>> math.PI
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'math' has no attribute 'PI'
>>>
6. 键错误(KeyError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> users = {'name':'Asab', 'age':250, 'country':'Finland'}
>>> users['name']
'Asab'
>>> users['county']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'county'
>>>
7. 类型错误(TypeError)
多种数据类型之间进行处理时易发生的错误
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 4 + '3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
8. 导入错误(ImportError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from math import power
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'power' from 'math'
>>>
9. 值错误(ValueError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('12a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12a'
>>>
10. 零除法错误(ZeroDivisionError)
asabeneh@Asabeneh:~$ python
Python 3.9.6 (default, Jun 28 2021, 15:26:21)
[Clang 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
Day16-日期时间处理
主要使用datetime
模块来处理日期和时间
1. 获取日期和时间
from datetime import datetime
now = datetime.now()
print(now) # 2021-07-08 07:34:46.549883
day = now.day # 8
month = now.month # 7
year = now.year # 2021
hour = now.hour # 7
minute = now.minute # 38
second = now.second
timestamp = now.timestamp()
print(day, month, year, hour, minute)
print('timestamp', timestamp)
print(f'{day}/{month}/{year}, {hour}:{minute}') # 8/7/2021, 7:38
2. 格式化日期输出
使用strftime
方法
from datetime import datetime
# current date and time
now = datetime.now()
t = now.strftime("%H:%M:%S")
print("time:", t)
time_one = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("time one:", time_one)
time_two = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("time two:", time_two)
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00-59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为 0,星期一为 1,以此类推。
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
3. 字符串转时间数据
from datetime import datetime
date_string = "5 December, 2019"
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)
4. 时间参数转时间数据类型
from datetime import date
d = date(2020, 1, 1)
print(d)
5. 表示时间的时间对象
from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(10, 30, 50)
print("b =", b)
# time(hour, minute and second)
c = time(hour=10, minute=30, second=50)
print("c =", c)
# time(hour, minute, second, microsecond)
d = time(10, 30, 50, 200555)
print("d =", d)
6. 时间差
date类型直接相减
import datetime from datetime import date,datetime today = date(year=2019, month=12, day=5) new_year = date(year=2020, month=1, day=1) time_left_for_newyear = new_year - today # Time left for new year: 27 days, 0:00:00 print('Time left for new year: ', time_left_for_newyear) t1 = datetime(year=2019, month=12, day=5, hour=0, minute=59, second=0) t2 = datetime(year=2020, month=1, day=1, hour=0, minute=0, second=0) diff = t2 - t1 # Time left for new year: 26 days, 23: 01: 00 print('Time left for new year:', diff)
timedelata
计算时间差timedelata将时间进行数据格式转换
from datetime import timedelta t1 = timedelta(weeks=12, days=10, hours=4, seconds=20) t2 = timedelta(days=7, hours=5, minutes=3, seconds=30) t3 = t1 - t2 print(t1) print(t2) print("t3 =", t3) #output 94 days, 4:00:20 7 days, 5:03:30 t3 = 86 days, 22:56:50
Day17-异常处理
1. 异常处理
单个异常
try: print(10 + '5') except: print('Something went wrong') try: name = input('Enter your name:') year_born = input('Year you were born:') age = 2019 - year_born print(f'You are {name}. And your age is {age}.') except: print('Something went wrong')
多个异常
try: name = input('Enter your name:') year_born = input('Year you were born:') age = 2019 - year_born print(f'You are {name}. And your age is {age}.') except TypeError: print('Type error occured') except ValueError: print('Value error occured') except ZeroDivisionError: print('zero division error occured')
异常后续处理
try: name = input('Enter your name:') year_born = input('Year you born:') age = 2019 - int(year_born) print('You are {name}. And your age is {age}.') except TypeError: print('Type error occur') except ValueError: print('Value error occur') except ZeroDivisionError: print('zero division error occur') else: print('I usually run with the try block') finally: print('I alway run.')
不指明具体异常类型,全部捕获,后续输出
try: name = input('Enter your name:') year_born = input('Year you born:') age = 2019 - int(year_born) print('You are {name}. And your age is {age}.') except Exception as e: print(e)
2. 打包和解包参数
* 对于元组
** 对于字典
解包
def sum_of_five_nums(a, b, c, d, e): return a + b + c + d + e lst = [1, 2, 3, 4, 5] print(sum_of_five_nums(*lst)) # 15 #*作用将列表解压出里面的元素
numbers = range(2, 7) # normal call with separate arguments print(list(numbers)) # [2, 3, 4, 5, 6] args = [2, 7] numbers = range(*args) # call with arguments unpacked from a list print(numbers) # [2, 3, 4, 5,6]
countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] fin, sw, nor, *rest = countries print(fin, sw, nor, rest) # Finland Sweden Norway ['Denmark', 'Iceland'] numbers = [1, 2, 3, 4, 5, 6, 7] one, *middle, last = numbers print(one, middle, last) # 1 [2, 3, 4, 5, 6] 7
def unpacking_person_info(name, country, city, age): return f'{name} lives in {country}, {city}. He is {age} year old.' dct = {'name': 'Asabeneh', 'country': 'Finland', 'city': 'Helsinki', 'age': 250} # Asabeneh lives in Finland, Helsinki. He is 250 years old. print(unpacking_person_info(**dct)
打包
def sum_all(*args): s = 0 for i in args: s += i return s print(sum_all(1, 2, 3)) # 6 print(sum_all(1, 2, 3, 4, 5, 6, 7)) # 28
#打包字典 def packing_person_info(**kwargs): # check the type of kwargs and it is a dict type # print(type(kwargs)) # Printing dictionary items for key in kwargs: print(f"{key} = {kwargs[key]}") return kwargs print(packing_person_info(name="Asabeneh", country="Finland", city="Helsinki", age=250))
通过解包链接列表
lst_one = [1, 2, 3] lst_two = [4, 5, 6, 7] lst = [0,*lst_one,*lst_two] print(lst) # [0, 1, 2, 3, 4, 5, 6, 7] country_lst_one = ['Finland', 'Sweden', 'Norway'] country_lst_two = ['Denmark', 'Iceland'] nordic_countries = [*country_lst_one, *country_lst_two] # ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] print(nordic_countries)
枚举
enumerate
for index, item in enumerate([20, 30, 40]): print(index, item) for index, i in enumerate(countries): print('hi') if i == 'Finland': print('The country {i} has been found at index {index}') #返回索引和对应的值
压缩
zip
将两个列表内容进行一对一绑定
a = [1, 2, 3, 4, 5, 6] b = ['a', 'b', 'c', 'd', 'e', 'f'] s = zip(a, b) z = [] for i, j in s: z.append({"a中:": i, "b中:": j}) print(z) #output [{'a中:': 1, 'b中:': 'a'}, {'a中:': 2, 'b中:': 'b'}, {'a中:': 3, 'b中:': 'c'}, {'a中:': 4, 'b中:': 'd'}, {'a中:': 5, 'b中:': 'e'}, {'a中:': 6, 'b中:': 'f'}]