栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【学习记录】Python零基础入门(五)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【学习记录】Python零基础入门(五)

第五章 Python零基础入门之条件、循环及其他语句

本人自学的主要教材为Magnus Lie Hetland的Beginning Python:From Novice to Professional, Third Edition。

本人只有C++基础,初入Python,如有不足,还请指正。本系列仅作本人记录学习用。

目录

第五章 Python零基础入门之条件、循环及其他语句

前言

一、print与import

1.打印多个参数 

1.1使用多个逗号

1.2使用+号

1.3自定义结束符

2.导入时重命名

二、赋值魔法

2.1序列解包

2.2链式赋值

2.3增强赋值

三、代码块

四、条件语句

1.布尔值

2.elif

3.条件表达式

4.复杂条件

4.1比较运算符

4.2布尔运算符

5.断言

五、循环语句

1.for

2.迭代字典

3.一些迭代工具

4.跳出循环

6.循环中的else语句

六、简单推导

七、三人行

1.pass

2.del

3.exec和eval

总结


前言

本章主要深入讨论几种语句(print、import、赋值语句、条件语句和循环语句),其中会介绍到代码块,最后将介绍列表推导和字典推导。


一、print与import

1.打印多个参数 

1.1使用多个逗号

使用逗号时,会在输出的结果中添加空格。使用逗号可以将不同类型的表达式合并在一起,而+号则不可以。还可自定义分隔符(使用sep)。

#代码示例
>>> print('Age',42)
Age 42
>>> print('Age',42,sep='_')
Age_42

1.2使用+号

使用+号时,会取消输出结果中的空格。还可自定义分隔符。

#代码示例
>>> print('greeting'+','+'Bob')
greeting,Bob

1.3自定义结束符

可以自定义结束字符串,以替换默认的换行符。例如,将结束字符串指定为空字符串,以后就可以继续打印到当前行。

#代码示例
>>> print('Hello,',end='')
Hello,>>> print('world!')
world!

2.导入时重命名

在import语句末尾添加as子句并指定别名。

#代码示例
>>>from module1 import open as open1
>>>from mudule2 import open as open2
>>>import math as foobar

二、赋值魔法

2.1序列解包

序列解包(可迭代对象解包):将一个序列(或者任何可迭代对象)解包,并将得到的值储存在一系列变量中。

利用序列解包可以同时给多个变量赋值。使用这种办法还可以交换多个变量的值。

#代码示例
>>> x,y,z=1,2,3
>>> print(x,y,z)
1 2 3
>>> x,y,z=y,x,z
>>> print(x,y,z)
2 1 3

解包在返回元组的函数或method时很有用,可将返回的元组解包到两个变量中。

#代码示例
>>> scoundrel={'name':'Amy','boyfriend':'Bob'}
>>> key,value=scoundrel.popitem()
>>> key
'boyfriend'
>>> value
'Bob'

 序列解包时,应保证要解包的序列包含的元素个数必须与等号左边列出的目标个数相同,否则将引发异常。

#代码示例
>>> x,y,z=1,2
Traceback (most recent call last):
  File "", line 1, in 
ValueError: not enough values to unpack (expected 3, got 2)
>>> x,y,x=1,2,3,4
Traceback (most recent call last):
  File "", line 1, in 
ValueError: too many values to unpack (expected 3)

可以使用星号运算符(*)收集多余的值,带星号的变量最终包含的是始终是一个列表,在变量和值的个数相同时也是如此。

#代码示例
>>> a,b,*rest=[1,2,3,4]
>>> rest
[3, 4]
>>> a,b
(1, 2)
>>> name="Albus percival Wulfric Brian DUnmledore"
>>> first,*middle,last=name.split()
>>> middle
['percival', 'Wulfric', 'Brian']
>>> first,last
('Albus', 'DUnmledore')
>>> a,*b,c=1,2,3
>>> b
[2]
>>> a,c
(1, 3)

2.2链式赋值

链式赋值可以将多个变量关联到同一个值。

