python数据类型及逻辑控制语句

发布于 2023-08-10  2145 次阅读


1.python介绍

1.特性解释性、需要编译在运行、有丰富的库、模块

2.版本

  1. python3
  2. python2

3.应用领域

  1. 自动化运维 脚本
  2. 爬虫

2.python环境安装部署

安装解释器

安装集成工具

3.输出语句

print("hello world")
hello world
print('hello python')
hello python
print("""linux
windows
test
macos""")
输出4行代码

变量
username = "test"
print(username)
print("hello",username)

格式化输出
%s 字符串占位符
%d 整数
%f 浮点数
%% %本身

username = "test"
age = 30
print("hello %s" % username)
print("My name is %s,my age is %s" % (username,age))

print("The number is %d" % 20)
print("The number is %d" % 3.14) 会把小数点后的去掉取整

print("The number is %f" % 10)
print("The number is %f" % 3.14) 会保留6位小数
print("The number is %.3f" % 3.1415926) 四舍五入保留三位小数

number = 50
print("The number is %d%%" % number)

4.变量定义及调用

1.变量定义

变量名称 = 变量值

规范:

  1. 只能大小写字母、数字、下划线
  2. 只能以字母、下划线开头 不能数字开头
  3. 见名知意
  4. 不能和python关键子冲突、os

2.调用变量

直接通过变量名调用变量值

username = "1"

print("username")

变量特性:

弱类型 不需要指定变量类型 整数型、、

number_01 = 100
number_02 = 100

print(id(number_01))
print(id(number_02)) 两个结果相同 因为100在内存中已经开辟 只是两个标识而已 实际指向的内存编码地址是同一个

a = 10
b = 20
a,b =b,a
print(a) 20
print(b) 10

3.交互式定义变量

name = input("请输入IP地址:")
print("IP is %s" % name)name = input("请输入用户名:")

请输入IP地址:1.1.1.1
IP is 1.1.1.1

input里数据类型都是str字符串 不当作数字

data = input("数据>>> ")
print(data)
print(type(data))

数据>>> 100
100
<class 'str'>

5.数据类型 运算符

数字、字符串、列表、元组、字典、集合、bytes

1.数字

  1. 整数
  2. 浮点数
  3. 复数
num_01 = 100
print(type(num_01))
num_02 = 3.14
print(type(num_02))
num_03 = 10 +10j
print(type(num_03))

<class 'int'>
<class 'float'>
<class 'complex'>

