流程控制if,while,for语句

流程控制

if语句

什么是if?

主要是用于判断事物的对错,真假,是否可行

语法结构:

  python是通过缩进来决定代码的归属

1.if条件:

  代码块

  ...

a=12
b=12
if a==b :
    print('true')
true

2.if条件:

  代码块

  ...

  else:

  代码块

  ...

a=12
b=12
if a==b :
    print('true')
else:
    print('false')
true

3.if条件1:

  代码块1

  ...

elif 条件2:

  代码块2

  ...

else :

  代码块n

gender='female'
age=19
is_beautiful=True

if gender =='female' and  18<age<29 and is_beautiful:
    print('小姐姐,给个微信')
elif gender=='female' and age<18 and is_beautiful:
    print('小姐姐,你太年轻了,认识一下')
else :
    print('打扰了')
小姐姐,给个微信

这里可以在流程控制语句中添加多个elif

pep8中:缩进一定是四个空格

从上往下执行哪一条里面的代码块,则不执行其他的

可以当作False来使用的:

0,None,"",[],{}

while语句:

语法结构:

  while 条件:

    条件成立时,将要执行的代码块

continue:跳过本次循环,执行下次循环,不管后面有多少行代码,都不会执行

break:结束本层循环,指代当前while,只能结束一层循环

#1.打印1-10
#2.不打印7
#3.遇到10,结束循环

count=0
while count<10:
    count+=1
    if count==7:
        continue
    if count==10:
        break
    print(count)
1
2
3
4
5
6
8
9

while+else:

  当你的while正常结束时,就会执行else下面的代码块,如果被break打断,就不会执行

len()方法:

  获取字符串的个数,包括空格,逗号

s1='hello , world'
print(len(s1))
13

  获取列表的个数

li=[1,2,3,4]
print(len(li))
4

  获取字典键—值对的数

info ={'name':'godlover','age':18}
print(len(info))
2

for循环语句

for:给我们提供了一种不依赖于索引的取值方式

语法结构:

  for 变量 in 容器类型:

    容器类型有几个值,就循环几次

for取值方式更加简洁

range()数字生成器 顾头不顾尾

range(start,stop,step)

字典对象直接访问无法访问值value

for+else:

  正常结束,执行else对应的代码块

  被break打断,便不会再执行

for语句的嵌套循环

#输入******
 #   ******
 #   ******

for i in range(3): for i in range(6): print('******',end='') print()
"""
九九乘法表:
1x1=1
2x1=2 2x2 =4
。。。。     
"""
for i in range(1,10):
    for j in range(1,i+1):
        print(f'{i}*{j}={i*j}',end="  ")
    print()
模拟用户登录
"""
模拟认证功能:
    1、接收用户的输入
    2、判断用户的输入结果
    如果用三次输入失败,锁定账户
    如果用户登录成功:
        执行指令
    3、返回数据

"""



db_username='godlover'
db_password='123'

count=0
tag=True
while tag:
    username=input('Please input your username:')
    password=input('Please input your password:')
    if username==db_username and password==db_password :
        print('登录成功!')
        while tag:
            cmd=input('执行指令:')
            if cmd=='exit':
                print('您已退出')
                tag=False
            else:
                print(f'执行{cmd}指令')
    else:
        print('登录失败,请重新输入!')
        count += 1
    if count == 3:
        print('锁定账户')
原文地址:https://www.cnblogs.com/godlover/p/11792476.html