Python基础知识入门PartI

这篇文档是李宁老师关于Python基础知识的入门教程,涵盖了Python的介绍、环境搭建、基础语法、条件循环、数据结构(列表、元组、字符串、字典)、函数、类、异常处理、方法、属性和迭代器等内容,适合初学者学习。
摘要由CSDN通过智能技术生成

本文档整理自李宁老师发布在B站的视频,主要介绍python相关的基础入门知识,相关代码和本文档(md格式)提取码:pyth
Part II 12-18章

1-11章

1 Python简介

一种面向对象的解释型语言,由荷兰人于1989年创建;
Python开源,GPL,强制使用空格作为语句缩进;
有丰富的Library,胶水语言(可以与其他语言结合)。

1.1 Python程序运行

Python test.py是将test.py编译成Python Byte Code字节码,然后由Python虚拟机PVM运行,在计算机输出结果。解释型语言是指解释Python字节码。PVM更贴近应用层;

1.2 应用领域

Linux/Unix运维,比shell功能强大;
开发命令行程序;
桌面GUI应用(PyQt、Kivy等);
移动APP(PyQt、Kivy等);
Web应用(Django框架等);
服务端应用(基于TCP协议的服务端程序);
网络爬虫(为搜索引擎、深度学习等提供数据源);
数据分析;
深度学习;
科学计算。

1.3 搭建Python开发环境

Anaconda集成了很多库。

2 Python基础知识

2.1 变量名

Python是一种动态语言,变量的数据类型是根据具体的值动态确定;
变量名通常由字母、数字、下划线组成,变量名不能以数字开头;

2.2 清空Python控制台

win+R调出控制台后,键入Python,调出Python的命令行工具;
win控制台下,输入cls可以清空界面;
在C:\Users\42524\clear.py中定义了clear函数,用于Windows下清空控制台;
import clear;然后调用clear.clear(),就能清空控制台;
或 from clear import clear,调用clear()。

2.3 数字的基础知识

除号得出的结果都是浮点数;
整除运算符//:5.2//2=2.0;5//2=2;
幂运算**:2**3=8;
取余%:5%2=1;5.2%2=1.2;
优先级:括号里的运算、幂运算、乘除&整除取余、加减;

2.4 大整数

Java中的int:-231到231-1,Java中提供了BigInteger类;
Python中基本没有限制,适合科学计算。

2.5 进制转换

十进制:0-9、表示为123;
二进制:0b,0b110101101;
八进制:0o,0o424511;
十六进制:0-9与A-F,表示为0x,0xFF12E;
除了十进制,其他三种进制都表示为一段字符串;

强制类型转换

int:其他进制转十进制,有两个参数,如int(“0xFF12E”,16);
bin:其他进制转二进制;
oct:其他进制转八进制;
hex:其他进制转十六进制。

2.6 数字的格式化输出

format函数有两个参数:1、要格式化的数字;2、格式字符串;  
print(format(x, '0.2f'));  
左对齐并补0print(format(x, '0<12.2f')),输出1234.5700000;  
右对齐并补0print(format(x, '0>12.2f')),输出000001234.57;  
中心01234.57000;  
千对齐并补0print(format(x,'0^12.2f')),输出0分位逗号:print(format(x, ',.2f')),输出1,234.57;  
科学计数法:print(format(x, '.2e')),输出1.23e+03

2.7 注释

单行注释:#
多行注释:‘’‘多行注释’‘’ 或者 “”“多行注释”“”
首行加# coding = utf-8,确保中文注释可以在任何文件中显示

2.8 字符串表示

Python支持单引号、双引号字符串
转义符\:字符串中同时输出单引号和双引号时,"Hello ‘w’“o"rld”

2.9 保持字符串中的转义符原样输出

1、使用repr函数:repr(“hello\nworld”)
2、使用转义符输出\:“hello\nworld”
3、字符串前面加上r:r"hello\nworld"

3 条件-循环和其他语句

3.1 print函数

sep参数可以指定参数值之间的分隔符

