从零开始的深度学习--python初学

引言

作为一位计算机系的学生,本人十分惭愧居然一点python的基础都没有。因此,这一系列博文便记录了本人学习从python基础到python深度学习的过程吧。

python基础

一、字面量

1.六种类型:string、list、tuple、set、dictionary、number(int float complex bool)

2.注释:以#开头,或""“多行注释 “””

3.变量:变量名=变量值

4.验证数据类型:type()语句

1
2
3
4
5
6
var=1
print(type(var))
var=1.5
print(type(var))
var="hello world"
print(type(var))

输出

1
2
3
<class 'int'>
<class 'float'>
<class 'str'>

5.数据类型转换:int(x) float(x) str(x)

1
2
num_str=str(11)
print(type(num_str),num_str)

输出

1
<class 'str'> 11

6.运算符

运算符作用
/
//整除
%取余
**指数

7.字符串的多种定义法:单引号,双引号,三引号(可以多行定义)均可

8.字符串使用+进行拼接

9.字符串拼接:使用占位符和%

1
2
3
4
name="platinum windy's "
salary=18000
message="%smonthy salary:%d"%(name,salary)
print(message)

输出

1
platinum windy's monthy salary:18000

占位符类型

占位符作用
%s将内容转换成字符串,放入占位位置
%d将内容转换成整数,放入占位位置
%f将内容转换成浮点型,放入占位位置

10.数字精度控制:采用辅助符号’m.n’来控制数据宽度和精度

1
2
3
4
5
6
7
num1=11
num2=11.3456
print("num1's width is limited 5,the result is:%5d"%num1)
#小于数字宽度不会生效
print("num1's width is limited 1,the result is:%1d"%num1)
#精度控制,进行四舍五入
print("num2's width is limited 5 and the precision is limited 2,the result is:%7.2f"%num2)

输出

1
2
3
num1's width is limited 5,the result is:   11
num1's width is limited 1,the result is:11
num2's width is limited 5 and the precision is limited 2,the result is: 11.35

快速格式化:f{}

1
2
3
num1=11
num2=11.3456
print(f"{num1},{num2}")

输出

1
11,11.3456

11.字符串格式化小练习

1
2
3
4
5
6
7
name="A"
stock_price=19.99
stock_code="123456"
stock_price_daily_growth_factor=1.2
growth_days=7
print(f"company is {name},stock code is {stock_code},stock price is {stock_price}")
print("daily growth factor is %.2f,after %d days of growth,the stock price is %.2f"%(stock_price_daily_growth_factor,growth_days,(stock_price*stock_price_daily_growth_factor**growth_days)))

12.数据输入:input() 输入的一切均为字符串,需要进行符号转换

1
2
name=input("What's your name?\n")
print("you are "+name)

输出

1
2
3
What's your name?
Zhao
you are Zhao

二、判断语句

1.if elif else

1
2
3
4
5
6
7
8
9
10
age=18
if age>=18:
print("I am 18 years old")
print("I will go to college")
elif age>=10:
print("I am 10 years old")
print("I will go to high school")
else:
print("you are younger than 12 years old")
print("How time flies")

2.循环嵌套练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import random
num=random.randint(1,10)
guess=int(input("Please guess a number:"))
if guess==num:
print("You are right")
elif guess>num:
guess=int(input("Please guess a smaller number:"))
if guess==num:
print("You are right")
elif guess>num:
guess=int(input("Please guess a smaller number:"))
if guess==num:
print("You are right")
else:
print("The correct number is %d"%num)
elif guess<num:
guess=int(input("Please guess a bigger number:"))
if guess==num:
print("You are right")
else:
print("The correct number is %d"%num)
elif guess<num:
guess=int(input("Please guess a bigger number:"))
if guess==num:
print("You are right")
elif guess>num:
guess=int(input("Please guess a smaller number:"))
if guess==num:
print("You are right")
else:
print("The correct number is %d"%num)
elif guess<num:
guess=int(input("Please guess a bigger number:"))
if guess==num:
print("You are right")
else:
print("The correct number is %d"%num)

三、循环语句

1.while语句

