《Python小白书》学习笔记(更新中)

文章持续更新中…

0 – Python简介

1 Python简介

1 Python是解释型语言:无需编译

2 Python是交互式语言:可以在>>>提示符后直接执行代码

3 Python是面向对象语言:Python支持 1面向对象的风格 2代码封装在对象 的编程技术

4 Python是初学者的语言:容易上手,支持广泛的应用程序

2 Python的10个特点

1 易于学习:Python有相对较少的关键字,结构简单,和一个明确定义的语法,学习起来更加简单。
2 易于阅读:Python代码定义的更清晰。
3 易于维护:Python的成功在于它的源代码是相当容易维护的。
4 一个广泛的标准库:Python的最大的优势之一是丰富的库,跨平台的,在UNIX,Windows和Macintosh兼容很好。
5 互动模式:互动模式的支持,您可以从终端输入执行代码并获得结果的语言,互动的测试和调试代码片断。
6 可移植性:基于其开放源代码的特性,Python已经被移植(也就是使其工作)到许多平台。
7 可扩展性:如果你需要一段运行很快的关键代码,或者是想要编写一些不愿开放的算法,你可以使用C或C++完成那部分程序,然后从你的Python程序中调用。
8 数据库:Python提供所有主要的商业数据库的接口。
9 GUI编程:Python支持GUI可以创建和移植到许多系统调用。
10 可嵌入:你可以将Python嵌入到C/C++程序,让你的程序的用户获得"脚本化"的能力。

3 常用的库(持续更新…)

NumPy https://www.numpy.org.cn
Pandas https://www.pypandas.cn
Matploplib https://www.matplotlib.org.cn

4 入门学习推荐(持续更新…)

runoob 菜鸟教程

《编程小白的第一本Python入门书》 # 简单易懂,偶尔有点小错误

《Python编程从入门到实践》 # 经典入门书籍

《笨办法学Python3》 # 经典入门书籍

《Python编程快速上手 让繁琐工作自动化》 # 自动化办公,进阶图书

《流畅的Python》 # 进阶图书

《Python》袖珍指南 # 工具书


1 – 变量与字符串

1 前提

1 区分大小写

2 句末无需添加分号

3 在shell中打开Python:输入Python3

4 Python 3 源码文件以UTF-8编码,所有字符串都是UNICODE字符串

5 解决中文注释报错问题:文件开头添加一行#coding:utf-8

6 注释的三种方法:# ''' """

7 多行语句,使用反斜杠\

2 四种数字类型

int bool float complex

3 变量

标识符必须以字母下划线开头

标识符的其他的部分由字母、数字和下划线组成

标识符对大小写敏感

# 标识符answer、赋值符=、值42
answer = 42

# 保留字不可以用作标识符,查询方法:
import keyword
keyword.kwlist
* 基础的实用函数
print(<变量名>)    # 打印
input(<变量名>)    # 输入
type(<变量名>)     # 返回变量的类型
len(<变量名>)      # 返回字符串的长度
4 字符串

三种写法:'' "" '''<无限长度的字符串,随意换行>'''

不区分char和string类型,''""基本等价;"abcd'e'fgh"双引号中可以直接包含单引号,无需转义

转义符\

字符串用+连接,用*重复

两种索引方式:从左往右以0开始,从右往左以-1开始

分片:截取出一段字符串,复制出一个副本,不会改动原字符串

字符串的截取格式:变量[头下标:尾下标:步长]

a b c d e f g h i j k l m n p
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
# <代码示例> +和*
str1 = 'aaa'
str2 = 'bbb'
print(str1+str2, str1*2, str2*3)      #aaabbb aaaaaa bbbbbbbbb

# <代码示例> 转义符 r'\'
print('abcde')      #abcde
print('abc\nde')    #abc(换行)de   #\n代表换行,反斜杠(\)将字母(n)转义为换行符
print(r'abc\nde')   #abc\nde      #r=raw string 取消转义,输出''中的全部内容