print('Ruby,' + 'Python,' + 'Java,' + 'Perl')  
print('Ruby', 'Python', 'Java', 'Perl', sep=",")  
# 均输出:Ruby,Python,Java,Perl  
# 通过命名end可以改变输出字符串结尾的字符,默认为换行,即\n  

3.2 赋值操作

Python允许多个变量同时赋值以及交换两个变量的值  
x, y, z = 10, 20, 30  
x, y = y, x  
x += 1等同于x = x + 1  

3.3 布尔值与布尔变量Boolean

True、False
Python中每一种类型的值都可以被解释为布尔值
解释为False:None、0、()、[]、{}
Python中把True当做1、False当做0进行运算
print(12 + True + False),输出:13
在==运算符下,只有把1当做True,0当做False,其余需要bool()函数进行转换,才能与布尔值进行匹配
print(1 == True):True
print(2 == True):False
print(‘’ == False):False
print(bool(‘’) == False):True

3.4 if语句

以if……elif……else……结构体形式

n = 4
if n == 3:
    print("n == 3")
elif n == 5:
    print("n == 5")
else:
    print("n != 3")

if语句中也可以再嵌套一个if结构体,判断时代码缩进量一致的处于同一层次的条件结构中

3.5 比较运算符

大小比较,返回值为布尔值
is 关键字用于测试两个变量是否引用同一对象:如果两个对象不是同一对象,即使两个对象 100% 相等,也会返回False

3.6 断言assertion

TDD(Test-driven development):测试时,设置条件,不满足时抛出异常;
满足条件时,程序编译正常,不满足时会抛出AssertionError。

x = 4
assert x > 10
# ++++++++++++++++++++++++++++++++++++++
# 不满足条件,会抛出异常
Traceback (most recent call last):
  File "D:\Projects\Python\test\first.py", line 2, in <module>
    assert value > 10
AssertionError

3.7 for循环

对一个序列进行操作
跳出循环
  break直接跳出最内层的循环
  continue,跳出当前的循环,即循环体中continue之后的语句不执行,直接进入下一次的循环
  在嵌套循环中,break、continue都是跳出离它们最近的循环
循环中的else语句
else语句仅仅在while或for循环正常退出时执行,可以用来判断循环是否中途退出

3.8 exec-eval函数动态执行python代码

exec中的字符串语句执行后产生的是全局变量,甚至可以将函数名重新作为变量名赋值(导致函数失效,要避免这种用法)
用exec实现简略版的python控制台

codes = ""
while True:
    code = input(">>>")
    if code == "exit":
        break
    if code == "":
        exec(codes)
        codes = ""
        continue    #跳出此次循环,不再执行下一行代码
    codes += code + "\n"

eval用于执行字符串表达式,并返回值

4 列表和元组

分片Slicing

截取子字符串、子列表等,str[start:end]截取的子串内容是start到end-1对应的字符
当结束索引end小于开始索引start时,返回一个空列表或空的字符串
开始索引或结束索引也可以省略

设置分片步长
str[start : end : step]  
# 步长step可以设置为负数,此时start要大于end,而且截取出来的子列表或子串中元素的排列顺序与原来的是颠倒的  

4.1 检查某个值是否属于一个序列

in运算符:返回布尔类型

4.2 列表的基本操作:赋值/删除元素/分片赋值

# 1、赋值
values = ['Bill', 'Mary', 'John']
values[0] = 'Mike'
values[1] = 10.4
values[-1] = 'Joe'
print(values)

# 2、删除元素
numbers = [1,2,3,4,5,6,7,8]
del numbers[3]
print(numbers)

# 3、分片赋值
names = ['Bill', 'Joe', 'Mike', 'Harry']
names[3:] = ['a', 'b', 'c']
print(names)
numbers[3:6] = []   # 使用分片赋值删除多个元素
print(numbers)
['Mike', 10.4, 'Joe']
[1, 2, 3, 5, 6, 7, 8]
['Bill', 'Joe', 'Mike', 'a', 'b', 'c']
[1, 2, 3, 8]

4.3 列表中的特有方法

