zoukankan      html  css  js  c++  java
  • 一步一步学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 执行和求值字符串

  • 相关阅读:
    layui动态修改select的选中项
    layui 鼠标悬停单元格显示全部
    使用LayUI操作数据表格
    layer.msg 弹出不同的效果的样式
    layer父页面刷新
    layui 获取radio单选框选中的值
    使用Dapper.Contrib
    微信公众号的文章爬取有三种方式
    centos的 各种安装包下载位置
    git pull一直弹出vim编辑器
  • 原文地址:https://www.cnblogs.com/chentongxin/p/3483236.html
Copyright © 2011-2022 走看看