python编程基础——选择、循环

选择结构

if语句

在python语言中,可以使用if语句实现:

if <boolean expression>:
	<statement 1>
	<statement 2>
	...
if x > y:
    temp = x
    x = y
    y = temp


if-else语句

if <boolean expression>:
	<block of statements>
else:
	<block of statements>
if x > y:
    max = x
else:
    max = y


三元操作符

A=X if * else Y
*结果为True时,A=X,否则为Y
x = 5 if True else 3
y = 5 if False else 3

# 结果
x = 5
y = 3


循环结构

for循环

for  <variable> in range(<start>, <stop>):
	<block of statements>
for x in range(2):
	print(x)
	
# 结果
0
1

for循环遍历系列对象

# 字符串
str = "asd"
for i in str:
    print(i)
# 列表
lis = list(str)
for i in lis:
    print(i)
# 元组
tup = tuple(str)
for i in tuple(str):
    print(i)
# 字典
dic = {}.fromkeys(str, 2)
for i in dic:
    print(i)
# 集合
se=set(str)
for i in se:
    print(i)

while语句

while <boolean expression>:
	<statement 1>
	<statement 2>
	...
while x < 10:
    print("X=", x)
    x += 1

break和continue

break的含义就是中断循环,跳出整个循环体。

a = 0
while True:
    a += 2
    if a > 10:
        break
print(a)

# 结果
12

continue的含义是跳过循环体中其后面的部分代码,继续循环。

a = 0
while a < 5:
    a += 1
    if a % 2 == 0:
        continue
    else:
        print(a)
# 结果
1
3
5
发布了19 篇原创文章 · 获赞 19 · 访问量 3617

猜你喜欢

转载自blog.csdn.net/qq_36733722/article/details/101109445