流程控制之if...elif...else和流程控制之while循环

一、流程控制之if elif else

1、如果:女人年龄大于28岁,那么:叫大姐姐,否则:叫小姐姐

old_gird=28
if old_gird > 28:
    print('大姐姐')
else
    print('小姐姐')

2、如果:女人的年龄>=18并且<22岁并且身高>170并且体重<100并且是漂亮的,那么:表白,否则:gd,如果:表白成功,那么:在一起,如果不成功,那么:mmp

old_gird=21
height=170
weight=99
is_pretty=True
success=False
if old_gird >= 18 and old_gird < 22 and height == 170 and weight < 100 and is_pretty==True:   #注意,这里值比较用"=="
    if success:
        print('在一起')
    else:
        print('mmp')
else:
    print('gd')

3、如果:成绩>=90,那么:优秀,
如果:成绩>=80且<90,那么:良好,
如果:成绩>=70且<80,那么:普通,
其他情况:很差

grade=input('grad=')
grade=int(grade)
if grade >= 90:
    print('优秀')
elif grade >= 80:
    print('良好')
elif grade >= 70:
    print('普通')
else:
    print('很差')

4、用户登录验证,需求:

输入用户名,密码,登录成功。

user=input('user:')
print(type(user))
password=input('password:')
print(type(password))
if user=='lqx' and password=='123456':
    print('login successful')
else:
    print('user or password orror')

5、根据用户输入内容打印其权限,需求:
用户1,lqx 超级管理员
用户2,ft 管理员
用户3,egon、join 普通用户

user=input('user:')
dict={'lqx':'超级管理员','ft':'管理员','egon':'普通用户','join':'普通用户'}  #这里用dict定义每个用户所定义的职位
if user=='lqx':
    print(dict[user])   #dict[user],[]里面如果不用''是变量的意思,如果''引起来是dict中的key的意思
elif user=='ft':
    print(dict[user])
elif user=='egon' or 'join':
    print(dict[user])
else:
    print('不相干人员')
二、if中使用逻辑符,或者使用if in [”,”] elif else

需求:周一到周五,工作。周末,浪

#方法一:
day_number=input('day_number:')

if   day_number==   'Mon':
    print('job')
elif day_number==   'Tue':
    print('job')
elif day_number ==  'Wed':
    print('job')
elif day_number ==  'Thu':
    print('job')
elif day_number ==  'Fri':
    print('job')
elif day_number ==  'Sat':
    print('job')
elif day_number ==  'Sun':
    print('job')
else:
    print('''please print under:
    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun
    ''')
#方法二 使用逻辑符or实现:
day_number=input('day_number:')

if   day_number=='Mon' or day_number=='Tue' or day_number ==  'Wed' or day_number =='Thu' or day_number == 'Fri':
    print('job')
elif day_number ==  'Sat' or day_number ==  'Sun':
    print('浪')
else:
    print('''please print under:
    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun
    ''')
#方法三:  使用if.in ['','']:elif...:else...
day_number=input('day_number:')

if day_number in ['Mon','Tue','Wed','Thu','Fri']:
    print('job')
elif day_number in ['Sat','Sun']:
    print('浪')
else:
    print('''please print under:
    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun
    ''')
三、流程控制之while循环
while语法:

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

实例:

1、打印0-10

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

2、打印0-10之间的偶数

count=0
while count <= 10:
    if count%2 == 0:
        print('loop',count)
    count+=1

3、打印0-10之间的奇数

count=0
while count <= 10:
    if count%2 == 1:
        print('loop',count)
    count+=1
死循环
import time    #导入模块 time
num=0
while True:
    print('count',num)
    time.sleep(1)   #使用模块,并且休息一秒
    num+=1
循环嵌套与tag
tag=True
while tag:
    ...
    while tag:
        ...
        while tag:
            ...

练习,要求如下:
1 循环验证用户输入的用户名与密码
2 认证通过后,运行用户重复执行命令
3 当用户输入命令为quit时,则退出整个程序

