zoukankan      html  css  js  c++  java
  • Python中的流程控制

    一、if

    1.语法

    if 条件1:

      满足条件1,所执行的代码

    elif 条件2:

      满足条件2 ,所执行的代码

    elif 条件3:

      满足条件3,所执行的代码

    else:

      以上条件均不满足所执行的代码。

    PS:if、elif、elif、else中的代码只有其中之一会被执行。例如:当不满足条件1而满足条件2时,会执行‘满足条件2 ,所执行的代码‘

    当同时满足 条件1和条件2的时候,程序在执行完’满足条件1,所执行的代码‘时就结束了,不会执行条件2的代码。

    score = 92
    
    if score > 90:
        print('excelent!'.title())
    elif score > 80:
        print('good!'.title())
    else:
        print('shamed'.title())

    2.if嵌套

    score = 92
    PE_score = 80
    if score > 90:
        print('excelent!'.title())
        if PE_score > 90:
            print('good at sports and sports'.title())
    elif score > 80:
        print('good!'.title())
    else:
        print('shamed'.title())

    二、while

    1.语法

    while + Condition1:

        Code1

    满足Condition1时,将执行Code1。当Code1的代码都被执行完一遍后,将重新判断是不是满足Condition1。

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

    2.break

    将直接结束本层循环

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

    3.continue

    跳过本次循环。即continue后的语句都不会执行,将重新判断是否满足Condition1。

    
    
    count = 0
    while count < 10:
        print(count)
        if count == 8:
            continue     # 进入到死循环,持续输出8
        count += 1

    4.while嵌套

    db_username = 'yyh'
    db_password = '1234'
    count = 0
    while True:
        input_name = input('Enter your username:')
        input_password = input('Enter your password:')
        if input_name == db_username and input_password == db_password:
            print('Login in!')
            while True:
                cmd = input('>>>')
                if cmd != 'quit':
                    print(f'run <{cmd}>')
                else:
                    break
            break
        else:
            print('Wrong username or password!')
            count += 1
            if count == 3:
                print('Your account is locked!')
                break

    三、for

    1.语法

    for element in iterable:

      body

    for循环给我们提供了不依赖索引的取值方式,适用于一切可迭代对象

    2.for与continue、break的用法同while

    3.for循环的嵌套

    for i in range(1, 10):
        for j in range(1,i+1):
            if j <= i:
                if i * j < 10:
                    print('{0}*{1}={2}'.format(j, i, i * j), end='  ')
                else:
                    print('{0}*{1}={2}'.format(j, i, i*j),end=' ')
        print()

    打印99乘法表

  • 相关阅读:
    Lyndon Word & The Runs Theorem
    Codeforces 1477F. Nezzar and Chocolate Bars
    Codeforces Round #700 (Div.1)
    kubeadm 安装 k8s
    centos7更新阿里yum源
    CF1186 F. Vus the Cossack and a Graph
    CF1152 D. Neko and Aki's Prank
    CF803 C. Maximal GCD
    CF1180 B. Nick and Array
    CF1186 D. Vus the Cossack and Numbers
  • 原文地址:https://www.cnblogs.com/Ghostant/p/11792136.html
Copyright © 2011-2022 走看看