Python基础教程(一)

1.编程基础

1.1标识符

标识符是变量、函数、模块和其他对象的名称。Python中标识符的命名不是随意的,而是要遵守一定的命名规则,比如说:

        1、标识符是由字母 (A~Z 和 a~z) 、下划线和数字组成,但第一个字符不
能是数字。
        2、标识符不能和 Python 中的保留字(关键字)相同。
        3、Python 中的标识符中,不能包含空格、@、% 以及 $等特殊字符。
        4、在 Python 中,标识符中的字母是严格区分大小写的。
        5、Python 语言中,以下划线开头的标识符有特殊含义,例如:_width、__add、__init__

1.2 关键字

False    class    from    def    if    raise    in    True    try
assert    else    with    await  finally    or    None    and    del   
is    while    nonlocal    continue    global    pass    import    as    
elif    return    lambda    async    except    yield    break    for not

1.3变量

>>> greet="hahaha"
>>> greet
'hahaha'
>>> score=95.5
>>> score
95.5
>>> x=10
>>> x
10
>>> x=30
>>> x
30
>>> x=True
>>> x
True
>>>

1.4 语句

Python代码是由关键字、标识符、表达式和语句等构成的,语句是代码的重要组成部分。语句结尾的逗号加不加都可以。

>>> greet="Holle world"
>>> score=95.5
>>> a=b=c=10
>>> b
10
>>> score
95.5
>>>

1.5代码注释

#这是一个整形变量
score=95
print(score)#打印score变量
'''
zzz
bbfdf
hahahah
'''

"""
gesgs
....
sdvss
"""

#表示单行注释

'''

'''表示多行注释

"""

"""表示多行注释

1.6模块

模块就是一个包含了Python定义和声明的“.py”文件。
import<模块名>
from<模块名> import<代码元素>
from<模块名> import <代码元素> as<代码元素别名>

2.数字类型的数据

2.1 数据类型

Python中有6种主要的内置数据类型:数字、字符串、列表、元组、集合和字典
Python中有4种数字类型整数类型、浮点类型、复数类型和布尔类型

2.2 整数类型

Python中整数类型为int类

>>> 10
10
>>> 0o10  #八进制
8
>>> 0x0A  #十六进制
10
>>> 0b1010  #二进制
10
>>> type(0x0a)
<class 'int'>
>>> 

2.3 浮点类型

Python中浮点类型为float类

>>> type(1.11)
<class 'float'>
>>> 

2.4 复数类型

复数在数学中被表示为: a+bi,其中a为实部,b为虚部,i为虚数单位。
在Python中虚数单位为j或者J。

>>> c=3+2j
>>> c
(3+2j)
>>> type(c)
<class 'complex'>
>>> a=complex(3,2)
>>> a
(3+2j)
>>> 

2.5 布尔类型

Python中的布尔类型为bool类,它只有两个值: True和False。

>>> bool(None)
False
>>> bool(0)
False
>>> bool([])
False
>>> bool(2)
True
>>> bool("")
False
>>> bool(" ")
True

2.6 数字类型相互转换

2.6.1 隐式类型的转换

数字之间可以进行数学计算,在进行数学计算时若数字类型不同,则会发
生隐式类型的转换。

>>> a=1+True
>>> a
2
>>> a=1.0+1
>>> a
2.0
>>> a=1.0+False
>>> a
1.0

2.6.2 显式类型的转换(强制转换)

>>> a=int(1.0)+1
>>> a
2
>>> int(False)
0
>>> int(True)
1
>>> int(0.3)
0
>>> float(3)
3.0
>>> float(True)
1.0
>>> 

3.运算符

3.1 算术运算符

3.2 比较运算符

3.3 逻辑运算符

3.4 位运算符

3.5 赋值运算符

4.程序流程控制

4.1 分支语句

4.1.1 if语句

if 条件表达式:
语句块

age=5
if age>3:
    print("hahaha")

4.1.2 if-else语句

if 条件表达式:
        语句块1
else:
        语句块2

u_name=input("请输入用户名:")
pwd=input("请输入密码:")
if u_name=="admin" and pwd=="123":
    print("登入成功!即将进入主界面...")
else:
    print("您输入的用户名或密码错误,请重新输入...")

