培训第二十四天(python基础学习)

上午

python开发工具:

1、安装自带的ide

2、pycharm(付费)

3、anaconda

1、环境 python2内置,需要换为python3

复制代码
 [root@3 ~]# pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ some-package  //切换国内下载
 [root@3 ~]# yum list installed | grep python
 [root@3 ~]# yum list installed | grep epel
 [root@3 ~]# yum list | grep python3
 [root@3 ~]# yum -y install python3.x86_64
 [root@3 ~]# python3 --version
 Python 3.6.8
 #最新版3.12版可以使用源码安装
 [root@3 ~]# python3     #进入到python的编辑状态
 Python 3.6.8 (default, Nov 14 2023, 16:29:52) 
 [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
 Type "help", "copyright", "credits" or "license" for more information.
 >>> print("hello world")
 hello world
 #如果直接输入python,会直接进入到python2中

2、变量和数据类型

1、三大类数据类型

字符 字符串str

数值 整数int,浮点float

逻辑 True False(注意首字母大写)

复制代码
 >>> print(1==1)
 True
 >>> print(1!=1)
 False
 >>> b='zhangsan'
 >>> type(b)
 <type 'str'>
 >>> c=3
 >>> type(c)
 <type 'int'>
 >>> d=3.14
 >>> type(d)
 <type 'float'>

3、数据集合

计算是在python内存中计算的,必须要有指定内存空间保存数据

这些内存空间其实就是变量(a,b,c)

我们使用数据集合批量管理内存空间

\]列表,{}字典,()元组 ##### (1)列表 在python中列表是使用最为广泛的一个数据集合工具 是java中数组和list的综合体 当有多个数据需要管理,可以定义一个列表(管理列表) ```  # python为开发提供了丰富的使用手册  help(lista) #通过上下方向,enter,space键来翻阅信息,使用q退出查看 more less  # 创建列表  lista=[]  listc=[1,2,3]  # 修改列表  # 追加元素  lista.append(item) #在所有元素之后添加元素  # 插入元素  listb.insert(pos,item) #在pos序号之前插入item  # 删除元素 remove 和 pop  list.pop() #删除list中的最后一个元素  list.remove(list[index]) #删除序号为index的元素  # 修改元素  list[index]=newvalue  # 删除列表  del list ``` 练习: ```  >>> listb=["tom","jerry"]  >>> listb  ['tom', 'jerry']  >>> listb.append("tomcat")  >>> listb  ['tom', 'jerry', 'tomcat']  >>> listc=["tom","jerry"]  >>> listc.pop()  'jerry'  >>> listc  ['tom']  >>> listd=listb.pop()  >>> listd  'tom'  >>> liste=listb.pop()  Traceback (most recent call last):    File "", line 1, in  IndexError: pop from empty list  >>> listb  []  # 当在列表中删除或者修改一个元素的时候,列表会返回新的列表  >>> listb.append('lisi')  >>> listb.append('zhangsan')  >>> listb.append('wangwu')  >>> listb  ['lisi', 'zhangsan', 'wangwu']  >>> listb[0]  'lisi'  >>> listb[1]  'zhangsan'  >>> listb[2]  'wangwu'  >>> listb.remove(listb[1])  >>> listb  ['lisi', 'wangwu'] ``` ##### (2)字典 dict dictionary key-value 键值对 {"name":"张三","age":"19","gender":"male","height":"145","weight":"180"} 健:值 如下: ```  {     "from":"me",     "to":"you",     "message":"你吃饭了吗?",     "time":"2024-7-8 9:00:32",     "user":{        "username":"abc",        "password":"abc"     }  } ``` ```  # 创建字典  dict0={      健:值,      健:值  }  # 追加元素  dict0["健"]="值"  # 删除元素  dict0.pop("健")  # 修改元素  dict0["存在的健"]="修改后的值" ``` 练习: ```  >>> dict0={  ... "id":1,  ... "username":"abc",  ... "password":"123"  ... }  >>> help(dict0)  >>> dict0  {'id': 1, 'username': 'abc', 'password': '123'}  >>> dict0["realname"]="zhangsan"  >>> dict0  {'id': 1, 'username': 'abc', 'password': '123', 'realname': 'zhangsan'}  >>> dict0.pop("id")  1  >>> dict0  {'username': 'abc', 'password': '123', 'realname': 'zhangsan'}  >>> dict0["password"]="123456"  >>> dict0  {'username': 'abc', 'password': '123456', 'realname': 'zhangsan'}  ​  # list列表与dict字典嵌套  >>> a=[1,2,3]  >>> b={"username":"abc","password":"abc"}  >>> a  [1, 2, 3]  >>> b  {'username': 'abc', 'password': 'abc'}  >>> a.append(b)  >>> b["a"]=a  >>> a  [1, 2, 3, {'username': 'abc', 'password': 'abc', 'a': [...]}]  >>> b  {'username': 'abc', 'password': 'abc', 'a': [1, 2, 3, {...}]} ``` ##### (3)元组 不能修改,只可以查看 tuple\[index\],list(tuple),tuple(list) list()可以把dict的key生成一个列表 list()可以把tupl变成列表 tupl可以把dict和list变成元组 | 功能 | 指令 | 说明 | |-------|-----------------------------------|---------------------------------------------| | 创建列表 | \[\] | 符号本身就是列表 | | | list(元组) | 将元组转成列表 | | | list(字典) | 提取字典的key转成列表 | | | 字典.keys() | 字典中的key返回一个列表 | | | 字典.values() | 字典中的value组成的列表 | | | 字典.items() | 字典中的每个k-v组成元组,这些元组组成一个新的列表 | | 修改列表 | l.inster(index,value) | 在索引值为index的元素之前插入一个元素 | | | l.append(value) | 在所有元素之后添加一个元素 | | | l\[index\]=value | 将索引为index元素的值修改为value | | | l.pop() | 删除最后一个元素 | | | del l | 释放l内存 | | 查看列表 | l | 显示列表中的所有数据 | | | l\[index\] | 返回索引值为index的元素 | | 字典的创建 | {} | 代表一个空字典 | | | {k0:v0,k2:v2.....} | 这是有初始值的字典 | | | dict(\[(k0,v0),(k1,v0),(k2,v2)\]) | \[\]中的每一个()中都有2个值,一个是key,一个是value自动解析为一个字典了 | | 元组 | (),(1,2,3,4) | 创建空元组,创建有初始值的元组 | | | 也可以从dict中提取,也可以将列表直接转换成元组 | | 登录信息返回的键值对: ```  {      "method":"post",      "username":"abc",      "password":"123",      "params":[1,2,3],      "cntroller":"login"  } ``` #### 4、选择语句和循环语句 ##### (1)if选择语句 缩进是必须的 (一个tab健或者四个空格) ```  if condition0:      statement0      if condition1:          block1      else:          block2  else:      statement1 ``` 多分支if语句 ```  if condition0:   block0  elif condition1:   block1  elif condition2:   block2  ...  else:   blockn ``` 练习: ```  [root@3 ~]# vim py001.py  if True:   print("i'm true")  else:   print("i'm false")  [root@3 ~]# python3 py001.py  i'm true  >>> n=58  >>> if n>90:  ...     print("优秀")  ... elif n>80:  ...     print("良好")  ... elif n>70:  ...     print("中等")  ... elif n>60:  ...     print("及格")  ... else:  ...     print("不及格")  ...  不及格  [root@3 ~]# vim py002.py  import random  n=random.randint(0,100)  print("随机分数为:",n)  if n>90:          print("优秀")  elif n>80:          print("良好")  elif n>70:          print("中等")  elif n>60:          print("及格")  else:          print("不及格")  [root@3 ~]# python3 py002.py  随机分数为: 68  及格  [root@3 ~]# vim py003.py  import random  n=random.randint(50,100)  print("随机数值为:",n)  if n>90:          print("youxiu")  else:          if n>80:                  print("lianghao")          else:                  if n>70:                          print("zhongdeng")                  else:                          if n>60:                                  print("jige")                          else:                                  print("bujige")  ​  [root@3 ~]# python3 py003.py  随机数值为: 93  youxiu ``` ##### (2)swith插槽 ##### (3)input与print ```  >>> print("请输入您的选择")  请输入您的选择  >>> print("1、创建master,2、创建slave")  1、创建master,2、创建slave  >>> input("---:")  ---:1  '1'  >>> input("---:")  ---:2  '2' ``` ##### (3)for循环语句 练习: ```  >>> list=[1,2,3,4,5]  >>> for var in list:   #列表遍历  ...     print(var)  ...  1  2  3  4  5  >>> for var in ["a","b","c"]:   #列表遍历  ...     print(var)  ...  a  b  c  >>> d={"a":1,"b":2,"c":3}    #字典遍历key  >>> for var in d:  ...     print(var)  ...  a  b  c  >>> for var in d:     #字典遍历value  ...     print(d[var])  ...  1  2  3  >>> tupl0=("a","b","c")  #遍历元组  >>> for var in tupl0:  ...     print(var)  ...  a  b  c  >>> range(9)  range(0, 9)  >>> list(range(9))  [0, 1, 2, 3, 4, 5, 6, 7, 8]  >>> for i in range(9):  ...     print(i)  ...  0  1  2  3  4  5  6  7  8  >>> for i in range(101):  ...     n=n+i  ...  >>> n  5050  [root@3 ~]# vim py004.py  n=0  for i in range(101):          n=n+i  print(n)  [root@3 ~]# python3 py004.py  5050 ``` ##### (4)while循环语句(continue与break) break和continue也可以应⽤于for ```  while condition:   blocak      #continue,break; ``` 练习: ```  >>> i=0  >>> while i<10:  ...     i+=1  ...     if i%2!=0:  ...             continue  ...     print(i)  ...  2  4  6  8  10  >>> c=0  >>> while True:  ...     print(c)  ...     c+=1  ...     if c==5:  ...             break  ...  0  1  2  3  4 ``` #### 5、常用的工具api ```  # 指令  vim 001.py  # 执⾏py脚本  python3 001.py  # 调试py脚本  python3 -m pdb 001.py  # 输⼊n按回⻋执⾏下⼀⾏代码  # 输⼊q退出调试  # 生成随机数  import random  n=random.randint(0,10)  #创建目录  import os  os.mkdir("/opt/aaa") ``` 练习: ```  [root@3 ~]# python3 -m pdb py003.py  > /root/py003.py(1)()  -> import random  (Pdb) n  > /root/py003.py(2)()  -> n=random.randint(50,100)  (Pdb) n  > /root/py003.py(3)()  -> print("随机数值为:",n)  (Pdb) n  随机数值为: 92  ......  (Pdb) q  >>> import random  >>> n=random.randint(0,10)  >>> n  10  >>> n=random.randint(0,10)  >>> n  4  >>> import os  >>> os.mkdir("/opt/aaa")  >>> quit()  [root@3 ~]# ls /opt  aaa ```

相关推荐
.R^O^18 分钟前
计算机知识
linux·服务器·网络·安全
啥都鼓捣的小yao28 分钟前
实战5:Python使用循环神经网络生成诗歌
开发语言·人工智能·python·rnn·深度学习
站大爷IP31 分钟前
Python中的“空”:对象的判断与比较
python
全栈派森40 分钟前
Web认证宇宙漫游指南
python·node.js
用户40937927136841 分钟前
函数
python
卡戎-caryon42 分钟前
【Linux网络与网络编程】11.数据链路层mac帧协议&&ARP协议
linux·服务器·网络·笔记·tcp/ip·数据链路层
夜月yeyue1 小时前
STM32启动流程详解
linux·c++·stm32·单片机·嵌入式硬件·c#
烛.照1031 小时前
RabbitMQ消息的可靠性
linux·docker·rabbitmq
SHIPKING3931 小时前
【LangChain核心组件】Memory:让大语言模型拥有持续对话记忆的工程实践
数据库·python·langchain·llm·memory
noravinsc1 小时前
windows上rabbitmq服务激活后 15672无法打开
windows·分布式·rabbitmq