print(10+20)
print(10/4)
print(10//4) 去掉小数部分
print(2 ** 3) 2的三次方

30
2.5
2
8

num = 1
# num = num + 1 写法意思代表相同
num += 2
print(num)

3

score = 11
print(score > 10 and score < 20 )
print(score > 20 or score < 20 )
print(score > 20 or score < 5 )

True
True
False

1.数学运算模块

import math
print(math.sqrt(9))
print(math.log10(100))

3.0
2.0

2.生成随机数

import random
print(random.random())
print(random.randint(90,100))

0.46980542903454403
92

2.字符串

常规操作符

原始字符串 避免转义 原始意思 \n   r raw
file_name = r"d:\newdir\log.jpg"
print(file_name)
str1 = "python"
str2 = "linux"
print(str1 + str2)
print(str1 * 3)

len获取字符串长度 也能获取列表的列数
print(len("python"))
print(len(str1 * 3))

判断成员关系
print("py" in "python")
print("py" not in "python")

索引
字符串的下标 默认从0开始
str3 = "python"
print(str3[2])
print(str3[-1])

切片
str3 = "python"
print(str3[2])
print(str3[-1])

print(str3[0:3])
print(str3[1:4])
print(str3[1:])
print(str3[-2:])
print(str3[1:4:2])
print(str3[1:6:2])
print(str3[::-1])

pythonlinux
pythonpythonpython
6
18
True
False
t
n
pyt
yth
ython
on
yh
yhn
nohtyp

Process finished with exit code 0

通过切片+ 改变字符串信息

data = "python"
new_data = data[0:2] + "K" + data[3:]
print(new_data)

字符串对象的操作方法

一切皆对象

dir()内置函数查看操作方法

print(dir(str))

print(dir(int))

data = "python"
print(data.capitalize())    首字母大写
print(data.upper())         全部大写
print(data.lower())         全部小写

print("abc".isalpha())        全是字母
print("abc1".isalpha())       全是字母
print("123".isdigit())        全是数字
print("avc123".isalnum()) 数字+字母
print("AVC".isupper())        全是大写
print("avc".islower())        全是小写

Python
PYTHON
python
True
False
True
True
True
True

Process finished with exit code 0
print("python".startswith("py"))    开头
print("python".endswith("on"))      结尾

print("ApythonA".strip("A"))        去掉两边A
print("ApythonA".lstrip("A"))       去掉左边A
print("ApythonA".rstrip("A"))       去掉右边A

print("    python    ".strip())       去掉两边空格
print("    python    ".lstrip())  去掉左空格
print("    python    ".rstrip())  去掉有空格

True
True
python
pythonA
Apython
python
python    
    python

Process finished with exit code 0
split()
默认以空白字符为分隔符 类似awk
data = "python Golang    Shell"
print(data.split())
print(data.split()[1])

ipaddr = "192.168.1.1"
print(ipaddr.split(".")[1])

['python', 'Golang', 'Shell']
Golang
168

splitlines()
默认以换行符为分隔符
data = """"test1
test2
test3
test4"""
data1 = "test1 test2 test3"

print(data.splitlines())
print(data1.splitlines())

['"test1', 'test2', 'test3', 'test4']
['test1 test2 test3']

count()   计数 出现多少次
replace() 替换
data = "oo11oo hello"
print(data.count("o"))

print(data.replace("o","r"))

5
rr11rr hellr

dir = input("请输入目录:")
if dir.endswith("/"):
    print(dir)
else:
    dir = dir + "/"
    print(dir)
判断数据目录后有没有加/ 没有的话加上 有的话输出

3.列表

常规操作符

listA = ["nginx","httpd","apache"]
print(type(listA))

listB = ["3","3.14",["redis","mq"],"nginx","httpd","apache"]
print(listB)

listC = [i for i in range(1,11)]
print(listC)

listD = [i ** 2 for i in range(1,11)]
print(listD)

iplist = ["192.168.1.%s" % i for i in range(1,11)]
print(iplist)
print(len(iplist)) #获取列表元素的个数

<class 'list'>
['3', '3.14', ['redis', 'mq'], 'nginx', 'httpd', 'apache']
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4', '192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8', '192.168.1.9', '192.168.1.10']
10

Process finished with exit code 0

#列表成员关系判断
listB = ["3","3.14",["redis","mq"],"nginx","httpd","apache"]
print("apache" in listB)
print("test" not in listB)
print(["redis","mq"] in listB)
print("redis" in listB)

True
True
True
False

Process finished with exit code 0

#列表索引  可变的数据类型 之前的变量不可修改
listB = ["3","3.14",["redis","mq"],"nginx","httpd","apache"]

listB[1] = "IIS"

print(listB[1])
print(listB[-4][0])

IIS
redis

Process finished with exit code 0
#列表切片
print(listB[0:2])

列表对象的操作方法

1.添加数据

listA = ["nginx","IIS","apache"]
listA.append("tomcat") #列表后边追加数据
print(listA)

listA.insert(1,"test")    #列表索引下标追加数据
print(listA)

['nginx', 'IIS', 'apache', 'tomcat']
['nginx', 'test', 'IIS', 'apache', 'tomcat']

Process finished with exit code 0

2.删除数据

listA = ["nginx","IIS","apache"]
listA.pop()
print(listA)

listA.remove("nginx")
print(listA)

['nginx', 'IIS']
['IIS']

Process finished with exit code 0

通过for循环遍历列表

listA = [["test","nginx"],["pop","IIS"],["http","apache"]]
for i,j in listA:
    print("内部列表第一个值为%s,内部列表第二个值为%s" % (i,j))

内部列表第一个值为test,内部列表第二个值为nginx
内部列表第一个值为pop,内部列表第二个值为IIS
内部列表第一个值为http,内部列表第二个值为apache

案例

根据提示输入数字,实现列表的添加、删除(获取)最后信息

import sys
data = []

menu = """"
1.添加数据
2.获取数据
3.查看数据
4.退出

选择>>>
"""

while True:
    cho = input(menu)

    if cho == "1":
        data.append(input("请输入添加的数据>>> "))
    elif cho == "2":
        print("获取列表最后一个数据%s" % data.pop())
    elif cho == "3":
        print("列表中所有数据:")
        print(data)
    elif cho == "4":
        sys.exit()

4.元组

常规操作符

tupleA = ("nginx","httpd","IIS")
print(type(tupleA))

tupleB = ("2","redis",["nginx","apache"],("tengine","mq","mysql"))
print(tupleB)

tupleC = ("test")
print(type(tupleC))
tupleD = ("test",)            #定义单个元组必须加,
print(type(tupleD))

<class 'tuple'>
('2', 'redis', ['nginx', 'apache'], ('tengine', 'mq', 'mysql'))
<class 'str'>
<class 'tuple'>

Process finished with exit code 0

#列表可变 索引下标 等号 可改变
#元组不可变

# tupleE = ("2","redis",["nginx","apache"],("tengine","mq","mysql"))
# tupleE[1] = "test"
# print(tupleE)             #元组执行错误 不可变
                            #列表可变
listE = ["nginx","apache"]
listE[1] = "test"
print(listE)

['nginx', 'test']

Process finished with exit code 0

遗留问题:for循环遍历占位符%s 报错最后一组元组 str list都能通过%s 占位遍历出来

tupleE = ("2","redis",["nginx","apache"],("test","bob"))
#print(tupleE[-3:-1])

#print(type(tupleE[-3]))

for i in tupleE:
    print("输出元组数据%s" % i)

E:\projecttest\venv\Scripts\python.exe E:\projecttest\yuanzuDemo.py 
输出元组数据2
输出元组数据redis
输出元组数据['nginx', 'apache']
Traceback (most recent call last):
  File "E:\projecttest\yuanzuDemo.py", line 27, in <module>
    print("输出元组数据%s" % i)
          ~~~~~~~~~~~^~~
TypeError: not all arguments converted during string formatting

Process finished with exit code 1

5.字典

  • 与list相似 数据可变

被定义在一对大括号{}中的数据

dictA = {"name":"bob","passwd":"123"}
print(type(dictA))

dictB = {
    "192.16.1.1" : {
        "user": "root",
        "passwd":"123",
        "port":"22"
    }
}
print(type(dictB))

<class 'dict'>
<class 'dict'>

Process finished with exit code 0

常规操作符

1.获取数据

dictA = {"name":"tom","age":"12"}

print(dictA.get("name"))              #推荐get 不会报错 没有这个键的输出 None
print(dictA.get("user"))
print(dictA["name"])
print(dictA["user"])

tom
None
tom
Traceback (most recent call last):
  File "E:\projecttest\dict.py", line 18, in <module>
    print(dictA["user"])
          ~~~~~^^^^^^^^
KeyError: 'user'

Process finished with exit code 1

2.添加数据

dictA = {"name":"tom","age":"12"}

#不存在这个建就是添加数据
dictA["user"] = "admin"
print(dictA)
#存在的话就是修改数据
dictA["name"] = "bob"
print(dictA)

{'name': 'tom', 'age': '12', 'user': 'admin'}
{'name': 'bob', 'age': '12', 'user': 'admin'}

Process finished with exit code 0

3.删除数据

dictA = {"name":"tom","age":"12"}
del dictA["user"]
print(dictA)

{'name': 'tom', 'age': '12'}

字典对象的操作方法

dictA = {"name":"tom","age":"12"}

print(dictA.keys())     #列表形式返回字典中所有的建
print(dictA.values())   #列表形式返回字典中所有的值
print(dictA.items())    #列表形式返回多个键值对的元组

dict_keys(['name', 'age'])
dict_values(['tom', '12'])
dict_items([('name', 'tom'), ('age', '12')])

Process finished with exit code 0

for 循环遍历

dictA = {"name":"tom","age":"12","class":"5"}

for i in dictA:
    print("键:%s & 值:%s" % (i,dictA.get(i)))

print(dictA.items())

for i,j in dictA.items(): #items以列表形式输出多组列表值 列表中是元组 通过for循环遍历多个值
    print(i,j)

键:name & 值:tom
键:age & 值:12
键:class & 值:5
dict_items([('name', 'tom'), ('age', '12'), ('class', '5')])
name tom
age 12
class 5

Process finished with exit code 0

案例

统计ip地址出现的次数

#首先确认
判断值是否在列表、字典中 
in not in在字典中只能判断键是否存在 不能判断值是否存在
list = ["10.1.1.11","10.1.1.1","10.1.1.11","10.1.1.1","10.1.1.11","10.1.1.12","10.1.1.1","10.1.1.1","10.1.1.1"]
end = {}
for i in list:
    if i not in end.keys():     #所以判断ip键是否存在可以判断 字典的keys键方法/直接判断字典本身
        end[i] = 1
    else:
        end[i] += 1
for i,j in end.items():
    print("出现的ip地址为:%s,出现的次数是%s" % (i,j))

出现的ip地址为:10.1.1.11,出现的次数是3
出现的ip地址为:10.1.1.1,出现的次数是5
出现的ip地址为:10.1.1.12,出现的次数是1

案例:输入用户名密码存字典 实现用户注册、登录

import sys
menu = """
1.用户注册
2.用户登录
3.退出

请输入:>>>
"""
user_info = {}

while True:
    cho = input(menu)
    if cho == "1":
        username = input("请输入用户名:")
        while True:
            if username in user_info.keys():
                print("用户名%s已存在,请重新输入" % username)
            else:
                break
        while True:
            passwd = input("请输入密码:")
            passwdagin = input("再次输入密码:")
            if passwd != passwdagin:
                print("两次输入的密码不相同,请重新输入")
            else:
                break
        user_info[username] = passwd
        print("用户%s注册成功,密码为%s" % (username,passwd))

    if cho == "2":
        checkuser = input("请输入用户名称:")
        if checkuser in user_info.keys():
            checkpasswd = input("请输入此用户的密码:")
            if checkpasswd == user_info[checkuser]:
                print("用户%s,登录成功!" % checkuser)
            else:
                print("您输入该用户的密码不正确")
        else:
            print("您输入的用户名不存在,请先注册在登陆")

    if cho == "3":
        sys.exit()

1.用户注册
2.用户登录
3.退出

请输入:>>>
1
请输入用户名:tom
请输入密码:123
再次输入密码:123
用户tom注册成功,密码为123

1.用户注册
2.用户登录
3.退出

请输入:>>>
2
请输入用户名称:tom
请输入此用户的密码:123
用户tom,登录成功!

6.集合

定义:set fronzenset定义的去重后的结果

data = "aaacccdddwdwdwwwde"
print(set(data))

{'c', 'd', 'a', 'w', 'e'}

类型:

可变集合 set()

不可变集合 fronzenset()

作用:实现数据的去重

for 循环遍历

set_a = set("hello")
print(set_a)
print(type(set_a))

set_b = frozenset("hello")
print(set_b)
print(type(set_b))

data = ["tom","nginx","nginx","apache","http"]
set_c = set(data)
print(set_c)

for i in set_b:
    print(i)

{'e', 'h', 'l', 'o'}
<class 'set'>
frozenset({'e', 'h', 'l', 'o'})
<class 'frozenset'>
{'nginx', 'apache', 'http', 'tom'}

e
l
o
h

Process finished with exit code 0

案例

统计一个字符串中出现字符的次数

data = "aaacccdddwdwdwwwde"

print(data.count("a"))
print(data.count("w"))

for i in set(data):
    print("字符%s,出现的次数为%s" % (i,data.count(i)))

7.bytes python3才有

定义:一串字节的集合

data = b"python"
print(type(data))
print(data)

<class 'bytes'>
b'python

字符串 bytes数据转换

字符串 ---> Bytes

1.encode()

data1 = "python"
newdata = data1.encode("utf-8")

print(newdata)
print(type(newdata))

data2 = "我爱你"
newdata2 = data2.encode("utf-8")

print(newdata2)
print(type(newdata2))

b'python'
<class 'bytes'>
b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0'
<class 'bytes'>

Process finished with exit code 0

2.bytes()

data2 = "我爱你"

newdata = bytes(data2,encoding="utf-8")
print(newdata)
print(type(newdata))

b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0'
<class 'bytes'>

Process finished with exit code 0
bytes ---> 字符串

1.decode() 解码

2.str()

data = b"test"
print(data)
print(type(data))

newdata = data.decode()
print(newdata)
print(type(newdata))

newdata1 = str(data)
print(newdata1)
print(type(newdata1))

b'test'
<class 'bytes'>
test
<class 'str'>
b'test'
<class 'str'>

Process finished with exit code 0

8.数据类型总结

可变数据类型:

列表、字典、可变集合

不可变数据类型

数字、字符串、元组、不可变集合

可迭代数据

通过某个类似下标方式获取某一部分的数据

​ 字符串 列表 元组 字典 bytes 集合

不可迭代数据

​ 数字

6.逻辑控制语句结构

1.条件判断 if

2.循环

1.条件判断 if

为真执行操作

为假不执行

num = 10
if num > 8:
    print("A")
    print("B")

A
B

num = 5
if num > 8:
    print("A")
else:
    print("B")

B

score = int(input("成绩>>> "))
print(type(score))

if score >= 60 and score < 70:
    print("及格")
elif score >= 70 and score < 80:
    print("中")
elif score >=80 and score < 90:
    print("良")
elif score >=90 and score <= 100:
    print("优")
else:
    print("差")

2.循环

for

while

1.for循环

语法:

for 变量 in 取值列表:

​ 执行的操作

​ 执行的操作

range(5) 0 1 2 3 4
range(1,5) 1 2 3 4

for i in range(1,5):
    print("第%s次循环开始" % i)
    print("-------")
    print("第%s次循环结束" % i)

第1次循环开始
-------
第1次循环结束
第2次循环开始
-------
第2次循环结束
第3次循环开始
-------
第3次循环结束
第4次循环开始
-------
第4次循环结束
中断循环的执行

continue 中断本次循环 立刻开始下一次循环

break 中断所有循环

for i in range(1,5):
    print("第%s次循环开始" % i)
    if i == 2:
        continue
    print("-------")
    print("第%s次循环结束" % i)

for i in range(1,5):
    print("第%s次循环开始" % i)
    if i == 2:
        break
    print("-------")
    print("第%s次循环结束" % i)

2.while循环

语法:

while 条件:

​ 执行的操作

​ 执行的操作

# i = 1
# while i <= 3:
#     print("while循环测试")
#     i += 1

i = 1
import time
while True:
    print("循环测试")
    i += 1
    if i == 4:
        break
    time.sleep(0.5)

执行后延时0.5s再次循环   

循环测试 i为2
循环测试  3
循环测试  4

案例脚本

1.生成10位随机字符 包含字母 数字 特殊符号

import random
import string

all = string.ascii_letters + string.digits + string.punctuation

data = ""
for i in range(10):
    data = random.choice(all) + data
print(data)

@aKY7eZH1B

2.统计

data = """Generating realistic location data for users for testing 
or modeling simulations is a hard problem. Current approaches just create 
random locations inside a box, placing 
users in waterways or on top of buildings. This inability to make accurate, synthetic location data stifles a lot of
innovative projects that require 
diverse and complex datasets to fuel their work."""
#统计行数
print(data.splitlines())
print(len(data.splitlines()))
#统计单词数
print(len(data.split()))

3.判断用户输入是否是合法的python标识符

import  string
import sys   #导入退出脚本模块
data = input("请输入python变量字符串>>> ").strip()
#print(len(data))

no1 = "_" + string.ascii_letters
no2 = "_" + string.ascii_letters + string.digits
#print(no1)
var = data[0]
#abcd 1,4       1 2 3
flag = 0
#判断首字符是否合法
if var  in no1:
    #判断剩余字符是否合法
    for i in range(1,len(data)):
        if data[i] not in no2:
            flag = 1
            #print("%s字符不符合规范" % data[i])
            break
else:
    print("首字母格式不能为%s" % data[0])
    sys.exit()

if flag == 1:
    print("输入规范不合法")
else:
    print("输入规范合法")
还记得妞妞吗
最后更新于 2023-08-10