python基础语法2 流程控制 if,while,for

if语句:

  什么是if?

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

  语法结构:

python是通过缩进来决定代码的归属
pep8:
    缩进一定是四个空格
    tab键
if 条件:
    代码块
    ....
    ....
if gender == 'female' and 24 > age > 18 and is_beautiful:
    print("小姐姐,给个微信")

if 条件:
     代码块1
     。。。
else:
     代码块2
     。。
if gender == 'female' and 24 > age > 18 and is_beautiful:
     print("小姐姐,给个微信")
else:  # 条件不成立将要执行的代码块
     print('打扰了')

if 条件1:
     代码块1
     。。。
elif 条件2:
     代码块2
elif 条件2:
     代码块2
elif 条件2:
     代码块2else:
     代码块n

if gender == 'female' and 24 > age > 18 and is_beautiful:
     print("小姐姐,给个微信")
# 在这个流程控制语句中可以加n多个elif
elif gender == 'female' and 30 > age > 18 and is_beautiful:
     print("认识一下")
elif 30 > age > 18 and is_beautiful:
     print("认识一下")
else:  # 条件不成立将要执行的代码块
      print('打扰了')

if ... elif ... else:
同一个代码结构里面只会执行一个
执行if就不会执行elif和else,
执行elif就不会执行if和else,执行else就不会执行if和elif    

例:

"""
模拟认证功能:
1、接收用户的输入
2、判断用户的输入解果
3、返回数据
"""
from_db_username = 'sean'
from_db_password = '123'

username = input("please input your username>>:")
password = input("please input your password>>:")

if username == from_db_username and password == from_db_password:
    print('登录成功')
else:
    print("登录失败")

if嵌套:

gender = 'female'
age = 20
is_beautiful = True
is_success = True

if gender == 'female' and 24 > age > 18 and is_beautiful:
    print("小姐姐,给个微信")
    if is_success:
        print("在一起")
    else:
        print('')
# 在这个流程控制语句中可以加n多个elif
elif gender == 'female' and 30 > age > 18 and is_beautiful:
    print("认识一下")
else:  # 条件不成立将要执行的代码块
    print('打扰了')

补充:
可以当做False来使用的:0,None,"",[],{}

while语句:

  语法结构:

  while条件:

    条件成立将要循环的代码块

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

# break:结束本层循环,单纯指代当前while  *****
# 只能结束一层循环
# 死循环
count = 0
while True:
     print(count)
     count+=1
while+嵌套:

      from_db_password = '123'
      count = 0
      tag = True
      while tag:
          username = input("please input your username>>:")
          password = input("please input your password>>:")
          if username == from_db_username and password == from_db_password:
              print('登录成功')
              while tag:
                  cmd = input(">>>:")
                  if cmd == 'exit':
                      tag = ''
                  else:
                      print(f"执行{cmd}指令")
           else:
               print("登录失败")
               count += 1
           if count == 3:
               print('锁定账户')
               tag = 0

for语句:

  # for:给我们提供了一种不依赖于索引的取值方式
  语法结构:
    for 变量 in 容器类型:
    # 容器对象中有几个值,他就循环几次

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

    for + continue

    for + break

    for + else
    # for循环正常执行结束,就会执行else对应的代码块
    # 非正常结束,例如break打断,就不会执行

for循环的嵌套:

for i in range(1,10):
    for j in range(1,i+1):
        print(f"{i}x{j}={i*j}",end="")
    print()

猜你喜欢

转载自www.cnblogs.com/ludingchao/p/11794489.html