• Python基础(七):流程控制语句


    if语句

    基本格式:

    if <test1>:
        <statements1>
    elif <test2>:
        <statements2>
    else:
        <statements3>

    例子:

    x=input("请输入数字:")
    if x=='1':
        print("you are right!")
    elif x=='2':
        print("you are wrong!")
    else:
        print("数字错误!")

    if /  else 的三目运算形式:[返回值A   if 条件表达式   else 返回值B]

    x=input("请输入数字:")
    answer="right " if x=='1' else "wrong"
    print(answer)

    while循环

    一般格式:

    while <test>:
        <statements1>
    else:
        <statements2>

    例子:

    a = 3
    b = 10
    while a < b:
        print(a, end=' ')
        a += 1
    
    结果:
    3 4 5 6 7 8 9 

    break,continue,pass

    break:

      跳出最近所在的循环

    while True:
        name = input("名字:(q退出)")
        if name =='q':break
        age=input("年龄:")
        print(name,'==>>',age)
    
    结果:
    名字:(q退出)joe
    joe
    年龄:22
    22
    joe ==>> 22
    名字:(q退出)q
    q

    continue:

      跳到最近所在循环的开头

    x = 10
    while x:
        x -= 1
        if x % 2 == 0: continue
        print(x, end='---')
    
    结果:
    9---7---5---3---1---

    pass:

      空占位语句,什么也不做

    for循环

    for循环是通用的序列迭代器。一般格式为:

    for <target> in <object>:
      <statements1>
    else:
      <statements2>

    例子:

    for x in ['hello','python','hello','world']:
        print(x,end="  ")
    
    
    结果:
    hello  python  hello  world 
    D={'a':1,'b':2,'c':3}
    for key,value in D.items():
        print(key,'=>',value)
    
    结果:
    a => 1
    c => 3
    b => 2

    range循环计数器

    range会产生从零算起的整数列表,但其中不包括该参数的值。range有三个参数,起始值,终值和步长。

    print(list(range(9)))
    
    结果:
    [0, 1, 2, 3, 4, 5, 6, 7, 8]
    for i in range(5):
        print(i,end="---")
    
    结果:
    0---1---2---3---4---
  • 相关阅读:
    [LeetCode290]Word Pattern
    [LeetCode19]Remove Nth Node From End of List
    [LeetCode203]Remove Linked List Elements
    [LeetCode160]Intersection of Two Linked Lists
    [LeetCode118]Pascal's Triangle
    [LeetCode228]Summary Ranges
    [LeetCode119]Pascal's Triangle II
    Directx11学习笔记【四】 封装一个简单的Dx11DemoBase
    Directx11学习笔记【三】 第一个D3D11程序
    平衡二叉树详解
  • 原文地址:https://www.cnblogs.com/austinjoe/p/9400607.html
Copyright © 2020-2023  润新知