Python中的流程控制

 

1.if语句

  为什么要有if判断?判断事物的对错,真假,是否可行,想让计算机像人一样去工作,那么计算机也应该有对事物的对错,真假,

是否可行的判断能力,从而做出不同的响应。

if ... else语句

单分支:

   if 条件:

    满足条件后要执行的代码

双分支:   

 

"""
if 条件:
    满足条件执行代码
else:
    if条件不满足就走这段
"""
AgeOfOldboy = 48

if AgeOfOldboy > 50 :
    print("Too old, time to retire..")
else:
    print("还能折腾几年!")

 

 

多分支:

 

if 条件:
    满足条件执行代码
elif 条件:
    上面的条件不满足就走这个
elif 条件:
    上面的条件不满足就走这个
elif 条件:
    上面的条件不满足就走这个    
else:
    上面所有的条件不满足就走这段

 

 

例如:猜年龄的游戏

age_of_oldboy = 48

guess = int(input(">>:"))

if guess > age_of_oldboy :
    print("猜的太大了,往小里试试...")

elif guess < age_of_oldboy :
    print("猜的太小了,往大里试试...")

else:
    print("恭喜你,猜对了...")
View Code

Ps:if可以嵌套

 

#在表白的基础上继续:
#如果表白成功,那么:在一起
#否则:打印。。。

age_of_girl=18
height=171
weight=99
is_pretty=True

success=False

if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    if success:
        print('表白成功,在一起')
    else:
        print('什么爱情不爱情的,爱nmlgb的爱情,爱nmlg啊...')
else:
    print('阿姨好')

 

缩进:

  你会发现,上面的if代码里,每个条件的下一行都缩进了4个空格,这是为什么呢?这就是Python的一大特色,强制缩进,目的是为了让程序知道,每段代码依赖哪个条件,

如果不通过缩进来区分,程序怎么会知道,当你的条件成立后,去执行哪些代码呢? 

2.while循环

  实际生活中类似于重复的做一些事情,流水线上的工人反复劳动,直到下班时间到来程序中需不需要做重复的事情呢?以刚刚的验证用户名和密码的例子为例,用户无论输入对错,

程序都会立马结束,真正不应该是这个样子。

 

 

1. 条件循环:while,语法如下

while 条件:    
    # 循环体
 
    # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
    # 如果条件为假,那么循环体不执行,循环终止

例如:

#打印0-10
count = 0
while count < 10:
    count +=1
    print(count)
#打印0-10之间的偶数
count = 0
while count < 10:
    count+=1
    if count%2 == 0:
    print(count)

2.死循环

 

import time
num=0
while True:
    print('count',num)
    time.sleep(1)
    num+=1 

 

while + break :

  break语法演示

while True:
    print('1')
    print('2')
    break
    print('3')
# 上面仅仅是演示break用法,实际不可能像我们这样去写,循环结束应该取决于条件

 

练习:

user_db = 'jason'
pwd_db = '123'
while True:
    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        break
    else:
        print('username or password error')
print('退出了while循环')

while+continue:

  continue的意思是终止本次循环,直接进入下一次循环

例如:需循环打印1,2,3,4,5,7,8,9,数字6不打印

count = 0
while count < 10:
    count+=1
    if count == 6:
        continue
    print(count)

ps:continue不能加在最后一步执行的代码,因为代码加上去毫无意义

while True:
    if 条件1:
        code1
        code2
        code3
        ...
    continue  # 无意义
  elif 条件1:
        code1
        code2
        code3
        ...
    continue  # 无意义
    else:
        code1
        code2
        code3
        ...
    continue  # 无意义
View Code

3.while循环嵌套

# 退出内层循环的while循环嵌套
user_db = 'jason'
pwd_db = '123'
while True:
    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        while True:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                break
            print('%s功能执行'%cmd)
    else:
        print('username or password error')
print('退出了while循环')

# 退出双层循环的while循环嵌套

while True:
    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        while True:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                break
            print('%s功能执行'%cmd)
        break
    else:
        print('username or password error')
print('退出了while循环')

Ps:上述方法有点low,有多个while循环就要写多个break,有没有一种方法能够帮我解决,只要我退出一层循环其余的各层全都跟着结束>>>:定义标志位

# 退出双层循环的while循环嵌套
user_db = 'jason'
pwd_db = '123'
flag = True
while flag:
    inp_user = input('username: ')
    inp_pwd = input('password: ')
    if inp_user == user_db and pwd_db == inp_pwd:
        print('login successful')
        while flag:
            cmd = input('请输入你需要的命令:')
            if cmd == 'q':
                flag = False
                break
            print('%s功能执行'%cmd)
    else:
        print('username or password error')
print('退出了while循环')
View Code

4.while+else(了解)

  while+else:else会在while没有被break时才会执行else中的代码。

# while+else
n = 1
while n < 3:
      if n == 2:break  # 不会走else
    print(n)
    n += 1
else:
    print('else会在while没有被break时才会执行else中的代码')

3.for循环

name_list = ['jason', 'nick', 'tank', 'sean']
n = 0
while n < len(name_list):  # while n < 4:
    print(name_list[n])
    n += 1
for name in name_list:
  print(name)  # 对比与while更加简便


# 再来看for循环字典会得到什么 info = {'name': 'jason', 'age': 19} for item in info: print(item) # 拿到字典所有的key print(info[item]) # for可以不依赖于索引取指,是一种通用的循环取指方式 # for的循环次数是由被循环对象包含值的个数决定的,而while的循环次数是由条件决定的

for循环也可以按照索引取值

for i in range(1, 10):  # range顾头不顾尾
    print(i)

# python2与python3中range的区别(cmd窗口演示即可)

# for循环按照索引取值
name_list =  ['jason', 'nick', 'tank', 'sean']
# for i in range(0,5):  # 5是数的
for i in range(len(name_list)):
    print(i, name_list[i])

for+break:跳出本层循环

# for+break
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    if name == 'jason':
        break
    print(name)

for+continue:跳出本次循环,进入下一次循环

# for+continue
name_list = ['nick', 'jason', 'tank', 'sean']
for name in name_list:
    if name == 'jason':
        continue
    print(name)
posted @ 2019-07-02 15:38  Yzy~Yolo  阅读(173)  评论(0编辑  收藏  举报