# <代码示例> 索引和分片;对照表格
name = 'abcdefghijklmnp'
len(name)
print(name, name[0:])          #abcdefghijklmnp abcdefghijklmnp
print(name[0], name[-15])      #a a   #正数第0位,倒数第-15位
print(name[14], name[-1])      #p p   #正数第14位,倒数第-1位
print(name[0:5], name[1:5])    #abcde bcde   #[头下标:共截取n位]
print(name[5:], name[:5], name[-5:])      #fghijklmnp abcde klmnp
5 字符串的常用方法

对象、方法

replace() 替换

find() 返回子字符串第一位在母字符串的位置

format() 字符串格式化符

# <代码示例> replace()
phone_num = '1234-567-890'
hiding_num = phone_num.replace( phone_num[:9], '*'*9 )
print(hiding_num)

# <代码示例> find()
search = '168'
num_a = '1386-168-0006'
num_b = '1681-222-0006'
num_a.find(search)      #返回'168'的第一位在num_a中的位置,返回5,即第6位
print( search + ' is at ' + str(num_a.find(search)+1) \
       + ' to ' \
       + str( num_a.find(search)+len(search) ) \
       + ' of num_a.' )
print( search + ' is at ' + str(num_b.find(search)+1) \
       + ' to ' \
       + str( num_b.find(search)+len(search) ) \
       + ' of num_b.' )
#5
#168 is at 6 to 8 of num_a.   #5+1, 5+3
#168 is at 1 to 3 of num_b.   #0+1, 0+3

# <代码示例> format()
# 1
print( '{} a word she can get what she {} for.'.format('_'*5, '_'*5) )
print( '{} a word she can get what she {} for.'.format('With', 'came') )
print( '{0} a word she can get what she {1} for.'.format('With', 'came') )
print( '{str_1} a word she can get what she {str_2} for.'.format(str_1='With', str_2='came') )
#_____ a word she can get what she _____ for.
#With a word she can get what she came for.
#With a word she can get what she came for.
#With a word she can get what she came for.

# 2 输入城市名称并赋值到city中,将city名称传入url,则能够使用百度提供的天气API查询当前天气
city = input('Write down the name of city:')
url = "https://jisuweather.api.bdymkt.com/weather/{}".format(city)
print(url)
#(输入)London
#https://jisuweather.api.bdymkt.com/weather/London
6 列表List
# <代码示例> 列表
# append() 向列表中插入内容
# 列表的索引,与字符串基本一致,把列表中的每一个元素看作字符串中的每一个字符
album = []
album = ['Black Star', 'David Bowie', 25, True]
album.append('new song')
print(album[0], album[-1])      #Black Star new song
print(album, album[0:], album[:3])

2 – 函数

一、内建函数

1 常用的内建函数
print()
input()
len()
#类型转换
type()
int()
bool()
float()
complex()
str()
#attribute属性
getattr()
hasattr()
setattr()
2 Python3的内建函数-69个

参考1:https://docs.Python.org/3/library/functions.html

参考2:https://www.runoob.com/python/python-built-in-functions.html

#Built-in Functions
# A -4
abs()
all()
any()
ascii()
# B -4
bin()
bool()
breakpoint()
bytearray()
bytes()
# C -5
callable()
chr()
classmethod()
compile()
complex()
# D -4
delattr()
dict()
dir()
divmod()
# E -3
enumerate()
eval()
exec()
# F -6
filter()
float()
format()
frozenset()
# G -6
getattr()
globals()
hasattr()
hash()
help()
hex()
# I -6
id()
input()
int()
isinstance()
issubclass()
iter()
# L -3
len()
list()
locals()
# M -4
map()
max()
memoryview()
min()
# N -1
next()
# O -4 
object()
oct()
open()
ord()
# P -3 
pow()
print()
property()
# R -4
range()
repr()
reversed()
round()
# S -8
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
# T -2
tuple()
type()
# V -1
vars()
# Z -1
zip()
# * -1
__import__()
3 数学运算符
+ - * /    #四则运算
//    #返回商的整数部分
%     #模运算,求余数
**    #幂运算,与pow(a,b)用法相同