4.1.3 if-elif-else语句

if 条件表达式1:
        语句块1
elif条件表达式2:
        语句块2
elif条件表达式n:
        语句块n
else:
        语句块n+1

score=int(input("请输入您的会员积分:"))
if score==0:
    print("注册会员")
elif 0<score<=200:
    print("铜牌会员")
elif 200<score<=1000:
    print("银牌会员")
elif 1000<score<=3000:
    print("金牌会员")
else:
    print("钻石会员")

4.1.4 嵌套分支结构

if 条件表达式1:
        if条件表达式2:
                语句块1
        else:
                语句块2
else:
        语句块3

id_code = input('请输入身份证号码:')
if len(id_code) == 18:
    number = int(id_code[-2])
    if number%2 == 0:
        print("女性")
    else:
        print("男性")
else:
    print("输入不合法")

4.2 循环语句

4.2.1 while循环

while 判断条件:
        语句

# 输出1-100的所有数的和
count = 0
num = 0
while count < 100:
    count = count + 1
    num = num + count
print("1-100的所有数的总和为: 和",num)

#无限循环
while True:
    num=int(input("请输入一个数字:"))
    print("您输入的数字是:",num)

4.2.2 for循环

for 临时变量 in 可迭代对象:
执行语句1
执行语句2

#数组遍历
languages =["c","Python","Java","C#"]
for x in languages:
 print("当前语言是:",x)

#输出[0~6),左开右闭包含0不包含6
for i in range(6):
    print("当前的数列为:",i)

#输出[1~3),左开右闭包含1不包含3
for i in range(1,3): #范围从1开始,不包含最后一个数字
    print(i)

#输出九九乘法表
for i in range(1, 10):#遍历9次,打印9行
    for j in range(1,10): #遍历9次,打印9列的数据
      if j<= i: # 当列数<=行数的时候,就可以打印乘法公式
        print(f"{j}*{i}={j*i}".format(j, i),end='\t')
    print("\n")

4.3 跳转语句

4.3.1 break语句

break:跳出循环

#遇到l跳出循环
for s in 'Hello':
    if s =='l':
        break
    print('当前字母为 :', s)


