zoukankan      html  css  js  c++  java
  • Python学习笔记(4):控制流

    Python的控制语句有if、while、for、break、continue。

    1. if语句

    下面是一个猜数字游戏例子:

    # Filename: if.py
    
    number = 10
    guess = int(input("Enter a integer:"))
    
    if guess == number:
        print("Congratulations, you guessed it.")
    elif guess < number:
        print("No, it is a little higher than that")
    else:
        print("No, it is a little lower than that")
    

    注意if语句结尾处包含一个冒号(:),所有控制语句结尾处都需要冒号。Python没有switch语句,您可以用if...elif...else来完成相同功能。

    2. while语句

    您可能发现上面猜数字游戏,每次都要启动一下才能猜,下面可以用while语句来控制直到你猜中才退出游戏。

    # Filename: while.py
    
    number = 10
    running = True
    
    while running:
        guess = int(input("Enter a integer:"))
    
        if guess == number:
            print("Congratulations, you guessed it.")
            running = False
        elif guess < number:
            print("No, it is a little higher than that")
        else:
            print("No, it is a little lower than that")
    else:
        print("The game is over.")
    

    其实与while相对的else是多余的,与直接把它的语句放在在while语句块后面的效果相同。

    3. for语句

    # Filename: for.py
    
    for i in range(1, 5):
        print(i)
    else:
        print("The for loop is over.")
    

    输出结果为:

    1

    2

    3

    4

    The for loop is over.

    4. break语句

    # Filename: break.py
    
    while True:
        s = input("Enter something:")
        if s == "quit":
            break
        print("Length of the string is", len(s))
    
    print("Done")
    

    5. continue语句

    # Filename: continue.py
    
    while True:
        s = input("Enter something:")
        if s == "quit":
            break
        if len(s) < 3:
            continue
        print("Input is of sufficient length")
    
  • 相关阅读:
    IplImage, CvMat, Mat 的关系
    neon memory copy
    基于v4l2的webcam应用, 本地预监
    makefile写法实例
    Ubuntu 12.04 使用Eclipse搭建C/C++编译环境
    xapp1167与TRD14.4 关系
    v3学院带你一次性认清UART、RS-232、RS-422、RS-485的区别
    v3学院教你学习-task和function的异同
    寒假参加V3
    FPGA培训学习心得
  • 原文地址:https://www.cnblogs.com/known/p/1789648.html
Copyright © 2011-2022 走看看