循环
Python中的循环语句包括for循环和while循环,它们都可以用来遍历序列或执行重复操作。下面是一些循环的基本用法:
for循环
for循环用于遍历序列(字符串、列表、元组等)中的每个元素,也可以使用range函数来生成一个整数序列进行遍历。
# for循环格式:
for 变量 in 序列:
循环体语句
# 遍历序列
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# 遍历整数序列
for i in range(1, 5):
print(i)
while循环
while循环用于在条件满足的情况下重复执行一段代码块,需要注意可能导致死循环,需要设置跳出循环的条件。
# while循环格式,条件表达式为True时执行循环体
while 条件:
循环体语句
# while循环
count = 0
while count < 5:
print(count)
count += 1
在循环中,还可以使用break和continue语句进行控制:
break语句可以立即跳出循环;
continue语句可以跳过当前循环,继续执行下一次循环。
# break语句
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
if fruit == 'banana':
break
print(fruit)
continue语句
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
if fruit == 'banana':
continue
print(fruit)
循环语句还可以和else语句一起使用,当循环正常执行完毕时,else语句会被执行。
for循环中的else语句
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
else:
print('No more fruits')
while循环中的else语句
count = 0
while count < 5:
print(count)
count += 1
else:
print('count >= 5')
以上就是Python中循环语句的基本用法,可以根据实际需要灵活使用。
分支语句
if-else语句
if语句是Python中的一种分支语句,用于在满足某个条件时执行一段代码块,否则执行另一段代码块。
if语句的基本语法格式如下:
if 条件:
代码块1
else:
代码块2
条件是一个表达式,如果表达式的值为True,则执行代码块1;否则执行代码块2。代码块1和代码块2可以是任意数量的语句块,缩进的语句块是属于相应代码块的。
if-elif-else语句
if-elif-else语句是Python中的一种分支语句,用于在多个条件中选择一个分支执行代码块。
if-elif-else语句的基本语法格式如下:
if 条件1:
代码块1
elif 条件2:
代码块2
elif 条件3:
代码块3
...
else:
代码块n
if-elif-else语句判断输入的整数num是正数、负数还是零。如果num大于0,则执行代码块1,打印输出num是正数;否则,判断elif后面的条件2,如果num小于0,则执行代码块2,打印输出num是负数;否则,执行else后面的代码块3,打印输出num是零。在使用if-elif-else语句时,需要注意各个条件的设置和代码块的缩进。
1 游客 2025-03-28 00:01 回复
555
1 游客 2025-03-28 00:00 回复
555-1 waitfor delay '0:0:15' --
1 游客 2025-03-27 23:59 回复
-1 OR 2+903-903-1=0+0+0+1
1 游客 2025-03-27 23:59 回复
-1 OR 3+640-640-1=0+0+0+1 --
1 游客 2025-03-27 23:59 回复
-1 OR 2+640-640-1=0+0+0+1 --
1 游客 2025-03-27 23:59 回复
555
1 游客 2025-03-27 23:58 回复
555
1 游客 2025-03-27 23:57 回复
555
1 游客 2025-03-27 23:55 回复
555
1 游客 2025-03-27 23:54 回复
555
@@boIJr 游客 2025-03-27 23:53 回复
555
1-1; waitfor delay '0:0:15' -- 游客 2025-03-27 23:51 回复
555
1 游客 2025-03-27 23:50 回复
555
1 游客 2025-03-27 23:49 回复
555
1 游客 2025-03-27 23:46 回复
555