'''
1、append:在列表最后插入新的值
2、clear:用于清除列表的内容
3、copy:用于复制一个列表
4、count:用于统计某个元素在列表中出现的次数
5、extend:在列表结尾插入另一个列表,该方法改变的是被扩展的列表
    如:list1.extend(list2),list1被修改了
6、index:从列表中找出某个值第一次出现的索引位置
7、insert:将值插入到指定位置
8、pop:移除列表元素(默认是最后一个),并返回该元素的值
9、remove:移除列表中某个值的第一次匹配项
10、reverse:将列表元素反向存放
11、sort:列表排序,调用该方法会改变原来的列表
'''
print('-----------append----------')
numbers = [1, 2, 3, 4, 5]
numbers.append(20)
numbers.append([1, 2, 3])
print(numbers)
print('------------clear-----------')
numbers.clear()
print(numbers)
print('-----------copy-----------')
numbers = [1, 2, 3, 4, 5]
a_copy1 = numbers
a_copy2 = numbers[:]
a_copy3 = numbers.copy()
# 后两种方法获得了原有列表的一个副本
numbers[3] = 'hello'
print(a_copy1, a_copy2, a_copy3, sep='\n')
print('-----------count------------')
search = ['he', 'new', [1, 2, 3], 'he', [1, 2, 3], 'he', 'world']
print(search.count('he'))
print(search.count([1, 2, 3]))
print(search.count(20))
print('----------extend------------')
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b) # extend操作不会产生新列表
a[1:3] = []
print('a =', a, 'b =', b)
x = a
a = a + b   # +号连接后创建了新的列表赋给a,所以此时的a与原来的a(或x)不同
x[2] = 123
print('a =', a, 'x =', x)
print('------------index----------')
a = [3, 4, 7, 3, 8]
print(a.index(3))
# print(a.index(10))    # 指定的值不在列表中,会抛出异常
print('-------------insert-----------')
numbers = [1, 2, 3, 4, 5]
numbers.insert(3, 'four')   # 插入的元素在numbers[3]
numbers[2:2] = ['four']     # 插入的元素在numbers[2]
print(numbers)
print('-------------pop-------------')
numbers = [1, 2, 3]
print(numbers.pop())
print(numbers.pop(0))
print(numbers)
print('----------remove-----------')
numbers = [1, 2, 3, 1]
numbers.remove(1)
print(numbers)
print('----------reverse----------')
numbers = [1, 2, 3, 4]
numbers.reverse()
print(numbers)
print('------------sort-------------')
numbers.sort(reverse= False)    # 参数为False,按从小到大排序
print(numbers)
a = [1, 2, 4, 7, 3]
b = sorted(a)   # 不会改变a,而是产生一个排好序的新列表
print('a=', a, 'b=', b)
-----------append----------
[1, 2, 3, 4, 5, 20, [1, 2, 3]]
------------clear-----------
[]
-----------copy-----------
[1, 2, 3, 'hello', 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
-----------count------------
3
2
0
----------extend------------
a = [1, 4, 5, 6] b = [4, 5, 6]
a = [1, 4, 5, 6, 4, 5, 6] x = [1, 4, 123, 6]
------------index----------
0
Traceback (most recent call last):
  File "D:\Projects\Python\test\first.py", line 50, in <module>
    print(a.index(10))
ValueError: 10 is not in list
-------------insert-----------
[1, 2, 'four', 3, 'four', 4, 5]
-------------pop-------------
3
1
[2]
----------remove-----------
[2, 3, 1]
----------reverse----------
[4, 3, 2, 1]
------------sort-------------
[1, 2, 3, 4]
a= [1, 2, 4, 7, 3] b= [1, 2, 3, 4, 7]

4.4 元组

a = ()
b = (1, 2, 3)
c = 1, 2, 3, 4, 5
x = 30,
print(c, x, (12,) * 4)
b.index(1)
b.count(1)
'''
1、元组可以在映射中作为键值使用,而列表不能作为键值使用
2、很多内建函数和方法的返回值是元组
3、元组不可修改(除非整体重新赋值),列表的其他操作基本都能在元组中实现
'''
(1, 2, 3, 4, 5) (30,) (12, 12, 12, 12)

5 字符串

5.1 字符串:基本操作

s1 = 'I love python.'
print(s1[7])
# print(s1[15])     # 超出范围,抛出异常
print(s1[::2])
print("abc" * 2)
print('python' in s1)
print(len(s1), max(s1), min(s1))    # 按照ASCII码排序,这里最小的是空格' '
p
Ilv yhn
abcabc
True
14 y  

5.2 字符串格式化

'''
字符串分为静态、动态两部分:如 Hello param_name
字符串格式化就是把一个或多个值替换另一个字符串的某个标记
% :格式化字符串,%f浮点数,%d整数
'''
formatStr = "Hello %s. Today is %s. Are there any activities today?"
values = ('John', "Wednesday")  # 元组可以同时替换多个标记
print(formatStr % values)

Str = '这件事的成功率是%d%%,如果有%s参与的话,成功率会提升至%d%%'
values1 = (56, 'John', 70)
print(Str % values1)
Hello John. Today is Wednesday. Are there any activities today?
这件事的成功率是56%,如果有John参与的话,成功率会提升至70%

5.3 Template类格式化字符串

'''
标记:$name,格式化方式:substitute
'''

from string import Template
temp1 = Template('$lang是我最喜欢的编程语言,$lang非常容易学习,而且功能强大')
print(temp1.substitute(lang = 'Python'))

temp2 = Template('${s}stitute') # 用花括号将静态部分与动态部分分隔
print(temp2.substitute(s = 'sub'))

temp3 = Template('$$$dollar相当于多少$pounds')
print(temp3.substitute(dollar = 20, pounds = '英镑'))

data = {
   }
data['dollar'] = 100
data['pounds'] = '英镑'
print(temp3.substitute(data))   # 使用字典对关键字进行替换
Python是我最喜欢的编程语言,Python非常容易学习,而且功能强大
substitute
$20相当于多少英镑
$100相当于多少英镑

5.4 format方法格式化字符串

# 标记:{...},格式化方法:Str.format(...)
# 1、按顺序来指定格式化参数值
s1 = 'Today is {}, the temperature is {} degrees.'
print(s1.format('Saturday', 30))

# 2、使用命名格式化参数
s2 = 'Today is {week}, the temperature is {degree} degrees.'
print(s2.format(degree = 21, week = 'Sunday'))  # 使用命名方式,标记的顺序可以颠倒

# 3、混合使用
s3 = 'Today is {week}, {}, the {} temperature is {degree} degrees.'
print(s3.format('abcd', 1234, degree = 43, week = 'Sunday'))
# 顺序参数必须在关键字参数之前,否则会报错:
# print(s3.format('abcd', degree = 43, 1234,  week = 'Sunday'))
                                        
#SyntaxError: positional argument follows keyword argument

# 4、使用序号格式化参数
s4 = 'Today is {week}, {0}, the {0} temperature is {degree} degrees.'
print(s4.format('abcd', 1234, degree = 43, week = 'Sunday'))
# 序号不能超过输入的顺序参数的数量,否则会报错,但字符串中可重复调用同一个序号的参数

# 5、获取列表中的指定值
fullname = ['Bill', 'Gates']
s5 = 'Mr.{name[1]}'
a = f"Mr.{
     fullname[1]}"