二、自定义函数

1 创建函数

注意:半角英文冒号,return前需要缩进

# <TEMPLATE> 创建函数
# def-definition; args-参数
def function(arg1, arg2):
    return <Something>

# <代码示例>
# (1) 摄氏度转换成华氏度,调用输入的值
def C2H(C):
    H = C * 9/5 + 32
    return str(H) + 'H'
celsius = input('Input Celsius:')      #35
print( C2H(int(celsius)) )             #95.0H

# (2) 重量转换器:g转换成kg
def G2KG(G):
    KG = G/1000
    return print(str(KG) + 'KG')
G2KG(1520)      #1.52KG

# (3) 计算直角三角形斜边的长度
def Triangle(a, b):
    c = pow(a*a+b*b, 0.5)
    return print(c)
Triangle(3,4)      #5.0
2 传递参数与参数类型
# 传递参数的两种方式
# (1)位置参数 - positional argument
def function(arg1, arg2, arg3):
    return <>
# (2)关键词参数 - keyword argument
def function(arg1=1, arg2=2, arg3=3):
    return <>

# 调用格式
function(1, 2, 3)                  #RIGHT! 参数按位置依次传入
function(arg1=3, arg2=2, arg3=1)   #RIGHT! 参数反序传入,但关键词参数打乱顺序不影响函数执行
function(1, 2, arg3=3)             #RIGHT! 参数正序传入
function(1, 2)                     #RIGHT! 参数正序传入,缺省关键词参数
function(arg3=3, arg2=2, 1)        #WRONG! 参数反序传入,其中包含位置参数,顺序不对,报错
function(arg1=1, arg2=2, 3)        #WRONG! 位置参数不能置于关键词参数后面
# 文件操作
file = open('/Users/apple/Desktop/text.txt', 'w')
file.write('Hello World!')
file.close()
#Hello World!

# <代码示例>
# 1 在桌面创建自命名的txt文件,同时写入数据
def text_create(name, msg):
    desktop_path = '/Users/apple/Desktop/'
    full_path = desktop_path + name + '.txt'
    file = open(full_path, 'a+')
    file.write(msg)
    file.close()
    print('DONE!')
text_create('hello', 'hello world!')
#桌面出现名为hello.txt的文本文件,第一行出现hello world!

# 2 关键字过滤,使用replace()
def text_filter(word, censored_word = 'lame', changed_word = 'AWESOME'):
    return word.replace(censored_word, changed_word)
text_filter('Python is lame!')
#Python is AWESOME!

# 3 在新函数中调用前两个函数
def text_filter_create(name, msg):
    msg = text_filter(msg)
    print(msg)
    text_create(name, msg)
text_filter_create('test', 'Python is lame.\n')
text_filter_create('test', 'Python is lame.\n')
#Python is Awesome!
#Python is Awesome!

3 – 循环与判断

一、判断

1 逻辑判断
# 比较运算符
# 不同类型之间只能使用 == 和 != 进行比较
# True=1 False=0 所以 True>False
== !=
> <
>= <=

# 成员运算符,等价于==
is
# 身份运算符
in
# 布尔运算符
not
and
or
2 if-else语句
# <TEMPLATE> if-else
# <condition>返回值为True
if <condition>:
    <do something>
elif <condition>:
    <do something>
else:
    <do something>
# <代码示例> if-else 密码
password_list = ['*#*#', '12345']

# 创建函数:输入密码-登录成功/改密码
def account_login():
    password = input('Password:')
    password_true = (password == password_list[-1])
    password_reset = (password_list[0])
    if password_true:
        print('Login Success!')
    elif password_reset:
        new_password = input('Wrong! Enter a new password:')
        password_list.append(new_password)
        print('Your password has changed successfully!')
        account_login()
    else:
        print('Wrong password or invalid input!')
        account_login()

