Python快速学习第四天

    xiaoxiao2025-03-06  6

    第四天:

    条件 、循环和其他语句

    1、    print

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

    >>> print 'tanggao ',20

    tanggao  20

    >>> 1,2,3

    (1, 2, 3)

    >>> print 1,2,3

    1 2 3

    >>> print(1,2,3)

    (1, 2, 3)

     

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

     

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

    importsomemodule

    fromsomemodule import somefunction

    fromsomemodule import somefunction , anotherfunction ....

    fromsomemodule import *  

     

    3、   序列解包

    多个赋值同时进行

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

    >>> print x,y,z

    1 2 3

    >>> 

     

    交换变量

    >>>x,y=y,x

    >>>print x,y,z

    21 3

    4、   链式赋值

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

    >>> x

    [1, 2, 3]

    >>> y

    [1, 2, 3]

     

    5、 增量赋值

    >>> x=2

    >>> x+=1

    >>> x*=2

    >>> x

    6

       字符串类型也适用

    >>> str='tang'

    >>> str+='gao'

    >>> str*=2

    >>> str

    'tanggaotanggao'

     

     

     

    语句块:

    缩排的乐趣,语句块实在条件为真时(条件语句)时执行或者执行多次(循环语句)的一组语句

    在代码前放置空格来缩进语句即可创建语句块,在python中用冒号(:)用来标识语句快的开始巨快中的每个语句都是缩进相同的

     

    条件和条件语句

    布尔变量

    真值

    下列值作为布尔表达式会被解释器看做假:

    False  None  0  “”  ()  []  {}

    标准值False ,None,所有类型的数字0,空序列(列表,元组,字符串,空字典)都为假,其他一切都解释为真(True)

    (0,1)与(False,True):

    >>> True

    True

    >>> False

    False

    >>> True==1

    True

    >>> False==1

    False

    >>> True+False+42

    43

    布尔值属于布尔类型;bool函数可以用来转换其他值

    >>> bool('i think , therefore i am')

    True

    >>> bool(42)

    True

    >>> bool("")

    False

    >>> bool(0)

    False

    条件执行和if语句

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

    if name.endswith('chen'):

        print ('hello ,mr.chen')

    >>> 

    what is your name?chen

    hello ,mr.chen

    >>> 

    else子句

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

    if name.endswith('chen'):

        print ('hello ,mr.chen')

    else:

        print ('hello,stranger')

    >>> 

    what is your name?qqq

    hello,stranger

    >>> 

    elif子句-----检查多个条件,后面带条件

    num=input('input a number: ')

    if num>'0':--------’0’表示字符串,输入赋值时是字符串

        print ('the number is positive.')

    elif num<'0':

        print ('the number is negative.')

    else:

        print ('the number is zero.')

    嵌套代码块----类似C语言了

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

    if name.endswith('chen'):

        if name.startswith('mr.'):

            print ('hello,mr.chen')

        elif name.startswith('mrs.'):

            print ('hello ,mrs.chen')

        else:

                print ('hello ,chen')

    else:

        print ('hello ,stranger')

     

    >>> 

    what is your name?chen

    hello ,chen

    >>> 

    what is your name?mr.chen

    hello,mr.chen

    >>> 

    what is your name?rrr

    hello ,stranger

    >>> 

    更复杂的条件

    is:同一性运算符,而不是相等性,同一对象

    in:成员资格运算符

    name=input('what is your name ')

    if 's' in name:

        print ("true")

    else:

        print ("false")

    字符串和序列的比较

    字符串可以按照字母顺序排列进行比较

    >>> "alpha"<"beta"

    True----------------------从第一个字母开始,如果大就不再进 行 下去

     布尔运算符

    nu=input ('input a number (1-10): ')

    if '1'<=nu<='10'://nu<=10 and nu>=1

        print ('true')

    else:

        print ('false')

    and 就是所谓的布尔运算符,连接连接两个布尔值,两者为 真返回真,否假,同类 or和not

    断言--------要求某些条件必须为真,使用assert

    >>> assert 0<age <100

    >>> age=-2

    >>> assert 0<age<100

    Traceback (most recent call last):

      File "<pyshell#9>", line 1, in <module>

        assert 0<age<100

    AssertionError

    >>> assert 0<age<100,'false'

    Traceback (most recent call last):

      File "<pyshell#10>", line 1, in <module>

        assert 0<age<100,'false'----------条件后可以添加字符串 解释断言 AssertionError: false

    >>> 

    ------要确保程序中的某个条件一定为真才能让程序正常工 作,assert 就很有用

    循环

    while循环

    x=1

    while x<=100:

        print (x)

        x+=1

    name=''

    while not name or name.isspace(): 

        name=input('please enter your name: ')

    print ('hello,%s!' % name)------输入回车,一直提示输入,直到输入为 止,连输入空格也一样

    for循环

    w=['hello',',','xi','men']

    for word in w:

        print (word)

     

    n=[0,1,2,3,4,5,6,7,8,9]

    for number in n:

        print (number)

     

    range(0,10)

    [0,1,2,3,4,5,6,7,8,9]----内建范围函数

    Range函数类似分片,范围=>0,没上限

    >>> for number in range(1,100):

    print (number)------输出1到99

     

    循环遍历字典元素

    d={'x':1,'y':2,'z':3}

    for key in d:

        print(key,'corresponds to',d[key])

    z corresponds to 3

    x corresponds to 1

    y corresponds to 2

    ------从输出可以看出,字典唯一对应的是键值,输出顺序随机,并无 固定顺序

     

    d={'x':1,'y':2,'z':3}

    for key,values in d.items():

        print(key,'corresponds to',values)

    x corresponds to 1

    y corresponds to 2

    z corresponds to 3

    ------对顺序有要求时,items会将键值作为元组返回,然后便可顺序 输出,因为元组是不可变序列,只能xyz顺序输出

     

    迭代工具

    并行迭代

    n=['chen','xi','tu','er']

    age=[18,19,201,21]

    for i in range(len(n)):------len(n)取n=4,带入range 得0<= <4范围

        print (n[i],'is',age[i],'years old')

    chen is 18 years old

    xi is 19 years old

    tu is 201 years old

    er is 21 years old

     

    Zip函数进行并行迭代,可以把两个序列压缩在一起,返回一个元组

    >>> n=['chen','xi','tu','er']

    >>> age=[18,19,201,21]

    >>> list(zip(n,age))

    [('chen', 18), ('xi', 19), ('tu', 201), ('er', 21)]

    在循环中解包元组:

    n=['chen','xi','tu','er']

    age=[18,19,201,21]

    for i in zip(n,age):

        print (n,'is',age,'years old')

    编号迭代

     

    -----获取迭代对象的同时,还获取当前对象的索引

    在一个字符串列表中替换包含’abc’的子字符串

    1---------

    strings=['abcd','abd','acd','abc']

    for string in strings:

        if 'abc' in string:

            index=strings.index(string)

            strings[index]='[ddddd]'

    print(strings)

    enumerate-------在提供索引的地方迭代索引-值对

    翻转和排序迭代

    reversed,sorted函数

    -----返回翻转或排序后的版本

    >>> sorted([4,3,5,6,7])

    [3, 4, 5, 6, 7]

    >>> sorted('hello,world')

    [',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

    >>> list(reversed('hello,world'))

    ['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']

    >>> ''.join(reversed('hello,world'))

    'dlrow,olleh'

    -----sorted返回列表,reversed返回可迭代对象,不能直接对他使 用索引,分片以及调用list方法

     

    跳出循环

    Break

    -----结束(跳出)循环可以使用break语句

    from math import sqrt

    for n in range(99,0,-1):------------1为反向迭代步长参数

        root=sqrt(n)

        if root==int(root):

            print (n)

            break

    ------从100往下倒0,找到一个平方数就不再继续循环

     

    Continue

    ----跳过剩余循环体,但不结束循环

     

    While true/break

    word=input('please input a word: ')

    while word:

        word=input('please input a word: ')

        print ('the word was '+word)

    word=input('please input a word: ')

     

    ------输入单词,不输入结束循环

    改善:

    while True:

        word=input('please input a word: ')

        if not word:break

        print ('the word was '+word)

    While True实现永远不会自己停止的循环

    循环中的else子句

    from math import sqrt

    for n in range(99,81,-1):

        root=sqrt(n)

        if root==int(root):

            print (n)

            break

    else:----------仅在没有调用break执行

        print ("didn't find it")

    >>> 

    didn't find it

    >>> 

    ------for,while中都可以使用continue,break,else

     

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

    -----利用其他列表创建新列表,类似for

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

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

    >>> 

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

    [0, 9, 36, 81]

     

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

    >>> 

    类比:

    a=[]

    for x in range(3):

        for y in range(3):

            a.append((x,y)

     

    >>> word=['1A','3B','3C','2D']

    >>> number=['1a','2b','3c','4d']

    >>> [b+'+'+g for b in number for g in word if b[0]==g[0]]

    ['1a+1A', '2b+2D', '3c+3B', '3c+3C']

    >>> -------连接首字母相同的元素

     

    三人行

    pass,del,exec

    Pass---做占位符

    del

    --------移除一个对象的引用和名字

    >>> x=['hello','world']

    >>> y=x

    >>> del x

    >>> y

    ['hello', 'world']

    >>> 

    ------x和y指向同一列表,删除x只是删名称,而不是值本 身,python是没办法删除值得,解释器会自动回收内存

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

    exec

    -------执行一个字符串的函数(python 3.0),动态创建 代码字符串

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

    hello,world

    -----简单的使用不妥当,要声明一个命名空间放置变量,从而不改变你的变量

    in<scope>----起到放置代码字符串命名空间作用的字典

    from math import sqrt

    scope={}

    exec ‘sqrt=1’ in scope

    sqrt(4)

    2.0

    scope[‘sqrt’]--------不会覆盖原sqrt函数,通过exec 赋值的变量只在它的作用域内有效

    1

    eval

    ------用于求值,计算python表达式,并返回结果值

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

    input an arithmetic expression: 5+9

    14

    >>> 

    -------也可使用命名空间,可以给eval提供两个命名空间, 一个全局一个局部,全局必须是字典,局部可以为任何形式 的映射

    scope={}

    scope['x']=2

    scope['y']=3

    print(eval ('x*y',scope))----在使用命名空间前放入值进 去

    转载请注明原文地址: https://ju.6miu.com/read-1296932.html
    最新回复(0)