06循环结构_数据类型内置方法(格式化语法补充)
【一】循环结构
【1】什么是循环结构
- 循环结构是一种程序控制结构,用于反复执行一组语句,直到满足某个条件为止。
- 循环结构使得程序可以更有效地重读执行某段代码,节省了编写重复代码地工作。
【2】循环结构的作用
- 循环结构的主要作用是重复执行一组语句,直到满足某个条件。
- 这种重复执行的过程可以是固定次数的,也可以是根据条件动态确定的。
- 循环结构使得程序可以更灵活、高效地处理需要重复执行地任务。
【3】while循环
# while循环
# continue break
username = "Dream"
password = "123"
# 记录错误验证的次数
count = 0
while count < 3:
inp_name = input("请输入用户名:")
inp_pwd = input("请输入密码:")
if inp_name == username and inp_pwd == password:
print("登陆成功")
else:
print("输入的用户名或密码错误!")
count += 1
【4】for循环
(1)语法
for variable in sequence:
# 循环体
- for 是循环的关键字。
- variable 是循环变量,它会在每次循环中取 sequence 中的一个值。
- sequence 是一个序列,可以是列表、元组、字符串等。
(2)使用
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Current fruit:", fruit)
print("Loop finished!")
- 上述代码会输出
Current fruit: apple
Current fruit: banana
Current fruit: cherry
Loop finished!
【5】退出循环(break)
while condition:
# 循环体
if some_condition:
break # 退出循环
【6】退出循环(continue)
while condition:
# 循环体
if some_condition:
continue # 跳过当前循环,继续下一次循环
【7】无限循环(死循环)
while True:
print("This is an infinite loop!")
-
这段代码会一直输出 "This is an infinite loop!",因为
while True:
的条件永远为真,所以循环不会停止。 -
不要再项目中出现死循环,会造成当前CPU飙升
-
在实际编程中,我们可能会在无限循环中加入某个条件来实现根据需要退出循环的逻辑
【8】标志位
(1)语法
flag = True # 初始化标志位
while flag:
# 循环体
if some_condition:
flag = False # 修改标志位,退出循环
【9】循环分支(else)
- 在while循环的后面
- 我们可以跟else语句
- 当while 循环正常执行完并且中间没有被break 中止的话
- 就会执行else后面的语句
count = 0
while count <= 5 :
count += 1
print("Loop",count)
else:
print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦 #没有被break打断,所以执行了该行代码
-----out of while loop ------
- 如果执行过程中被break
- 就不会执行else的语句
count = 0
while count <= 5 :
count += 1
if count == 3:
break
print("Loop",count)
else:
print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
-----out of while loop ------ #由于循环被break打断了,所以不执行else后的输出语句
【 range 关键字】
(1)遍历数字序列
[1]语法
for i in range(stop):
# 循环体
for i in range(start, stop):
# 循环体
for i in range(start, stop, step):
# 循环体
#使用
for i in range(5):
print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4
for i in range(2, 6):
print(i)
# 输出:
# 2
# 3
# 4
# 5
for i in range(1, 10, 2):
print(i)
# 输出:
# 1
# 3
# 5
# 7
# 9
(2)range + len遍历序列
- range :顾头不顾尾
[1]使用
my_list = ['apple', 'banana', 'orange']
for i in range(len(my_list)):
print(f"Index {i}: {my_list[i]}")
# 输出:
# Index 0: apple
# Index 1: banana
# Index 2: orange
name = 'dream'
for i in range(len(name)):
print(name[i])
#输出:
d
r
e
a
m
【二】while循环练习
# 登录认证练习
# 用列表套字典存储用户数据
# 有一个输入框输入用户名和密码 ,增加重试次数 让他一直重试知道正确位置
# 正确的话就断掉了
#方法一:
user = [{"张三":"123456"},{"李四":"147258"}]
tag = True
while tag:
user_name = input("输入用户名:")
user_password = input("输入密码:")
for user_data in user:
password = user_data.get(user_name)
if password and password == user_password:
print("登陆成功")
tag = False
break
elif password and password != user_password:
print("密码错误")
break
#方法二:
user_data_list = [
{"username":"zhangsan","password":"123"},
{"username":"lisi","password":"456"}
]
tag_ture = True
while tag_ture:
user_name = input("用户名:>>>")
user_password = input("密码:>>>")
for user_data in user_data_list:
username = user_data.get("username")
password = user_data.get("password")
if user_name == username:
if password != user_password:
print("密码错误")
else:
print("登陆成功")
tag_ture = False
【三】整数类型的内置方法
【1】类型强制转换
- 可将符合整数格式的字符串转换成整数类型
- 整数强制转换只能转化赋值整数类型格式的字符串
num = '1'
print(int(num))
#输出结果
1
【2】进制转换
(1)十进制转八进制(0o)
(2)十进制转十六进制(0x)
(3)十进制转二进制(0b)
(4)其他进制数转换为十进制数,int 也支持转换进制
#(1) print(oct(999)) # 0o 1747
#(2) print(hex(999)) # 0x 3e7
#(3) print(bin(999)) # 0b 1111100111
#(4)
# num = '0b1111100111'
# print(int(num, 2))
# num = '0o1747'
# print(int(num, 8))
# num = '0x3e7'
# print(int(num, 16))
【3】浮点数的内置方法
- 强制类型转换,转换符合浮点数的字符串可以将整数转换为浮点数
num = 100
print(float(num)) # 100.0
num = '100.11'
print(float(num)) # 100.11
【4】判断当前类型是否是整数或者浮点数
num1 = b'4' # <class 'bytes'>
num2 = '4' # unicode,Python 3 中不需要在字符串前加 'u'
num3 = '四' # 中文数字
num4 = 'Ⅳ' # 罗马数字
(1)判断当前是否为数字类型(isdigit)
print(num1.isdigit()) # True
print(num2.isdigit()) # True
print(num3.isdigit()) # False
print(num4.isdigit()) # False
(2)判断是否是小数点类型
print(num2.isdecimal()) # True
【四】字符串内置方法
【1】字符串拼接
(1)字符串 + 字符串
name = "dream"
name_one = "hope"
print(name + name_one) # dreamhope
(2).join 字符串拼接
print(','.join(name_one)) # h,o,p,e
【2】索引取值
- 正索引 从 0开始取值
- 负索引从 -1 开始取值
- 索引取值可以但是不能修改
【3】切片
- 给定一个起始位置和结束位置 截取这之间的元素
- 顾头不顾尾
name = "dream"
print(name[2:4]) # ea
print(name[0:4:2]) # de
print(name[-4:-1]) # rea
【4】计算长度
print(len(name)) # 5
【5】成员运算
print("d" in name) # True
【6】去除特殊符号
# 去除两边的特殊字符
username = "$dream$"
print(username.strip('$')) # dream
# 默认是去除两侧的空格
name = " dream "
print(name.strip(' ')) # dream
# 去除指定一侧的特殊字符
# right :右侧
print(name.rstrip("$")) # $dream
# left 左侧
print(name.lstrip("$")) # dream$
【7】切分字符串
username_password = "dream|521"
username, password = username_password.split("|")
print(username, password) # dream 521
name = "dream 521"
print(name.split()) # ['dream', '521']
【8】遍历
- 将里面的每一个元素看一遍
name = 'dream'
for i in name:
print(i)
- 输出结果
d
r
e
a
m
【9】大小写转换
name = 'Dream'
print(name.upper()) # DREAM
print(name.lower()) # dream
name = "dream"
print(name.isupper()) # False
print(name.islower()) # True
【10】判断当前字符串以 .. 开头或者结尾
name = "dream"
# 判断开头
print(name.startswith("d")) # True
# 判断结尾
print(name.endswith("m")) # True
【11】格式化语法
# %s %d占位
name = "dream"
age = 18
print("my name is %s ,my age is %s" % (name, age))
# 输出:
my name is dream ,my age is 18
# format
# 按位置传参数
print('my name is {} ,my age is {}'.format(name, age))
# 输出:
my name is dream ,my age is 18
# 按关键字传参数
print('my name is {name_location} ,my age is {age_location}'.format(name_location=name, age_location=age))
# 输出:
my name is dream ,my age is 18
# f+ {}
print(f"my name is {name} . my age is {age}")
# 输出:
my name is dream ,my age is 18
【12】join拼接
print(','.join("drema")) # d,r,e,m,a
print('|'.join(["drema","521"])) # drema|521
print('|'.join(("drema","521"))) # drema|521
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!