#方法一:
count=1
while True:
    user = input('user:')
    password = input('password:')
    dict = {'user': 'lqx', 'password': '123'}
    if user == 'lqx' and password == '123':
        print('login successful')
        count_com=0
        while true:  
            command=input('command>>>:')
            print(command)
            if command in ['exit','quit','q'] :
                break    #这个break会退出最近的一层while循环
        break    #这个break会退出再外面一层的while循环
    else:
        count+=1
        continue   #这里continue不加也默认本次循环,执行下一次循环
#方法二:使用tag
name='egon'
password='123'
tag=True   
while tag:
    inp_name=input('用户名: ')
    inp_pwd=input('密码: ')
    if inp_name == name and inp_pwd == password:
        while tag:
            cmd=input('>>: ')
            if not cmd:continue   #这里是用了个合并行,其实还是
            #if not cmd:   #cmd没有值
            #   continue 
            if cmd == 'quit':
                tag=False
                continue
            print('run <%s>' %cmd)
    else:
        print('用户名或密码错误')
break与continue
#break用于退出本层循环
while True:
    print('123')
    break
    print('456')  #这里是测试,break退出本层循环后,就不会执行下面同级别的命令

#continue用于退出本次循环,继续下一次循环
while True:
    print('123')
    continue     #这里是测试,continue退出本次循环后,也不会执行后面同级别的命令
    print('456')
while+else
#与其他语言else 一般只与if搭配不同,在python中还有while...else语句,while 后面的else作用是指:当while循环正常执行完成,中间没有被break终止的话,就会执行else后面的语句
count=0
while count <= 5:
    if count==0:
        print("------out of while loop ------")
    count +=1
    print('loop',count)

else:
    print('''循环完成
-------------end--------------''')

#如果执行过程中被break啦,就不会执行else的语句啦
count = 0
while count <= 5:
    count += 1
    print(count)
    if count == 3:break
    print("loop",count)
else:
    print("zhixingwanc")
while循环练习题

使用while循环输出1 2 3 4 5 6 8 9 10

count=1
while count <=10:
    print(count)
    count+=1
else:
    print('输出完成')

求1-100的所有数的和

count=0
sum=0
while count <100:
    sum=sum + (count+1)   #第一轮左sum=1,右sum=0,count=0,0+1;最后一轮左sum=5050,右边的sum=4050,count等于99
    count+=1
else:
    print(sum)

输出 1-100 内的所有奇数

count=0
while count <=100:
    if count%2 ==1:    #count%2,除法取余,奇数/2余1
        print(count)
    count+=1

输出 1-100 内的所有偶数

count=0
while count <=100:
    if count%2 ==0:    #count%2,除法取余,偶数/2余0
        print(count)
    count+=1

求1-2+3-4+5 ... 99的所有数的和

count=0
sum=0
while count <=100:    #第一轮,count=0      #第二轮,count=1             第三轮,count=2     第四轮....
    if count%2 ==0:    #第一轮,count%2=0   #第二轮,count%2==1,不满足    第三轮,满足
        sum=sum+count  #第一轮,左sum=0+0                               第三轮,左sum=-1+2
        print(count)
    elif count%2 ==1:                      #第二轮,count%2==1,满足
        sum=sum-count                      #第二轮,左sum=0-1
        print(count)
    count+=1
else:
    print(sum)

用户登陆(三次机会重试)

count=1
while count <= 3:
    user = input('user:')
    password = input('password:')
    count=1
while count <= 3:
    user = input('user:')
    password = input('password:')
    dict = {'user': 'lqx', 'password': '123'}
    if user == dict['user'] and password == dict['password']:
        print('login successful')
        break
    else:
        print('user or password is error,可以重试3次,第 %s 次' %count)
    count += 1
    continue
    if user == 'lqx' and password == '123':
        print('login successful')
        break
    else:
        print('user or password is error,可以重试3次,第 %s 次' %count)
    count += 1
    continue