#代码示例
x=y=somefuncion()
#等价于
y=somefunciton()
x=y
#不等价于
x=somefunction()
y=somefunction()

2.3增强赋值

使用增强赋值可使代码量减少,可读性提高。

#代码示例
>>> x=2
>>> x+=1
>>> x
3
>>> x*=2
>>> x
6
>>> fnord='foo'
>>> fnord+='bar'
>>> fnord
'foobar'

三、代码块

代码块指一组语句,通过缩进代码来创建(标准是每级缩进四个空格)。在Python中,使用冒号(:)指出接下来是一个代码块,缩进量与之前相同时,当前代码块结束。

#伪代码示例
>>>this is a line 
>>>this is another line:
>>>    this is another block
>>>    continuing the same block
>>>    the last line of this block
>>>phew, there we escaped the inner block

四、条件语句

1.布尔值

真值称为布尔值。在Python中以下视为假:

Flase        None         0          “”        ()          []          {} 

总结就是标准值Flase和None、各种类型的数值0,空序列以及空映射都被视为假。

实际上True和Flase是1和0的别称。

#代码示例
>>> True==1
True
>>> False==1
False
>>> False==0
True
>>> False+True+42
43

2.elif

相当于C++中的else if。

3.条件表达式

C++中的三目运算符的Python版。

#代码示例
>>> name=input("enter your name: ")
enter your name: Bob
>>> status="friend" if name.endswith("Bob") else "stranger"
>>> status
'friend'

4.复杂条件

4.1比较运算符

需要注意的是is(相同运算符)与==(相等运算符)的区别。

is检查的是两个对象是否相同,是否是同一个对象,而==检查的是两个对象的值是否相等。

#代码示例
>>> x=[1,2,3]
>>> y=[2,4]
>>> x is not y
True
>>> del x[2]
>>> y[1]=1
>>> y.reverse()
>>> x==y
True
>>> x is y
False

字符串与序列的比较实际上是Unicode码的比较。字符是根据顺序值排列的,可以使用函数ord来获取字符的顺序值,作用与chr相反。

#代码示例
>>> ord('A')
65
>>> chr(65)
'A'

4.2布尔运算符

and,or,not。

Python具有短路逻辑。

#代码示例
>>> yourname=input("enter your name: ") or ''
enter your name:
>>> yourname
''

5.断言

断言的实现通过函数assert实现,可以在程序中充当检查点,还可以在条件后添加字符串,对断言做出说明。

#代码示例
>>> age=10
>>> assert 0>> age=-1
>>> assert 0", line 1, in 
AssertionError
>>> assert 0", line 1, in 
AssertionError: the age must be realistic

五、循环语句

1.for
#代码示例
>>>numbers=[1,2,3,4,5,6,7,8,9]
>>>for item in numbers:
>>>    print(item)
1
2
3
4
5
6
7
8
9

Python有内置的创建范围的函数range ,范围左闭右开。

