流程控制 if while for 语句

             if 语句是用来判断条件的真假,是否成立,如果为ture就执行,为flase则跳过

                                 1.python用缩进表示代码的归属

                                 2.同一缩进的代码,称之为代码块,默认缩进4个

       if 语句结构

    if 条件语句

   代码块1

         代码块2  

    代码块3

                  else:  # 不能单独使用,必须和if,while,for配合使用

       代码块1

       代码块2  

  代码块3

elif:

       代码块1                  if elif else 同一级别配合使用的时候,只会指向一个代码块(走了if就不会走elif else,

                                      走了elif就不会走else,if看到没走,走了else说明if elif都没走,都不满足if elif的条件

       代码块2  

  代码块3

else:

      代码块1

       代码块2  

  代码块3

while语法:用来判断语句循环的次数
    while 条件:
       代码1
       代码2
       代码3
       代码4
       代码5  

break:立即结束本层循环(只针对它所属于的哪一个while有效)
 continue:跳出本次循环,直接开始下一次循环

while也可以嵌套

while+else
 只有当while循环依据条件正常结束才会走else代码
 如果是主动结束的break,那么不会走else

 小练习:模拟用户登录 有三次机会 超过了 提示用户是否继续

user_name_bd='Kevin'
password_bd=12345
c=0
while True:
    if c==3:
        choice=input('三次机会已经用完,你还想不想尝试?(Y/N)>>:')
        if choice=='Y':
            c=0
        else:
            break
    user_name_bd=input('please input your name>>:')
    password_bd=input('please input your password_bd>>:')
    if user_name_bd=='kevin'and password_bd==12345:
        print('登陆成功')
        break
    else:
         c+=1

for循环:一般用于循环从容器(列表list 或 字典dict )中取出相对应的数值 

                       for i in [21,23,43,45,56,89]  for i in ['name':'jason','age':18,'habby':'weite'] 只取kye

len()  # 获取数据类型(容器类型)的个数,字符串是特例 获取的是字符串中字符的个数

   for循环语法结构

  for 变量名 in 容器类型:
   代码1,
   代码2,
   代码3,
   代码4,

打印金字塔:

max_level = 5
for current_level in range(1,max_level+1):
    # 打印空格
    for i in range(max_level-current_level):
        print(' ',end='')
    # 打印信号
    for j in range(2*current_level-1):
        print('*',end='')
    print()

 for循环也是可以嵌套和if while else 使用

range在python2与python3中的区别 (面试常考)

     python2中:

                    1.range其实就是一个列表
       2.xrange其实就是你python3中的range

python3中:

       range就是一种迭代,不占具多余的内存空间,需要时才会取出相对应的值

猜你喜欢

转载自www.cnblogs.com/Gaimo/p/11120786.html