Python基础(七):流程控制语句

if语句

基本格式:

if <test1>:
    <statements1>
elif <test2>:
    <statements2>
else:
    <statements3>

例子:

x=input("请输入数字:")
if x=='1':
    print("you are right!")
elif x=='2':
    print("you are wrong!")
else:
    print("数字错误!")

if /  else 的三目运算形式:[返回值A   if 条件表达式   else 返回值B]

x=input("请输入数字:")
answer="right " if x=='1' else "wrong"
print(answer)

while循环

一般格式:

while <test>:
    <statements1>
else:
    <statements2>

例子:

a = 3
b = 10
while a < b:
    print(a, end=' ')
    a += 1

结果:
3 4 5 6 7 8 9 

break,continue,pass

break:

  跳出最近所在的循环

while True:
    name = input("名字:(q退出)")
    if name =='q':break
    age=input("年龄:")
    print(name,'==>>',age)

结果:
名字:(q退出)joe
joe
年龄:22
22
joe ==>> 22
名字:(q退出)q
q

continue:

扫描二维码关注公众号,回复: 2503553 查看本文章

  跳到最近所在循环的开头

x = 10
while x:
    x -= 1
    if x % 2 == 0: continue
    print(x, end='---')

结果:
9---7---5---3---1---

pass:

  空占位语句,什么也不做

for循环

for循环是通用的序列迭代器。一般格式为:

for <target> in <object>:
  <statements1>
else:
  <statements2>

例子:

for x in ['hello','python','hello','world']:
    print(x,end="  ")


结果:
hello  python  hello  world 
D={'a':1,'b':2,'c':3}
for key,value in D.items():
    print(key,'=>',value)

结果:
a => 1
c => 3
b => 2

range循环计数器

range会产生从零算起的整数列表,但其中不包括该参数的值。range有三个参数,起始值,终值和步长。

print(list(range(9)))

结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
for i in range(5):
    print(i,end="---")

结果:
0---1---2---3---4---

猜你喜欢

转载自www.cnblogs.com/austinjoe/p/9400607.html
今日推荐