python入门基础三之流程控制

流程控制(if  while  for)

一.if

为什么要有if判断
判断事物的对错,真假,是否可行
想让计算机像人一样去工作,那么计算机也应该有对事物的对错,真假,是否可行的判断能力
从而做出不同的响应

固定语法
python用缩进表示代码的归属
同一缩进的代码,称之为代码块


补充:布尔值位False数据由哪些:0,None,'',[],{}
布尔值可以直接用来判断
变量名也可以用来判断,因为变量名指向的值对应的就是True或False

例子:

if 条件:
            代码1
            代码2
            代码3
            代码4
            ...
if 条件:
            代码1
            代码2
            代码3
            代码4
            ...
        else:  # 不能单独使用,必须和if,while,for配合使用
            代码1
            代码2
            代码3
            代码4
            ...
if 条件:
            代码1
            代码2
            代码3
            代码4
            ...
elif 条件:
            代码1
            代码2
            代码3
            代码4
            ...
elif 条件:
            代码1
            代码2
            代码3
            代码4
            ...
elif 条件:
            代码1
            代码2
            代码3
            代码4
            ...
else:  # 不能单独使用,必须和if,while,for配合使用
            代码1
            代码2
            代码3
            代码4
            ...
if 条件:
    代码1
    代码2
    代码3
    代码4
    ...
        if 条件:
        代码1
        代码2
        代码3
        代码4
        ...       
           if 条件:
            代码1
            代码2
            代码3
            代码4
            ...                

练习1:

* 如果 成绩>=90,打印"优秀"
* 如果 成绩>=80 并且 成绩<90,打印"良好"
* 如果 成绩>=70 并且 成绩<80,打印"普通"
* 其他情况:打印"差"

if score >= 90:
    print('优秀')

elif score >= 80:
    print('良好')

elif score >= 70:
    print('普通')
else:
    print('')

练习2:模拟登录注册

user_from_db = 'jason'
pwd_from_db = '123'

user_from_inp = input('username: ')
user_from_inp = input('password: ')

if user_from_inp == user_from_db and pwd_from_inp == pwd_from_db:
    print('login successful')
else:
    print('username or password error')

练习3:上下班

如果:今天是Monday,那么:上班
如果:今天是Tuesday,那么:上班
如果:今天是Wednesday,那么:上班
如果:今天是Thursday,那么:上班
如果:今天是Friday,那么:上班
如果:今天是Saturday,那么:出去浪
如果:今天是Sunday,那么:出去浪

today=input('>>: ')
if today == 'Monday' or today == 'Tuesday' or today == 'Wednesday' or today == 'Thursday' or today == 'Friday':
    print('上班')
elif today == 'Saturday' or today == 'Sunday':
    print('出去浪')
today=input('>>: ')
if today in ['Monday','Tuesday','Wedensday','Thursday','Friday'] :
    print('上班')
elif today in['Saturday','Sunday'] :
    print('出去浪')

二.while

1.while语法

while 条件
    code 1
    code 2
    code 3
    ...

while True:
    print('>>>1')
    print('>>>2')
    print('>>>3')  #这是循环,我们写代码要避免这种死循环,必须要有退出循环的条件

2.while+break

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循环')

3.while+continue

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

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

n = 1
while n < 10:
    if n == 6:
        n += 1  # 如果注释这一行,则会进入死循环
        continue
    print(n)
    n += 1

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

4.while+else

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

例子:

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

5.while循环嵌套

例子:ATM密码输入成功还需要进行一系列的命令操作,比如取款,比如转账。并且在执行功能结束后会退出命令操作的功能,即在功能出执行输入q会退出输出功能的while循环并且退出ATM程序。

# 退出内层循环的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循环嵌套
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)
        break
    else:
        print('username or password error')
print('退出了while循环')

下面展示一种用定义标志位来退出多个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循环')

三.for循环

通过一个例子比较一下while循环与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循环来遍历列表,当面对字典时,while循环很难操作,反而for循环就很简便:

info = {'name': 'jason', 'age': 19}
for item in info:
    print(item)  # 拿到字典所有的key
    print(info[item])

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

for i in range(1, 10):  # range顾头不顾尾
    print(i)
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循环与while循环都可以存在 break continue

for循环练习题:

1.打印99乘法口诀表

'''
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
...
9*1=9.................9*9=81
'''

for i in range(1,10): #i=3
     for j in range(1,i+1):
         print('%s*%s=%s ' %(i,j,i*j),end='') #i=2 j=2
     print()
万般皆下品,唯有读书高!
原文地址:https://www.cnblogs.com/s686zhou/p/11120844.html