zoukankan      html  css  js  c++  java
  • Python中的基本语句

           本文简单的介绍下Python的几个基本语句。

    print语句

          print可同时打印多个表达式,只要将他们用逗号隔开。

    >>> name='Gumy'
    >>> greet='hello'
    >>> print(name+',',greet) #注意这里既有用到+号,又用到逗号同时打印多个表达式
    Gumy, hello

    import语句

          在导入一些模块的时候会用到import。

                import somemodule

                from somemodule import somefunction

                from somemodule import somefunction,otherfunction,otherfunction

                from somemodule import*

          同时还可以加入as作为导入的别名。

    >>> import math as foobar
    >>> foobar.sqrt(4)
    2.0
    >>> from math import sqrt as myfunc
    >>> myfunc(3)
    1.7320508075688772


    赋值语句

          在Python的赋值语句存在一些小技巧。

    (1)序列解包

          将多个值构成的序列解开,然后放到变量的序列中。它允许函数返回一个以上的值打包成元组。 然后通过一个赋值语句很容易进行访问,所解包的序列中的元素数量必须和放置在=左边变量的数量相等,否则引发异常。

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

    (2)链式赋值

         将同一个值赋给多个变量的捷径。

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

    (3)增量赋值

         其实就是c++里面的复合赋值。

    >>> x=2
    >>> x*=2
    >>> x
    4


    if、while和for语句

         语句的功能基本上和其他语言的语句一样,有些区别。

       (1)Python中,语句块并不是用“{}”来表示,而是用":“表示语句块的开始,缩进表示语句块,退回缩进量表示语句块结束。

       (2)elseif被简写为elif。

       (3)比较运算符多了一个”x is y“(判断x和y是不是同一对象),而x==y只是判断x和y的值相不相等。

    >>> x=y=(1,2)
    >>> z=(1,2)
    >>> x==y
    True
    >>> x==z
    True
    >>> x is z
    False
    >>> x is y
    True

       (4)短路运算采用not,and,or,而不是||,&&,~。

       (5)del语句,只是删除某个变量本身,而不删除变量所指向的空间,指向的空间由Python负责释放。

    >>> x=y=(1,2)
    >>> del x  #只是将x变量删除,其指向元组还在
    >>> x
    Traceback (most recent call last):
      File "<pyshell#33>", line 1, in <module>
        x
    NameError: name 'x' is not defined
    >>> y
    (1, 2)

       (6)for循环表达式结构有点小区别。同时也可以使用break,continue关键字。

    sum=0;
    arr=[1,2,3,4,5]
    for i in range(len(arr)):
        sum+=arr[i]
    print (sum)

       (7)轻量级循环

    >>> [x*x for x in range(10) if x<5]
    [0, 1, 4, 9, 16]
    >>> [(x,y) for x in range(3) for y in range(3)]
    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

       (8)空操作不是用nop了哟,而是用pass关键字。

       (9)迭代工具:并行迭代,编号迭代,翻转和排序迭代。

       (10)也存在断言工具。、

       (11)执行Python语句exec,执行Python表达式eval。

  • 相关阅读:
    Windows API—CreateEvent—创建事件
    C++的注册和回调
    Python内置模块-logging
    使用 C++ 处理 JSON 数据交换格式
    Python生成器
    5.Spring-Boot缓存数据之Redis
    6.Spring-Boot项目发布到独立的tomcat中
    7.Spring-Boot自定义Banner
    8.Spring-Boot之SpringJdbcTemplate整合Freemarker
    9.Spring-Boot之Mybatis-LogBack-Freemarker
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3429287.html
Copyright © 2011-2022 走看看