实验介绍
本实验介绍了 Python(Python3)语言的基础,通过本次实验快速掌握 Python 语言中的基本数据类型、Python 编程语言的基本语法、Python 面向对象编程和 Python 的文件操作。
实验目的
通过以下小的实验可以帮助我们掌握 Python 这门编程语言,为以后的数据分析实例实验打下基础。
实验环境
anaconda 2020.7 with jupyter python 3.8.6 Windows10 当前实验在平台上不区分环境,任选一个 kernel 皆可
使用指定的名称来绑定特征值
语法:变量名=变量值(等号代表赋值)
a="hello world"print(a)
hello world
为了代码的清晰我们可以在代码中加入注释 从#号开始,一直到本行的末尾,都是被注释的内容不会被 Python 解释器解析,即 Python 解释器看到#就不会进行编译。
输出使用函数 print()
如果输出的是字符串,一定使用引号'' 数字则不需要
在 print 设置 end 会设置 print 默认的结束符号,默认符号是\n
print('hello world') #打印出:hello worldprint("hello world") #打印出:hello world。和单双引号输出相同。
hello worldhello world
input 会使得函数停止在 input 这一行,等待输入
语法:input(content) 返回值是字符串
**例如:**我们在运行以下代码之后输入 123,即使我们输入了数字,python 仍然会把它解释成字符串
input()
123'123'
我们可以在参数中传入提示的文字
input('请输入你的名字:')
请输入你的名字:zz'zz'
数值类型包含整型、浮点型、复数类型、布尔类型。各数值类型间可相互转换
print(int()) #默认为0print(float()) #没有参数,默认为0.0print(complex()) #没有参数。默认为 0jprint(bool()) #没有参数,默认为False
00.00jFalse
接下来这段代码定义了将一个小数转换为 int 类型,python 会只保留整数部分,而不是四舍五入
int(3.5)
3
熟悉 Python 中数值的基本运算。注意,Python 中的“与或非”布尔操作不是使用操作符,而是使用关键词 and/or/not。
print(True+False) # 输出1,True默认为1,False为0print(True or False) # 输出True,关键字or执行“或”操作print(5//2) # 输出2,//为取整运算符print(5%2) # 输出1,%为取余运算符print(3**2) # 输出9,**表示乘方操作print(5+1.6) # 输出6.6,不同精度的类型的数字相加默认取高精度类型作为结果
1True2196.6
字符串的基本操作
S = 'python' # 给变量S赋值 python# len(obj): 返回对象的长度print(len(S)) # 输出6print(S[0],S[1],S[-1]) # 输出pyn ,按照索引获取元素print(S+'1',S*2) # 输出python1 pythonpython:合并和重复
6p y npython1 pythonpython
字符串的不可变性
S = 'python' # 变量赋值S1 ='Z'+S[1:] # 生成了新的字符串 zython,并赋值给S1print("S:%s,S1:%s"%(S,S1)) # 输出S:python,S1:zythonS[0] = 'Z' # 程序异常
S:python,S1:Zython---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-7-5e643dd4c64b> in <module>2 S1 ='Z'+S[1:] # 生成了新的字符串 zython,并赋值给S13 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']PYthonPYTHONpythonlifeisshorthello world 12
列表的常用操作
animals = ['cat', 'dog', 'monkey']# list.append(obj):在列表末尾添加新的对象。animals.append('fish') # 追加元素print(animals) # 输出 ['cat', 'dog', 'monkey', ‘fish’]# list.remove(obj):移除列表中某个值的第一个匹配项。animals.remove('fish') # 删除元素fishprint(animals) # 输出 ['cat', 'dog', 'monkey']# list.insert(index, obj):用于将指定对象插入列表的指定位置。index:插入位置animals.insert(1,'fish') # 在下标1的地方插入元素fishprint(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]
元组的常用操作
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
字典的常用操作
# 字典的三种赋值操作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')) # 输出Noneprint(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
集合的常用操作
sample_set = {'Prince', 'Techs'}print('Data' in sample_set) # 输出False,in的作用是检查集合中是否存在某一元素# set.add(obj):给集合添加元素,如果添加的元素在集合中已存在,则不执行任何操作。sample_set.add('Data') # 向集合中增加元素Dataprint(sample_set) # 输出 {'Prince', 'Techs', 'Data'}print(len(sample_set)) # 输出3# set.remove(obj):移除集合中的指定元素。sample_set.remove('Data') # 删除元素Dataprint(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]
接收一个用户输入的分数,然后判断用户所输入的分数属于什么级别。使用 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去补考吧!
当满足条件时循环执行语句块,想要结束循环时,使用 break 或 continue 结束循环。
#while循环i = 0 # 新建i变量while i<9: # 设置循环条件i+=1 # 每次循环i增加1if i == 3: # 判断条件是否满足print("跳出此次循环")continue # continue跳出当前的这一次循环if i == 5:print("跳出当前大的循环")break # 跳出当前的大的循环print(i)
12跳出此次循环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()
*********************************************************************************
自定义一个函数,返回一个序列。序列中每个数字都是前两个数字之和(斐波那契数列)。
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!
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 20212021-01-29 19:54:23