#判断质数
for n in range(2,10):
    for x in range(2,n):
        if n%x==0:
            print(n,'等于',x,'*',n//x)
            break
    else:   #当从内循环break跳出后不会执行else内的语句,否则会执行
        print(n,'是质数')

4.3.2 continue语句

continue:跳过本次循环

#当x<=0跳过本次循环
for x in [0,-2,5,7,-10]:
    if x<=0:
        continue
    print(x)

4.4 pass语句

pass:作用是占位,保持语句结构的完整,相当于{}

x=0
if x<=0:
    pass#作用是占位,保持if语句结构的完整

5.容器类型数据

5.1 序列

在 Python 中,序列类型包括字符串、列表、元组、集合和字典,这些序列支持以下几种通用的操作,但比较特殊的是,集合和字典不支持索引、切片、相加和相乘操作。

5.1.1 序列索引操作

>>> a="Hello"
>>> a[0]
'H'
>>> a[-5]
'H'
>>> a[5]   #越界访问
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
IndexError: string index out of range
>>> max(a)
'o'
>>> min(a)
'H'
>>> len(a)
5

5.1.2 加和乘操作

注意要同类型才行

>>> a='hello'
>>> print(a+' world')
hello world
>>> print(a+' world'+'你好')
hello world你好
>>> print(a*2)
hellohello

5.1.3 切片操作

sname[start : end : step]

start :切割开始索引,默认为0         end : 切割结束索引,默认为数组最大长度        step:切割步长,默认为1.

>>> str='Hello world'
>>> print(str[:2])  #注意是左闭右开[0,2)切割
He
>>> print(str[::2])  #step表示切割的步长,默认为1
Hlowrd
>>> print(str[:])
Hello world

5.1.4 成员测试

成员测试运算符有两个: in和not in。

>>> str='Hello'
>>> 'e' in str
True
>>> 'E' not in str
True

5.2 列表

5.2.1 创建列表

创建列表的方式非常简单,既可以使用中括号“[]”创建,也可以使用内置的list()函数快速创建。
①使用中括号“[]”创建列表

list_one=[] #空列表
list_two=['p','y','t' , 'h' , 'o' , 'n']#列表中元素类型均为字符串类型
list_three=[1,'a','&',2.3]#列表中元素类型不同

②使用list ()函数创建列表

>>> list_one=list(1)  #参数传递的对象必须是可迭代的
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> list_two=list('python')
>>> list_two
['p', 'y', 't', 'h', 'o', 'n']
>>> list_three=list([1,'python'])
>>> type(list_three)
<class 'list'>
>>> list_three
[1, 'python']
>>> from collections import Iterable  #导入迭代器模块
>>> print(isinstance([],Iterable))
True

5.2.2 追加元素

list_one=list([1,2,3,4])
print(list_one)
list_one.append(10)
print(list_one)
lint_two=list([5,6])
list_one.extend(lint_two)
print(list_one)
lint_two+=list_one
print(lint_two)

5.2.3 插入元素

>>> names=['zhang','li','wang']
>>> names.insert(2,'xiaoqian')   #在索引为2处插入
>>> names
['zhang', 'li', 'xiaoqian', 'wang']

5.2.4 替换元素

>>> names
['zhang', 'li', 'xiaoqian', 'wang']
>>> names[1]='lihua'
>>> names
['zhang', 'lihua', 'xiaoqian', 'wang']

5.2.5 删除元素

删除列表元素的常用方式有del语句、remove()方法和pop()方法

①del语句

>>> names
['zhang', 'lihua', 'xiaoqian', 'wang']
>>> del names[0]
>>> names
['lihua', 'xiaoqian', 'wang']

②remove()方法:元素替换,只会替换第一个符合要求的元素

>>> chars=['h','e','l','l','o']
>>> print(chars)
['h', 'e', 'l', 'l', 'o']
>>> chars.remove('e')
>>> print(chars)
['h', 'l', 'l', 'o']

③pop()方法

>>> numb=[1,2,3,4,5,6]
>>> print(numb.pop())
6
>>> print(numb.pop(2))
3
>>> print(numb)
[1, 2, 4, 5]

5.3 元组

元组 (tuple) 是一种不可变序列类型。元组中的元素是不允许修改的,除非在元组中包含可变类型的数据。

5.3.1 创建元组

①使用圆括号“()”创建元组

tuple_one=()#空元组
tuple_two=('t',' e','p','l','e')#元组中元素类型均为字符串类型
tuple_three=(0.3,1,'python','&')#元组中元素类型不同

②使用tuple()函数创建元组

tuple_null=tuple()
print(tuple_null)

tuple_str=tuple('abc')
print(tuple_str)

tuple_list=tuple([1,2,3])
print(tuple_list)

'''结果
>>> %Run main.py
()
('a', 'b', 'c')
(1, 2, 3)
'''

5.3.2 元组拆包

>>> val=(10,121)
>>> a,b=val
>>> a
10
>>> b
121

5.4 集合

集合集合 (set) 是一种可迭代的、无序的、不能包含重复元素的容器类型的数据。

5.4.1 创建集合

set([iterable])                可变集合
frozenset([iterable])        不可变集合

①可变集合的创建

>>> set_one=set([1,2,3,4])
>>> set_two=set((1,2,3))
>>> type(set_one)
<class 'set'>
>>> type(set_two)
<class 'set'>
>>> set_one
{1, 2, 3, 4}
>>> set_three={1,21,2,11,44,21}
>>> set_three
{1, 2, 11, 44, 21}    #集合元素是无序的

#集合是元素唯一的
>>> set_one=set([1,2,3,1])
>>> set_one
{1, 2, 3}

②不可变集合的创建

>>> frozenset_one=frozenset((1,2,3,4))
>>> frozenset_two=frozenset([1,2,3,4])
>>> type(frozenset_one)
<class 'frozenset'>
>>> frozenset_two
frozenset({1, 2, 3, 4})

5.4.2 修改集合

①添加元素

>>> set_one=set()
>>> set_one
set()
>>> set_one.add('py')    #添加一个元素
>>> set_one
{'py'}
>>> set_one.update('thon')    #添加多个元素
>>> set_one
{'h', 'n', 't', 'py', 'o'}

②删除元素

>>> set_one={'zhangsan','liai','wangwu','xiaoq'}
>>> set_one.remove('zhangsan')
>>> set_one
{'liai', 'xiaoq', 'wangwu'}
>>> set_one.remove('zhangsan')
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
KeyError: 'zhangsan'
>>> set_one.discard('zhangsan')    #如果存在则删除
>>> set_one.discard('liai')
>>> set_one
{'xiaoq', 'wangwu'}
>>> set_one.pop()        #随机删除一个元素
'xiaoq'
>>> set_one
{'wangwu'}

③清空元素

>>> set_one={'zhangsan','liai','wangwu','xiaoq'}
>>> set_one.clear()
>>> set_one
set()

5.5 字典

字典 (dict) 是可迭代的、通过键 (key) 来访问元素的可变的容器类型的数据

5.5.1 创建字典

①使用花括号{}创建字典{键1:值1,键2:值2...}

注意:字典元素是无序的,键和值成对出现,键唯一,值可以不唯一

>>> scores={'zhangsan':100,'lisi':98,'wangwu':45}
>>> scores
{'zhangsan': 100, 'lisi': 98, 'wangwu': 45}
>>> scores_null={}
>>> type(scores)
<class 'dict'>
>>> scores_null
{}
>>> type(scores_null)
<class 'dict'>

②使用内置的dict ( )函数创建字典:dict(键1=值1,键2=值2...)

>>> dict_one=dict(name='zhangsan',age=20)
>>> dict_one
{'name': 'zhangsan', 'age': 20}
>>> dict_two=dict({100:'zhangsan',101:'lisi',102:'wangwu'})
>>> dict_two
{100: 'zhangsan', 101: 'lisi', 102: 'wangwu'}
>>> dict_three=dict(((100,'zhangsan'),(101,'lisi')))
>>> dict_three
{100: 'zhangsan', 101: 'lisi'}
>>> dict_four=dict([(100,'zhangsan'),(101,'lisi')])
>>> dict_four
{100: 'zhangsan', 101: 'lisi'}
>>> dict_five=dict([(100,'zhangsan'),(100,'wangwu'),(101,'lisi')])
>>> dict_five
{100: 'wangwu', 101: 'lisi'}

5.5.2 修改字典

①添加和修改字典元素

>>> add_dict={'stu1':'zhangsan'}
>>> add_dict.update(stu2='lisi')
>>> add_dict
{'stu1': 'zhangsan', 'stu2': 'lisi'}
>>> add_dict['stu3']='wangwu'
>>> add_dict
{'stu1': 'zhangsan', 'stu2': 'lisi', 'stu3': 'wangwu'}
>>> add_dict['stu1']='xiaoqian'
>>> add_dict
{'stu1': 'xiaoqian', 'stu2': 'lisi', 'stu3': 'wangwu'}

②删除字典元素

>>> dist_one={'001':'zhangsan','002':'lisi','003':'wangwu','004':'xioaqian'}
>>> dist_one.pop()
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
TypeError: pop expected at least 1 arguments, got 0
>>> dist_one.pop('001')    #要传递参数键才能删除
'zhangsan'
>>> dist_one
{'002': 'lisi', '003': 'wangwu', '004': 'xioaqian'}
>>> dist_one.popitem()        #随机删除一对键值对
('004', 'xioaqian')
>>> dist_one
{'002': 'lisi', '003': 'wangwu'}
>>> dist_one.clear()    #清空
>>> dist_one
{}

5.5.3 访问字典

>>> dist_one={'001':'zhangsan','002':'lisi','003':'wangwu','004':'xioaqian'}
>>> print(info.items())
dict_items([('001', 'zhangsna'), ('002', 'lisi'), ('003', 'wangwu')])
>>> for i in info.items():
    print(i)
    
('001', 'zhangsna')
('002', 'lisi')
('003', 'wangwu')
>>> print(info.keys())
dict_keys(['001', '002', '003'])
>>> for i in info.keys():
    print(i)
    
001
002
003
>>> print(info.values())
dict_values(['zhangsna', 'lisi', 'wangwu'])
>>> for i in info.values():
    print(i)
    
zhangsna
lisi
wangwu
  • 20
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值