• 一步一步学python(五) -条件 循环和其他语句


    1、print

    使用逗号输出 - 打印多个表达式也是可行的,但要用逗号隔开

    >>> print 'chentongxin',23

    SyntaxError: invalid syntax

    python3.0以后,print不再是语句,而是函数,函数要加上括号

    >>> print('chentongxin',23)
    chentongxin 23
    >>> 1,2,3
    (1, 2, 3)
    >>> print 1,2,3
    SyntaxError: invalid syntax
    >>> print(1,2,3)
    1 2 3

     

    2、把某件事作为另一件事导入

    import  somemodule

    from  somemodule import somefunction

    from somemodule import somefunction  , anotherfunction ....

    from somemodule import  *

    3、 序列解包

    多个赋值同时进行

    >>> x,y,z = 1,2,3
    >>> print(x,y,z)
    1 2 3

    交换变量

    >>> x,y = y,x
    >>> print(x,y,z)
    2 1 3

    popitem : 获取字典中的键值对

    4、 链式赋值

    x = y = somefunction()

    5、 增量赋值

    >>> x = 2
    >>> x += 1
    >>> x*=2
    >>> x
    6

    字符串类型也适用
    >>> str = 'str'
    >>> str += 'ing'
    >>> str*=2
    >>> str
    'stringstring'

    6、语句块

    语句块实在条件为真时执行或者执行的多次的一组语句。在代码钱放置空格来缩进即可创建语句块

    Python中用冒号(:)来标识语句块的开始,块中的每一个语句都是缩进的,当回退到和已经闭合的快一样的缩进量时,就表示当前块结束了

    7、 条件和条件语句

    False  None0 " "( ) [ ]{ } 这些符号解释器会看成false其他的一切都为真

    if  和 else 用法

    name = input('what is your name?')

    if name.endswith('Gumby'):
        print('hello,mr,gumby')
    else:
        print('hello,stranger')
    e
    lif  用法:

    8、嵌套代码块

    if 里面 可以继续嵌套 if语句

    9、更复杂的条件

    比较运算符

    相等运算符

    同一性运算符  is

     成员资格运算符 in

    字符串和序列比较

    10、断言

    assert

    11、循环

    while循环

    name = ''
    while not name:
        name = input('please enter your name:')
    print('hell,%s' % name)

    for循环

    words = ['this','is','an','ex','parrot']
    for word in words:
        print(word)

    12、一些迭代工具

    并行迭代

    编号迭代

    13、跳出循环

    break 

    continue

    14、循环中的else子句

    from math import sqrt
    for n in range(99,80,-1):
        root = sqrt(n)
        if root == int(root):
            print(n)
            break
    else:
        print("Didn't find it")

    15、列表推导式 - 轻量级循环

    列表推导式是利用其他列表创建新列表

    [x*x for x in range(10)]

    16、什么都没发生

    pass 程序什么都不做

    17、使用del删除

    18、使用exec和eval 执行和求值字符串

  • 相关阅读:
    IE故障修复之点击无反应
    第三十四天 我为集成平台狂(七)-步履轻盈的JQuery(五)
    《世界如此险恶,你要内心强大》读书笔记(二)
    hbase phoenix char may not be null
    堆(优先级队列) 的应用
    JVM 调优总结
    Reactor模式和NIO
    JVM调优总结 -Xms -Xmx -Xmn -Xss
    Hadoop源码分析37 RPC的线程协作
    Hadoop源码分析37 RPC的线程协作
  • 原文地址:https://www.cnblogs.com/chentongxin/p/3483236.html
Copyright © 2020-2023  润新知