account_login()

二、循环

1 for循环
# <TEMPLATE> for
for <变量名> in <可迭代的集合>:
    <do something>

# <代码示例> 打印九九乘法表
for i in range(1,10):
    for j in range(1,10):
        print('{} * {} = {}'.format(i,j,i*j))
2 while循环
# <TEMPLATE> while
while <条件>:
    <do something>
    
# <代码示例> 
# (1)死循环。条件永远为真,需要强制停止运行
while 1:
    print('Infinite Loop! 死循环环环环环...')
# (2)执行5遍,break跳出循环
cnt1 = 0
while 1:
    print('随便写点什么1')
    cnt1+=1
    if (cnt1 == 5):
        break

cnt2 = 0
while (cnt2 < 5):
    print('随便写点什么2')
    cnt2+=1
3 练习题
# 简单的习题
# Practice 1 -- 在桌面创建10个txt,并以数字的顺序命名
for count in range(1,11):
    file = open('/Users/apple/Desktop/{}.txt'.format(count), 'a')
    file.close()
    print(str(count) + '.txt FINISHED')

# Practice 2 -- 复利:A(1+x)^t=B
def invest(amount, rate, time):
    print('principal amount: ' + str(amount))
    for count in range(1,time+1):
        invest = ((1+rate*0.01)**count) * amount
        print('year '+ str(count) + ': $' + str(invest))
        count+=1
invest(100,5,8)

# Practice 3 -- 打印1~100内的偶数
for count in range(1,101):
    if (count%2==0):
        print(count)
# 练习题:注册账户时,为了正确发送验证码,判断输入的电话号码
CN_mobile = ['134','135','136','137','138','139','150','151','152','157','158','159','182','183','184','187','188','147','178','1705']
CN_union = ['130','131','132','155','156','185','186','145','176','1709']
CN_telecom = ['133','153','180','181','189','177','1700']

def SIGNIN():    
    num = input('Enter Your Number: ')
    
    if len(num) == 11:
        if (num[0:3] in CN_mobile) or (num[0:4] == '1705'):
            print('Operator: China Mobile\n'+str(num)+' Verification Code Sended.')
        elif (num[0:3] in CN_union) or (num[0:4] == '1709'):
            print('Operator: China Union\n'+str(num)+' Verification Code Sended.')
        elif (num[0:3] in CN_telecom) or (num[0:4] == '1700'):
            print('Operator: China Telecom\n'+str(num)+' Verification Code Sended.')
        else:
            print('No such an operator!\n')
            SIGNIN()            
    else:
        print('Invalid lengthm your number shoulde be in 11 digits.\n')
        SIGNIN()

4 – 数据结构

一、四种数据结构

列表list 字典dict 元组tuple 集合set

1 列表 list = []

每一个元素都是可变的

元素有序

可以容纳Python中的任何对象

可以通过分片来查询 [a:b],只能用位置进行索引

类比数组

# list[]的增删改查
# 增
<list>.insert('~', '~')
# 删
<list>.remove('~')
del <list>[i:j]
# 改
list[i] = '~'
# 查:列表只接受用位置进行索引
2 字典 dict = {}

key-value 键值对

字典中数据必须以键值对的形式出现

键不能重复,值可以重复

键不可变,无法修改;值可变、可修改,可以是任何对象

不能通过分片来查询

# dict{}的增删改查
#增
<dict>[key] = {
    
    value}
<dict>.update( {
    
    key1:value1, key2:value2} )
#删
del <dict>[]
#查
<dict>[key]

3 元组 tuple

稳固版的列表,不可修改,可以查看索引

4 集合 set

集合中的元素是无序、不重复的任意对象

不能切片、不能被索引

可以做集合运算

集合元素可以被添加、删除

二、数据结构的基础技巧

1 多重循环
2 推导式
3 循环列表时获取元素的索引
4 综合项目

猜你喜欢

转载自blog.csdn.net/m0_47892534/article/details/113101941