Python基础篇(五)

     bool用于判断布尔值的结果是True还是False

     >>> bool("a")

     True

     >>> bool(3)

     True

     >>> bool("")

     False

     >>> bool(0)

     False

     Python中的elif类似于Java中的elseif

     >>> number = (int)(input("input a number: "))

     input a number: 9

     >>> if number >0:

      ...     print("postive")

      ... elif number<0:

      ...     print("negative")

      ... else:

     ...     print("zero")

     ...

     postive

     可以将符合if后面的语句和if放在一行,也可以使用空格来缩进。使用空格来缩进时,如果缩进所使用的空格的个数不一样会导致出错,这点是需要注意的。

     Python中==和Java中的作用不一样,比较的是内容,比较内存地址使用的是is或者is not

     >>> x=y=[1,2,3]

     >>> z =[1,2,3]

     >>> x == z

     True

     >>> x is z

     False

     >>> x is not z

     True

     in运算符用于判断元素是否是成员

     >>> name = input("input your name: ")

     input your name: sdd

     >>> if "s" in name:

     ...    print(""s" is in your name")

     ... else:

     ...     print("not in")

     ...

     "s" is in your name

     更多的运算符操作:

     >>> number = (int)(input("input a number between 0 and 10 : "))

     input a number between 0 and 10 : 2

     >>> if 0<=number<=10:

     ...    print("correct number")

     ... else:

      ...    print("wrong number")

      ...

     correct number

     while循环

     >>> x=1

     >>> while x<=100:

     ...     print(x)

     ...     x = x+1

     for循环,Python中的for循环常和range配合使用

     >>> for i in range(0,100):    #也可以写成range(100)

     ...    print(i)

     >>> words = ["hello world"]

     >>> for word in words:

     ...    print(word)

     ...

     hello world

     能使用for循环时尽量使用for循环,for循环更加简洁。

     使用for循环遍历字典

     >>> d= {"a":"1","b":"2","c":"3"}

     >>> for key,value in d.items():

     ...    print(key,value)

     ...

     b 2

     a 1

     c 3

     list有sort方法,tuple和str没有sort方法,但是可以直接调用内置的sorted方法

     >>> l=[3,1,4,2]

     >>> l.sort()

     >>> l

     [1, 2, 3, 4]

     >>> sorted((2,4,1,3))

     [1, 2, 3, 4]

     >>> sorted("2413")

     ['1', '2', '3', '4']

     同样的还使用与reverse,用于做翻转操作。

     break语句,和for配合使用,跳出循环

     求1到99平方根为整数的数字,找到1个后使用break跳出循环

    >>> for int in range(99,0,-1):

    ...     if sqrt(int) % 1 ==0.0 :

    ...        print(int)

    ...        break

    ...

    81

     continue,跳过本轮循环

     >>> for int in range(0,11):

     ...    if int % 2 == 0:

     ...       print(int)

     ...    else:

...       continue

...

while True用于构建一个无限循环

>>> while True:

...    word = input("Please input a word: ")

...    if not word : break

...    print(word)

...

Please input a word: add

add

Please input a word: p

p

Please input a word:

for循环可以配合else使用,for中有输出时则不会调用else,否则会调用else

>>> from math import sqrt

>>> for int in range(99,81,-1):

...     if sqrt(int) % 1 ==0.0 :

...        print(int)

...        break

...    else:

...        print("not found")

...

not found

列表推导式:轻量级for循环

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

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

可以代替下面复杂的逻辑:

>>> items = []

>>> for int in range(0,10):

...    items.append(int*int)

...

>>> items

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

用if增加更多的限制条件:

>>> [x*x for x in range(10) if x%3==0]

[0, 9, 36, 81]

增加更多的for语句:

>>> [(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)]

Python中空代码是非法的,如果某种情况下的处理代码未完成,又想进行调试,可以用pass代替未完成的代码

>>> number = (int)(input("input a number between 0 and 10:"))

input a number between 0 and 10:-1

>>> if 0<=number<=10:

...    print("correct number")

... else:

...     pass

...

exec函数可以执行字符串格式的Python命令

>>> exec("print("hello world")")

hello world

但是简单的使用exec函数不是好的选择,exec的内容可能来自于网络,出于安全的考虑,需要将exec的内容先存储到一个命名空间中,从而使代码不会影响到其他的命名空间。

>>> from math import sqrt

>>> exec("sqrt =1")

>>> sqrt(4)

Traceback (most recent call last):

  File "", line 1, in

TypeError: 'int' object is not callable

上述的例子就是产生了相互的干扰。

>>> from math import sqrt

>>> scope = {}

>>> exec("sqrt =1",scope)    #2.x版本的命令是exec("sqrt =1") in scope

>>> sqrt(4)

2.0

>>> scope.get("sqrt")

1

eval函数用于计算表达式的值:

>>> eval(input("enter an arithmetic expression: "))

enter an arithmetic expression: 6 + 18*2

42

>>> scope ={"x":1,"y":2}

>>> eval("x*y",scope)

2

>>> scope ={}

>>> exec("x=2",scope)

>>> eval("x*x",scope)

4

使用缩进来格式代码块时,一定要注意匹配,多一个少一个空格就可能无法匹配,导致出错。

创建函数:

>>> def facfunction(number):

...     fac = [0,1]

...     for n in range(number):

...        fac.append(fac[-1] + fac[-2])

...     return fac

...

>>> facfunction(8)

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

def关键字可以用于创建函数,其他地方要引用函数直接调用函数名即可。

Python中的函数可以用return返回一个返回值,没有返回值时可以返回空。

希望给函数的功能加上注释,可以使用#,也可以直接使用字符串,使用help参数来查看注释。

>>> def facfunction(number):

...     "caculate fac number"

...     for n in range(number):

...        fac.append(fac[-1] + fac[-2])

...     return fac

...

>>> help(facfunction)

Help on function facfunction in module __main__:

facfunction(number)

    caculate fac number

原文地址:https://www.cnblogs.com/lnlvinso/p/3888452.html