1
2
3
4
5
6
7
8
9
10
11
import random
num=random.randint(1,100)
guess=int(input("Please enter a number:"))
while 1:
if guess>num:
guess=int(input("Please enter a smaller number:"))
elif guess<num:
guess=int(input("Please enter a bigger number:"))
else:
print("Correct!")
break

1
2
3
4
5
6
7
8
9
m=1
n=1
while n<=9:
m=1
while m<=n:
print("%d*%d=%d"%(m,n,m*n),end="\t")
m+=1
print("")
n+=1

2.for语句

for 临时变量 in 序列类型

练习:数一数输入的字符串有几个a

1
2
3
4
5
6
name=input("Please enter a string:")
cnt=0
for x in name:
if x=='a':
cnt+=1
print(name+" has "+str(cnt)+" letter a")

range语句:获取一个数字序列

语法1:range(num)
语法2:range(num1,num2)
语法3:range(num1,num2,step)

1
2
3
4
5
6
7
8
for x in range(10):
print(x,end=" ")
print("")
for x in range(5,10):
print(x,end=" ")
print("")
for x in range(0,10,2):
print(x,end=" ")

三者输出如下:

1
2
3
0 1 2 3 4 5 6 7 8 9
5 6 7 8 9
0 2 4 6 8

3.循环语句综合练习

1
2
3
4
5
6
7
8
9
10
11
import random
salary=10000
for x in range(19):
if salary==0:
break
score=random.randint(1,10)
if score>=5:
salary-=1000
print("Employee %d get his salary:1000 and his score is %d,total salary remain %d"%(x+1,score,salary))
else:
print("Employee %d's score is %d,less than 5"%(x+1,score))

四、函数

1.函数的定义:

1
2
3
def 函数名(传入参数):
函数体
return 返回值

参数和返回值如不需要,可以省略

2.函数的格式化说明:

1
2
3
4
5
6
7
def func(x,y):
` ` `
函数说明
:param x:形参x的说明
:param y:形参y的说明
:return:返回值的说明
` ` `

3.函数练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
money=5000000
name=None
name=input("请输入您的名字:")
def menu():
print("---------------主菜单----------------")
print("%s,欢迎来到ATM机,请选择操作"%name)
print("查询余额[输入1]")
print("存款\t[输入2]")
print("取款\t[输入3]")
print("退出\t[输入4]")
print("请输入您的选择:")

def check():
print("---------------查询余额----------------")
print("%s,您好,您的余额剩余:%d元"%(name,money))

def store(x):
global money
money+=x
check()

def withdraw(x):
global money
money-=x
check()

def main():
menu()
while True:
choice=input()
if choice=='1':
check()
elif choice=='2':
x=int(input("请输入存款数:"))
store(x)
elif choice=='3':
x=int(input("请输入取款数:"))
withdraw(x)
else :
break
main()

五、数据容器

1.list(列表):使用[]的方式定义列表

列表的元素可以通过索引的方式来取出(可以正向或反向读取)

列表的常用方法:

方法作用
list.index(element)查找指定元素在列表的下标
list.insert(index,element)在指定的下标位置,插入指定的元素
list.append(element)将指定元素追加到列表的尾部
list.extend(data containers)将其他数据容器的内容取出,依次追加到列表胃部
list.pop(index)删除元素,并返回删掉的元素
list.remove(element)删除找到的第一个元素
list.clear()清空列表
list.count()统计某元素在列表内的数量
len(list)统计容器内有多少元素

列表练习

1
2
3
4
5
6
7
8
9
10
list=[21,25,21,23,22,20]
list.append(31)
print(list)
newlist=[29,33,30]
list.extend(newlist)
print(list)
first=list[0]
last=list[-1]
print(first,last)
print(list.index(31))

输出

1
2
3
4
[21, 25, 21, 23, 22, 20, 31]
[21, 25, 21, 23, 22, 20, 31, 29, 33, 30]
21 30
6

1
2
3
4
5
6
7
8
9
10
list=[1,2,3,4,5,6,7,8,9,10]
index=0
while index<len(list):
if(list[index]%2==0):
print(list[index],end=" ")
index+=1
print("")
for ele in list:
if(ele%2==0):
print(ele,end=" ")

