Python 基础实操题

实验介绍

本实验介绍了 Python(Python3)语言的基础,通过本次实验快速掌握 Python 语言中的基本数据类型、Python 编程语言的基本语法、Python 面向对象编程和 Python 的文件操作。

实验目的

通过以下小的实验可以帮助我们掌握 Python 这门编程语言,为以后的数据分析实例实验打下基础。

实验环境

anaconda 2020.7 with jupyter python 3.8.6 Windows10 当前实验在平台上不区分环境,任选一个 kernel 皆可

1 基础概念

1.1 变量

使用指定的名称来绑定特征值

语法:变量名=变量值(等号代表赋值)

a="hello world"
print(a)
hello world

1.2 注释

为了代码的清晰我们可以在代码中加入注释 从#号开始,一直到本行的末尾,都是被注释的内容不会被 Python 解释器解析,即 Python 解释器看到#就不会进行编译。

1.3 输入与输出

输出使用函数 print()

如果输出的是字符串,一定使用引号'' 数字则不需要

在 print 设置 end 会设置 print 默认的结束符号,默认符号是\n

print('hello world') #打印出:hello world
print("hello world") #打印出:hello world。和单双引号输出相同。
hello world
hello world

input 会使得函数停止在 input 这一行,等待输入

语法:input(content) 返回值是字符串

**例如:**我们在运行以下代码之后输入 123,即使我们输入了数字,python 仍然会把它解释成字符串

input()
123
'123'

我们可以在参数中传入提示的文字

input('请输入你的名字:')
请输入你的名字:zz
'zz'

2 数据类型

2.1 数值类型

数值类型包含整型、浮点型、复数类型、布尔类型。各数值类型间可相互转换

print(int()) #默认为0
print(float()) #没有参数,默认为0.0
print(complex()) #没有参数。默认为 0j
print(bool()) #没有参数,默认为False
0
0.0
0j
False

接下来这段代码定义了将一个小数转换为 int 类型,python 会只保留整数部分,而不是四舍五入

int(3.5)
3

2.2 运算符

熟悉 Python 中数值的基本运算。注意,Python 中的“与或非”布尔操作不是使用操作符,而是使用关键词 and/or/not。