print(s5.format(name = fullname), a)

import math
s6 = 'The {mod.__name__} module defines the value {mod.pi} for PI.'
print(s6.format(mod = math))
Today is Saturday, the temperature is 30 degrees.
Today is Sunday, the temperature is 21 degrees.
Today is Sunday, abcd, the 1234 temperature is 43 degrees.
Today is Sunday, abcd, the abcd temperature is 43 degrees.
Mr.Gates Mr.Gates
The math module defines the value 3.141592653589793 for PI.

5.5 字段宽度/精度和千位分隔符

# 让一个数值在宽度为12的范围内输出,如果数值没到12位,左侧填充空格
print(f"a:{
     32:12}")

print(f"{
     '姓名':10}{
     '年龄':6}")
# f之后是单引号,则里面需要用双引号,否则会报错,反之也是
print(f"{
     'Bill':10}{
     34:6}")
print(f"{
     'Mike':10}{
     25:6}")
# 每个汉字会被当做一个字符,但其占用的宽度约为一个英文字符的1.5倍
# 字符串输出时默认左对齐,数值输出时默认右对齐

import math

print(f"float number:{
     math.pi:7.4f}")
# 7为输出的总位数(小数点也作为一位),4是小数点后的位数

print(f"{
     'Hello World!':.5}")  # 截取前五位