2.tuple(元组):一旦被定义完成,不可以修改,使用()定义

如果元组中只有一个元素,需要在元素后面加一个","

元组的常用方法:

方法作用
tuple.index(element)查找指定元素在元组的下标
tuple.count(element)统计某元素在元组内的数量
len(tuple)统计容器内有多少元素

元组练习

1
2
3
4
5
6
7
tuple=("toms",11,['football','music'])
print(tuple.index(11))
print(tuple[0])
tuple[2].remove('football')
print(tuple)
tuple[2].append("coding")
print(tuple)

输出

1
2
3
4
1
toms
('toms', 11, ['music'])
('toms', 11, ['music', 'coding'])

3.str(字符串):不支持修改

字符串的常用方法:

方法作用
str.index(element)查找指定元素在字符串首地址的下标
str.replace(str1,str2)将字符串内全部的str1替换成str2(得到一个新的字符串)
str.split(str)按照指定的分隔符字符串,将字符串划分成多个字符串,并存入列表对象中
str.strip()去除字符串前后空格
str.strip(str)去除字符串前后指定字符
str.count(element)统计某元素在字符串内的数量
len(str)统计容器内有多少元素

4.序列:内容连续,有序,可使用下标索引的一类数据容器

切片操作:序列[起始下标:结束下标:步长]

5.set(集合):不允许重复且无序,因此不支持索引

定义集合:变量名称={element,element…}

定义空集合:变量名称=set()

集合常用方法

方法作用
set.add(element)向集合中添加新元素
set.remove(element)移除集合中的元素
set.pop()随机取出一个元素
set.clear()清空集合
set1.difference(set2)取出集合1和集合2的差集,得到一个新集合
set1.difference_update(set2)在集合1内,删除和集合2相同的元素 集合1被修改,集合2不变
set1.union(set2)将集合1和集合2合并,得到一个新集合
len(set)统计容器内有多少元素

集合的遍历:

1
2
for ele in set:
print(ele)

6.dict(字典)

定义:变量名称={key:value,key:value,…}

定义空字典:变量名称=dict()

通过key获取value:dict[key]

字典的常用方法

方法作用
dict.pop(key)获取指定key的value,并移除key:value
dict.clear()清空字典
dict.keys()取得字典里所有key
len(dict)计算字典内元素数量

字典的遍历

1
2
for key in dict.keys():
print(key,dict[key])

字典的练习:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
dic={
"A":{
"部门":"科技部",
"工资":3000,
"级别":1
},
"B":{
"部门":"市场部",
"工资":5000,
"级别":2
},
"C":{
"部门":"市场部",
"工资":7000,
"级别":3
},
"D":{
"部门":"科技部",
"工资":4000,
"级别":1
},
"E":{
"部门":"市场部",
"工资":6000,
"级别":2
}
}
print("全体员工当前信息如下:")
print(dic)
for key in dic:
if dic[key]["级别"]==1:
dic[key]["级别"]=2
dic[key]["工资"]+=1000
print("全体员工级别为1的完成升职加薪操作,操作后:")
print(dic)

输出

1
2
3
4
5
6
全体员工当前信息如下:
{'A': {'部门': '科技部', '工资': 3000, '级别': 1}, 'B': {'部门': '市场部', '工资': 5000, '级别
': 2}, 'C': {'部门': '市场部', '工资': 7000, '级别': 3}, 'D': {'部门': '科技部', '工资': 4000, '级别': 1}, 'E': {'部门': '市场部', '工资': 6000, '级别': 2}}
全体员工级别为1的完成升职加薪操作,操作后:
{'A': {'部门': '科技部', '工资': 4000, '级别': 2}, 'B': {'部门': '市场部', '工资': 5000, '级别
': 2}, 'C': {'部门': '市场部', '工资': 7000, '级别': 3}, 'D': {'部门': '科技部', '工资': 5000, '级别': 2}, 'E': {'部门': '市场部', '工资': 6000, '级别': 2}}