zoukankan      html  css  js  c++  java
  • [python]python中的if, while, for

    python中的代码块,通过缩进对齐,来表达代码逻辑。

    1. if语句

    if expression1:
        if_suite
    elif expression2:
        elif_suite
    else:
        else_suite

    如果expression1的值为非0或者为布尔值True,则执行if_suite;

    如果expression2的值为非0或者为布尔值True,则执行elif_suite;

    否则,执行else_suite。

    2. while循环

    while expression:
        while_suite

    while_suite会持续循环执行,直到表达式的值变成0或False。

    3. for循环

    for接受可迭代对象作为其参数,每次迭代其中一个元素。

    示例:

    print 'I like to use the internet for: '
    for item in ['email', 'net-surfing', 'homework', 'chat']:
        print item

    运行结果:

    I like to use the internet for: 
    email
    net-surfing
    homework
    chat

    如果想让输出在同一行上,可以在print后加逗号。

    示例:

    print 'I like to use the internet for: '
    for item in ['email', 'net-surfing', 'homework', 'chat']:
        print item,

    运行结果:

    I like to use the internet for: 
    email net-surfing homework chat

    我们可以用for来生成一个数字序列。

    示例:

    for eachnum in [0, 1, 2]:
        print eachnum

    运行结果:

    0
    1
    2

    python的range()内建函数,可以接受一个数值范围,很方便的生成一个列表。

    示例:

    for eachnum in range(3):
        print eachnum

    运行结果:

    0
    1
    2
  • 相关阅读:
    luogu P3804 【模板】后缀自动机 (SAM)
    莫队
    luogu P4688 [Ynoi2016]掉进兔子洞
    FZOJ 2331 LYK loves graph
    字典树
    luogu P6623 [省选联考 2020 A 卷] 树
    luogu P6018 [Ynoi2010]Fusion tree
    luogu P3264 [JLOI2015]管道连接
    最小斯坦纳树
    9. 回文数
  • 原文地址:https://www.cnblogs.com/sophia194910/p/4998454.html
Copyright © 2011-2022 走看看