猜年龄游戏
要求:
允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出

count=1
while count <= 3:
    age=int(input('age:'))
    if age > 43:
        print('猜大了,可以重试3次,第 %s 次' %count)
    elif age < 43:
        print('猜小了,可以重试3次,第 %s 次' %count)
    else:
        print('猜中了,successful')
        break
    count += 1

猜年龄游戏升级版
要求:
1、允许用户最多尝试3次
2、每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
3、如何猜对了,就直接退出

ps:流程图:
这里写图片描述

count=1
while True:
    if count ==3 :
        age=int(input('age:'))
        if age > 43:
            print('猜大了,可以重试3次,第 %s 次' %count)
        elif age < 43:
            print('猜小了,可以重试3次,第 %s 次' %count)
        else:
            print('猜中了,successful')
            break
        count += 1
    else:
        judge = input('是否继续(Y/N):')
        if judge in ['Y','y']:
            count = 1
        else:
            break

四、作业

I、练习题
1、简述编译型与解释型语言的区别,且分别列出你知道的哪些语言属于编译型,哪些属于解释型
编译型与解释型语言的区别:
1、编译型:直接编译成二进制的语言统称为编译型语言,如c、c++
2、解释型:需要有指定的解释器去翻译的语言称为解释型语言,会生成中间文件,再编译,才能被计算机识别。如python,shell
2、执行 Python 脚本的两种方式是什么
1、./run.py.shell直接调用python脚本
2、python run.py 调用python 解释器来调用python脚本
3、Pyhton 单行注释和多行注释分别用什么?
单行注释,可以使用单引号,双引号,三引号,#
多行注释,直接使用三引号。
4、布尔值分别有什么?
True/False
5、声明变量注意事项有那些?
1、不能使用-号
2、开头不能是数字
3、不能使用python关键字
6、如何查看变量在内存中的地址?
print(id(变量名))
7、写代码

1、实现用户输入用户名和密码,当用户名为 seven 且 密码为 123 时,显示登陆成功,否则登陆失败!
2、实现用户输入用户名和密码,当用户名为 seven 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次
3、实现用户输入用户名和密码,当用户名为 seven 或 alex 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次

#代码1:
dic={'user':'seven','passwd':123}
user=input("输入用户名:")
passwd=int(input("输入密码:"))
if user == dic['user'] and passwd == dic['passwd']:
    print("登录成功")
else:
    print("登录失败")

#代码2:
dic={'user':'seven','passwd':'123'}
count=1
while True:
    user=input("输入用户名:")
    passwd=input("输入密码:")
    if user == dic['user'] and passwd == dic['passwd']:
        print("登录成功")
        break
    else:
        print("登录失败,请重新输入,输入失败3次,自动退出,第< %s >次" %count)
        if count == 3:
            break
        else:
            count+=1
#代码3:
dic={'seven':{'passwd':'123','count':0},
     'alex':{'passwd':'123','count':0}
     }
count=1
while True:
    user=input("输入用户名:")
    passwd=input("输入密码:")
    if user in  dic and passwd == dic[user]['passwd']:
        print("登录成功")
        break
    elif not user in dic:
        print("用户不存在")
    else:
        print("登录失败,请重新输入,输入失败3次,自动退出,第< %s >次" %count)
        if count == 3:
            break
        else:
            count+=1
            continue
8、写代码

a. 使用while循环实现输出2-3+4-5+6…+100 的和
b. 使用 while 循环实现输出 1,2,3,4,5, 7,8,9, 11,12
c.使用 while 循环实现输出 1-100 内的所有奇数
e. 使用 while 循环实现输出 1-100 内的所有偶数

#代码1:使用while循环实现输出2-3+4-5+6...+100 的和
count=0
sum=0
while count <100:
    if count%2 == 0 and count >=2:
        sum=sum-(count+1)
        count+=1
    elif count%2 == 1 and count >=2:
        sum=sum+count+1
        count += 1
    else:
        sum=2
        count += 1