print(f"One google is {
     10 ** 10:,}")    # 千分位分隔符
a:          32
姓名        年龄    
Bill          34
Mike          25
float number: 3.1416
Hello
One google is 10,000,000,000

5.6 符号/对齐和用0填充

from math import pi
print(f"{
     pi:012.3f}")
print(f"{
     pi:*12.3f}")   # 此时不会用*填充

# <(左对齐) ^(中对齐) >(右对齐)
print(f"{
     pi:*<12.3f}")
print(f"{
     pi:*^12.3f}")
print(f"{
     pi:*>12.3f}")

print(f"{
     -pi:*=12.3f}")
# 用=会在符号与数字之间填充前面的#
# '=':强制在符号(如果有)之后数码之前放置填充。这被用于以 '+000000120' 形式打印字段。这个对齐选项仅对数字类型有效。
# 这是当 '0' 紧接在字段宽度之前时的默认选项。
00000003.142
       3.142
3.142*******
***3.142****
*******3.142
-******3.142

5.7 字符串方法:center

print("<" + "hello".center(30) + ">")
print(f"<{
     'hello':^30}>")
print("<" + "hello".center(20, "*") + ">")
# center的第二个参数必须是一个长度为1的字符串
print(f"<{
     'hello':*^20}>")
<            hello             >
<            hello             >
<*******hello********>
<*******hello********>

5.8 字符串方法:find

s = "hello world"
print(s.find("world"))
print(s.find("abc"))
print(s.find("o"))
print(s.find("o", 5))
print(s.find("l", 5, 9))
# 在s[start]到s[end-1]的范围内查找
6
-1
4
7
-1

5.9 字符串方法:join

list = list("abcde")
s = "*"
print(s.join(list))

# windows系统目录格式:C:\abc\xyz
# Linux系统目录格式:/abc/xyz
# 使用join方法来转换不同操作系统之间的目录

dirs = "", "usr", "local", "nginx", ""
linuxPath = "/".join(dirs)
print(linuxPath)
windowPath = "C:" + "\\".join(dirs)
print(windowPath)
a*b*c*d*e
/usr/local/nginx/
C:\usr\local\nginx\

5.10 字符串方法:split方法

# join方法产生字符串,split方法产生列表
s1 = "a b c d e f"
print(s1.split())
s2 = "a*b*c*d*e*f"
print(s2.split("*"))
path = "/usr/local/ngnix"
pathlist = path.split("/")
print(pathlist)
windowPath = "D:" + "\\".join(pathlist)
print(windowPath)
['a', 'b', 'c', 'd', 'e', 'f']
['a', 'b', 'c', 'd', 'e', 'f']
['', 'usr', 'local', 'ngnix']
D:\usr\local\ngnix

5.11 字符串方法:lower/upper和capwords

print("HEllo".lower())
print("hello".upper())

list = ["Python", "Ruby", "Java", "KOTLIN"]
for lang in list:
    if "kotlin" == lang.lower():
        print("找到KOTLIN")
        break
from string import capwords
s = "i not only like PYTHON, but also like Kotlin. so what about you?"
print(capwords(s,sep='. '))
print(capwords(s))
hello
HELLO
找到KOTLIN
I not only like python, but also like kotlin. So what about you?
I Not Only Like Python, But Also Like Kotlin. So What About You?

5.12 字符串方法:replace和strip

s = "abaga"
print(s.replace("a", "123"))
print(s.replace("abc", "123"))
str1 = "    geekori.com     "
str2 = "  <   geekori.com    >   "
print(str1.strip())
print(str2.strip())
print("  python   " == "python")
str3 = "***$$$ *** Hello *$ world  $$**"
print(str3.strip(" *$"))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值