#代码示例
>>> range(0,10)
range(0, 10)
>>> list(range(0,10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>for number in range(10):
>>>    print(number)
0
1
2
3
4
5
6
7
8
9

2.迭代字典

可利用for循环遍历字典的所有关键字。

#代码示例
>>>d={'x':1,'y':2,'z':3}
>>>for key in d:
    print(key,'correspond to',d[key])
x correspond to 1
y correspond to 2
z correspond to 3

可以在fore循环中使用序列解包。

#代码示例
>>>d={'x':1,'y':2,'z':3}
>>>for key,value in d.items():
    print(key,value)
x 1
y 2
z 3

3.一些迭代工具

并行迭代。同时迭代两个序列。有两种做法,第一种是直接迭代,第二种是使用zip。序列长度不同时,zip将在最短的序列用完后终止缝合。

#代码示例
#第一种
>>>names=['anne','beth','geogle','damon']
>>>ages=[12,34,31,101]
>>>for i in range(len(names)):
    print(names[i],ages[i])
anne 12
beth 34
geogle 31
damon 101
#第二种
>>>name_age=list(zip(names,ages))
>>>for name, age in name_age:
    print(name,'is',age,'years old')
anne is 12 years old
beth is 34 years old
geogle is 31 years old
damon is 101 years old

迭代时获取索引。有时需要在迭代对象序列的同时获取当前对象的索引。一种很有效的解决办法是使用内置函数enumerate。

#代码示例
>>>for index, string in enumerate(strings):
>>>    if 'xxx' in string:
>>>        strings[index]='[censored]'

反向迭代和排序后再迭代。使用到内置函数reversed和 sorted。不就低修改对象,返回反转和排序后的版本。sorted返回一个列表,而reversed返回一个神奇的东西,不需要知道这是什么,只需在for循环或join等方法中使用它。不能对其执行索引或切片操作,也不能直接对它调用列表的方法。要执行这些操作,需要用list进行转换。

#代码示例
>>>sorted([4,3,4,5612,5456])
[3, 4, 4, 5456, 5612]
>>>sorted('Hello, World')
[' ', ',', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']
>>>list(reversed('Hello, World'))
['d', 'l', 'r', 'o', 'W', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>>''.join(reversed('Hello, World'))
'dlroW ,olleH'
>>>reversed('Hello, World')

4.跳出循环

break。用法与C++相同。

continue。结束当前迭代,并跳到下一次迭代开头。

#代码示例
>>>for x in seq:
>>>    if condition1: continue
>>>    if condition2: continue
>>>    if condition3: continue

>>>    do_something()
>>>    do_something_else()
>>>    do_another_thing()
>>>    etc()

while true/break。一个应用场景是要在用户根据提示输入单词是执行某种操作,并在用户没有提供单词时结束循环。

#代码示例
>>>while True:
>>>    word=input('please enter a word: ')
>>>    if not word: break
>>>    print('The word is ',word)

6.循环中的else语句

 在循环后添加一条else子句,仅在没有调用break时才执行。

#代码示例
>>>from math import sqrt
>>>for n in range(99,81,-1):
>>>    root=sqrt(n)
>>>    if root==int (root):
>>>        print(n)
>>>        break
>>>else:
>>>    print("Don't find it!")

六、简单推导

列表推导。一种从其他列表创建列表的方式。

#代码示例
>>> [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)]

用圆括号代替方括号,不能实现元组推导,而是创建生成器。

用花括号代替方括号,实现字典推导。

#代码示例
>>> {i:"{} squared is {}".format(i,i**2) for i in range(10)}
{0: '0 squared is 0', 1: '1 squared is 1', 2: '2 squared is 4', 3: '3 squared is 9', 4: '4 squared is 16', 5: '5 squared is 25', 6: '6 squared is 36', 7: '7 squared is 49', 8: '8 squared is 64', 9: '9 squared is 81'}

七、三人行

1.pass

nothing to do。

#代码示例
>>>if name =='Ralph Aulus Melish':
>>>    print('Welcome!')
>>>elif name=='Enid':
       #还未完成
>>>    pass
>>>elif name=='Bill Cates'
>>>    print('Access Denied')

2.del

用del会删除到对象的引用和名称本身。

#代码示例
>>> x=1
>>> del x
>>> x
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'x' is not defined
>>> x=["Hello","World"]
>>> y=x
>>> del x
>>> y
['Hello', 'World']

3.exec和eval

exec将字符串作为代码执行。应该向其传递一个命名空间,用于放置变量。通常提供一个字典作为命名空间。若将字典的键打印出来,会发现有一个__builtins__,这是自动添加了包含所有内置函数和值的字典。

#代码示例
>>> from math import sqrt
>>> scope={}
>>> exec('sqrt=1',scope)
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
>>> len(scope)
2
>>> scope.keys()
dict_keys(['__builtins__', 'sqrt'])

eval计算用字符串表示的Python表达式,并返回结果。

#代码示例
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6+18*2
42

总结

本章主要介绍了多种语句,包括打印语句、导入语句、赋值语句、代码块、条件语句、循环语句、推导以及三个函数。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1008575.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号