else:
    print(sum)

#代码2:使用 while 循环实现输出 1,2,3,4,5, 7,8,9, 11,12 
count=1
while count <= 12:
    print(count)
    count+=1
else:
    print('输出完成')

#代码3:使用 while 循环实现输出 1-100 内的所有奇数
count=1
while count <= 100:
    if count%2 ==1:
        print(count)
        count+=1
    else:
        count+=1
else:
    print('输出完成')

#代码3:使用 while 循环实现输出 1-100 内的所有奇数
count=1
while count <= 100:
    if count%2 ==0:
        print(count)
        count+=1
    else:
        count+=1
else:
    print('输出完成')
9、现有如下两个变量,请简述 n1 和 n2 是什么关系?
  n1 = 123456
  n2 = n1
  n1的值是123456,然后n2的值是n1的值,都为123456
II、作业:
1、编写登陆接口,需求:

1、让用户输入用户名密码
2、认证成功后显示欢迎信息
3、输错三次后退出程序
4、流程图:
这里写图片描述

#代码:
count=1
tag=True
dic={
    'user':['lqx','yft'],
    'password':['123','456'],
    'auth_pass':{'lqx':'123','yft':'456'}
}
while count <=3:
    user=input('user:')
    password=input('password:')
    if user in dic['user'] and password in dic['password']  and  password == dic['auth_pass'][user]:
        print('''connecting to 192.168.10.1:22...
connection established.
To escape to local shell,press 'Ctrl+Alt+]'
        ''')
        while tag:
            command=input('[root@%s ~]#' %user)
            print('<%s># %s' %(user,command) )
            if not command:
                continue
            elif command in ['exit','quit','q']:
                print('logout')
                break
        break
    else:
        print('输入错误,请重新输入,第 <%s> 次' %count)
    count+=1
    continue

2、升级需求:

1、可以支持多个用户登录 (提示,通过列表存多个账户信息)
2、用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(提示:需把用户锁定的状态存到文件里)
流程图:
这里写图片描述

way1:

dic={
    'lqx':{'passwd':'123','count':0},
    'yft':{'passwd':'456','count':0}
}
i=1
while True:
    user=input('user:')
    passwd=input('passwd:')
    if user in dic and passwd == dic[user]['passwd']:
        print('login successful!')
        break
    elif not user in dic:
        print('用户不存在')
        i+=1
        if i == 3:
            cont_yorn=input('输错大于三次,是否继续(Y/N)')
            if cont_yorn in ['y','Y']:
                continue
            elif cont_yorn in ['N','n']:
                break
            else:
                while True:
                    print('请输入Y/N')
                    break
                continue
    else:
        print("密码错误")
        dic[user]['count']+=1       #这里是修改dict中的count值,count+1
        if dic[user]['count'] == 3:
            print('密码输错3次,<%s> 被锁定' %user)
            break

way2:

import os
user_pwd={'lqx':'123',
          'www':'qwe'}
count=1
if not os.path.isfile('user'):
    with open('user','w',encoding='utf-8'):pass
while True:
    user = input('user:').strip()
    password = input('pwd:').strip()
    with open('user','r',encoding='utf-8') as f ,open('user','a',encoding='utf-8') as write_f:
        if user  in  f.read().split('\n'):
            print('%s 用户被锁定,请联系管理员,或者尝试使用其他用户登录' %user)
            continue
        if user not in [i for i in user_pwd.keys()]:
            print('输入用户非法,请重新输入。')
        if user in [i for i in user_pwd.keys()]:
            if user_pwd[user] == password:
                print('登录成功')
            elif count == 3:
                write_f.write('%s\n'%user)
                user_pwd.pop(user)
                count=1
                print('%s 用户被锁定,请联系管理员,或者尝试使用其他用户登录'%user)
            else:
                print('密码错误')
                count+=1
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值