print(True+False) # 输出1,True默认为1,False为0
print(True or False) # 输出True,关键字or执行“或”操作
print(5//2) # 输出2,//为取整运算符
print(5%2) # 输出1,%为取余运算符
print(3**2) # 输出9,**表示乘方操作
print(5+1.6) # 输出6.6,不同精度的类型的数字相加默认取高精度类型作为结果
1
True
2
1
9
6.6

2.3 字符串类型

字符串的基本操作

S = 'python' # 给变量S赋值 python
# len(obj): 返回对象的长度
print(len(S)) # 输出6
print(S[0],S[1],S[-1]) # 输出pyn ,按照索引获取元素
print(S+'1',S*2) # 输出python1 pythonpython:合并和重复
6
p y n
python1 pythonpython

字符串的不可变性

S = 'python' # 变量赋值
S1 ='Z'+S[1:] # 生成了新的字符串 zython,并赋值给S1
print("S:%s,S1:%s"%(S,S1)) # 输出S:python,S1:zython
S[0] = 'Z' # 程序异常
S:python,S1:Zython
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-5e643dd4c64b> in <module>
2 S1 ='Z'+S[1:] # 生成了新的字符串 zython,并赋值给S1
3 print("S:%s,S1:%s"%(S,S1)) # 输出S:python,S1:zython
----> 4 S[0] = 'Z' # 程序异常
TypeError: 'str' object does not support item assignment

以下为输出结果,可以发现报错了,体现字符串不可变性。

字符串的常用操作

S = 'python' #变量赋值
#str.split(str='',num=-1): 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔num+1 个子字符串,-1表示分割所有。
print(S.split('h')) # 输出[‘pyt’,’on’],根据h对字符串切割
# str.replace(old, new[, max]):返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
print(S.replace('py','PY')) # Python,将字符串中的py替换为PY
# str.upper():返回小写字符转化为大写后的值。
print(S.upper()) # PYTHON
# str.lower():返回大写字符转化为小写后的值。
print('PYTHON'.lower()) #python,字符串转小写
line='aa,bb,ccc,dd\n' #\n为换行
# str.join(sequence):sequence:要连接的序列,返回指定字符连接序列中元素后生成的新字符串。
print(''.join(['life', 'is' ,'short'])) # 输出life is short,join拼接字符串
hw12='%s %s %d' % ('hello','world',12) # 格式化字符串
print(hw12) # 输出hello world 12
['pyt', 'on']
PYthon
PYTHON
python
lifeisshort
hello world 12

2.4 列表

列表的常用操作

animals = ['cat', 'dog', 'monkey']
# list.append(obj):在列表末尾添加新的对象。
animals.append('fish') # 追加元素
print(animals) # 输出 ['cat', 'dog', 'monkey', ‘fish’]
# list.remove(obj):移除列表中某个值的第一个匹配项。
animals.remove('fish') # 删除元素fish
print(animals) # 输出 ['cat', 'dog', 'monkey']
# list.insert(index, obj):用于将指定对象插入列表的指定位置。index:插入位置
animals.insert(1,'fish') # 在下标1的地方插入元素fish
print(animals) # 输出 ['cat', ‘fish’, 'dog', 'monkey']
# list.pop([index=-1]):要移除列表中对下标对应的元素(默认是最后一个)。Index:下标
animals.pop(1) # 删除下标为1的元素
print(animals) # 输出 ['cat', 'dog', 'monkey']
#遍历并获取元素和对应索引
# enumerate(sequence) :将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
for i in enumerate(animals):
print(i) # 元素下标和元素所组成的索引
"""
输出:(0, cat)
(1, dog)
(2, monkey)
"""
#列表推导式
squares = [x*2 for x in animals]
# 批量生成符合规则的元素组成的列表
print(squares)
#['catcat ', 'dogdog ', 'monkeymonkey ']
list1 = [12,45,32,55]
# list.sort(cmp=None, key=None, reverse=False):cmp为可选参数, 如果指定了该参数,会使用该参数的方法进行排序。key是用来进行比较的元素。reverse为排序规则,False为升序。
list1.sort() # 对列表进行排序
print(list1) # 输出[12,32,45,55]
# list.reverse():反向列表中元素。
list1.reverse() # 对列表进行逆置
print(list1) # 输出[55,45,32,12
['cat', 'dog', 'monkey', 'fish']
['cat', 'dog', 'monkey']
['cat', 'fish', 'dog', 'monkey']
['cat', 'dog', 'monkey']
(0, 'cat')
(1, 'dog')
(2, 'monkey')
['catcat', 'dogdog', 'monkeymonkey']
[12, 32, 45, 55]
[55, 45, 32, 12]

2.5 元组

元组的常用操作

T=(1,2,3) #创建元组
print(T+(4,5)) #元组合并,输出:(1, 2, 3, 4, 5)
t=(42,) #只有一个元素的元组,区别于数字
tuple1 = (12,45,32,55,[1,0,3]) # 创建元祖
tuple1[4][0] = 2 # 元组中可变的元素是可以变得
print(tuple1) # (12,45,32,55,[2,0,3])
tuple1[0] = "good" # 程序异常,元组的不可变性
(1, 2, 3, 4, 5)
(12, 45, 32, 55, [2, 0, 3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-6b94b0c3f1ff> in <module>
5 tuple1[4][0] = 2 # 元组中可变的元素是可以变得
6 print(tuple1) # (12,45,32,55,[2,0,3])
----> 7 tuple1[0] = "good" # 程序异常,元组的不可变性
TypeError: 'tuple' object does not support item assignment

2.6 字典

字典的常用操作

# 字典的三种赋值操作
x = {'food':'Spam','quantity':4,'color':'pink'}
X =dict(food='Spam',quantity=4, color='pink')
x = dict([("food", "Spam"),("b", "2"),("color","pink")])
# dict.copy():拷贝数据
d =x.copy()
d['color'] = 'red'
print(x) #
{'food':'Spam','quantity':4,'color':'pink'}
print(d) # {'food':'Spam','quantity':4,'color':'red'}
#元素访问
print(d.get('name')) # 输出None
print(d.get('name','键值不存在!')) # 输出 键值不存在
print(d.keys()) # 输出dict_keys(['food', 'quantity','color'])
print(d.values()) # 输出dict_values(['Spam', 4, 'pink'])
print(d.items())
# 输出 dict_items([('food', 'Spam'), ('quantity', 4), ('color', 'pink')])
d.clear() # 清空字典中的所有数据
print(d) # 输出 {}
del(d) # 删除字典
print(d) # 程序异常,提示“d”未定义
print(d['name']) # 得到错误信息
{'food': 'Spam', 'b': '2', 'color': 'pink'}
{'food': 'Spam', 'b': '2', 'color': 'red'}
None
键值不存在!
dict_keys(['food', 'b', 'color'])
dict_values(['Spam', '2', 'red'])
dict_items([('food', 'Spam'), ('b', '2'), ('color', 'red')])
{}
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-dad89fb8776a> in <module>
19 print(d) # 输出 {}
20 del(d) # 删除字典
---> 21 print(d) # 程序异常,提示“d”未定义
22 print(d['name']) # 得到错误信息
NameError: name 'd' is not defined

2.7 集合

集合的常用操作

sample_set = {'Prince', 'Techs'}
print('Data' in sample_set) # 输出False,in的作用是检查集合中是否存在某一元素
# set.add(obj):给集合添加元素,如果添加的元素在集合中已存在,则不执行任何操作。
sample_set.add('Data') # 向集合中增加元素Data
print(sample_set) # 输出 {'Prince', 'Techs', 'Data'}
print(len(sample_set)) # 输出3
# set.remove(obj):移除集合中的指定元素。
sample_set.remove('Data') # 删除元素Data
print(sample_set) # {'Prince', 'Techs'}
list2 = [1,3,1,5,3]
print(list(set(list2))) # 输出 [1,3,5],利用集合元素的唯一性进行列表去重
sample_set = frozenset(sample_set)# 不可变集合
False
{'Techs', 'Prince', 'Data'}
3
{'Techs', 'Prince'}
[1, 3, 5]

3 流程控制

3.1 选择判断

接收一个用户输入的分数,然后判断用户所输入的分数属于什么级别。使用 Python 中的 if 语句可以完成 此功能。

#根据输入的分数判断
# input():用于接收输入。
score = input("请输入你的分数") # input函数接收输入,为字符串类型
score = float(score) # 将分数转化为数字类型
# try:… except Exception:… 是Python中用于捕获异常的语句,如果try中的语句出现错误,则会执行except中的语句。
try:
if 100>=score>=90: # 判断输入的值是否大于等级分数
print("优") # 满足条件后输出等级
elif 90 > score >= 80:
print("良")
elif 80>score>60:
print("及格")
else:
print("去补考吧!")
except Exception:
print("请输入正确的分数")
请输入你的分数56
去补考吧!

3.2 循环语句

当满足条件时循环执行语句块,想要结束循环时,使用 break 或 continue 结束循环。

#while循环
i = 0 # 新建i变量
while i<9: # 设置循环条件
i+=1 # 每次循环i增加1
if i == 3: # 判断条件是否满足
print("跳出此次循环")
continue # continue跳出当前的这一次循环
if i == 5:
print("跳出当前大的循环")
break # 跳出当前的大的循环
print(i)
1
2
跳出此次循环
4
跳出当前大的循环
#使用for循环打印包含*元素的菱形
for i in range(10): #定义外层循环(第几行)
for k in range (10-i): #定义内层循环,每一行对应的纵向位置
print(" ",end="") #打印空
for j in range(2*i-1): #打印*, 每一行对应的纵向位置
print('*', end="")
print()
*
***
*****
*******
*********
***********
*************
***************
*****************

4 函数

自定义一个函数,返回一个序列。序列中每个数字都是前两个数字之和(斐波那契数列)。

def fibs(num): # 位置参数
result = [0,1] # 新建列表存储数列的值
for i in range(2,num): # 循环num-2次
a = result[i-1] + result[i-2]
result.append(a) # 将值追加至列表
return result # 返回列表
fibs(5)
[0, 1, 1, 2, 3]
def hello(greeting='hello',name='world'): # 默认参数
print('%s, %s!' % (greeting, name)) # 格式化输出
hello() # hello,world 默认参数
hello('Greetings') # Greetings,world 位置参数
hello('Greetings','universe') # Greetings,universe 位置参数
hello(name='Gumby') # hello,Gumby 关键字参数
hello, world!
Greetings, world!
Greetings, universe!
hello, Gumby!

5 时间模块

import time
# time.time():用于获取当前时间戳
time_now = time.time()
print("时间戳:",time_now)
# time.localtime():获取时间元组
localtime = time.localtime(time_now)
print("本地时间为 :", localtime)
# time.asctime():获取格式化的时间
localtime = time.asctime(localtime)
print("本地时间为 :", localtime)
#time.strftime(format[, t]):接收时间元组,并返回以可读字符串表示的当地时间,格式由参数format决定。
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
时间戳: 1611921263.3955252
本地时间为 : time.struct_time(tm_year=2021, tm_mon=1, tm_mday=29, tm_hour=19, tm_min=54, tm_sec=23, tm_wday=4, tm_yday=29, tm_isdst=0)
本地时间为 : Fri Jan 29 19:54:23 2021
2021-01-29 19:54:23