条件、循环及其他
1、print和import
1、打印多个参数
print现在是一个函数,但以前是一个语句。它可以用于打印一个表达式,这个表达式要么是字符串,要么自动转换为字符串。
可以同时打印多个表达式,用逗号分隔:
>>> print("abc",123)
abc 123
>>> print("name:","Tom")
name: Tom
输出变量时,涉及到字符串的拼接:
>>> print("abc",123)
abc 123
>>> print("name:","Tom")
name: Tom ##就这样将词拼接为一句话
>>> greeting="hi"
>>> name="Tom"
>>> print(greeting,",",name)
hi , Tom
>>> salutation = "Mr"
>>> print(greeting, ',', salutation, name)
hi , Mr Tom
>>> print(greeting + ',', salutation, name)
hi, Mr Tom ##注意这个输出和上面输出的差别,虽然上面的不会报错,但是就英文的书写,“,”是要紧跟在上一个词后的
>>> print("I", "wish", "to", "register", "a", "complaint", sep="_")
I_wish_to_register_a_complaint ##sep定义了用什么符号将字符串连接
>>> print('Hello,', end='')
Hello,
>>> print('Hello,')
Hello,
>>> print('Hello,', end='666')
Hello,666 ##end自定义了输出以什么结尾,这样可以不换行的连续输出,向下面这样:
print('Hello,', end='')
print('world!')
Hello,world! ##这样就可以把两个输出显示在一行了,不然第一个print后就会换行。
2、导入时重命名
导入模块有线面四种情况:
import somemod
from somemod import somefunc
from somemod import somefuncA,somefuncB,somefuncC
from somemod import *
##只有当确定要导入模块中的全部时采用最后一种语句
如果两个不同的模块包含相同名称的函数时,有两种办法:
##办法1:强关联模块
mod1.func()
mod2.func()
##这种方法在实际操作中会多会多打很多字
##办法2:别名
from mod1 import func as func1
from mod2 import func as func2
##这样在使用函数时就区分开了
##用的时候像这样:
>>> from math import sqrt as s
>>> s(4)
2.0
>>> import math as m
>>> m.sqrt(4)
2.0
2、赋值魔法
1、序列解包
变量赋值可同时给多个变量赋值:
>>> x,y,z=1,2,3
>>> x
1
>>> y
2
>>> z
3
这种方法还可以对变量的值进行交换:
>>> x,y,z=z,x,y
>>> x
3
>>> y
1
>>> z
2
这里面的操作叫 序列解包:将一个序列解包,并将得到的值存储到一些列变量中。
下面的例子解释更清晰:
>>> value=1,2,3 #这种方式可以定义一个元组
>>> x,y,z=value
>>> x
1
>>> y
2
>>> z
3
这在使用返回元组的函数或方法中很有用。比如之前的popitem方法,它随便获取一个键值对并以元组的方式返回,要使用元组中的内容就可以用这种方法;
>>> s= {'name':'Tom','friend':'Jerry'}
>>> k,v=s.popitem() #左边的变量数要和右边的返回元素数相同,不然会报错
>>> k
'friend'
>>> v
'Jerry'
>>> s.popitem() #popitem删除了friend-Jerry组合,剩下的就剩name-Tom了
('name', 'Tom') #你看,返回的是元组
如果只需要2个值,那其他的值可以用*进行收集;
>>> a,b,*rest=(1,2,3,4,5,6)
>>> a
1
>>> b
2
>>> rest
[3, 4, 5, 6]
>>> a,b=(1,2,3,4,5,6) #这里你看就会报错
Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
a,b=(1,2,3,4,5,6)
ValueError: too many values to unpack (expected 2)
带*的变量可以放在任何地方:
>>> w="I am Tom"
>>> fir,*others,las=w.split()
>>> fir
'I'
>>> others
['am']
>>> las
'Tom'
2、链式赋值
x=y=somefun()
##等价于:
y=somefun()
x=y
##不等价于:
x=somefun()
y=somefun()
3、增强赋值
>>> x=1
>>> x=x+1
>>> x
2
>>> x+=1 #这个东西叫增强赋值,还可以是*什么的
>>> x
3
3、缩进
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
4、条件和条件语句
1、布尔值
用作布尔表达式时,下面的值都会被解释器视为“假”:
False None 0 "" () [] {}
其他各种值都被视为“真”,Ture和False就是0和1的别名,作用相同:
>>> True
True
>>> False
False
>>> True == 1
True
>>> False == 0
True
>>> True + False + 42
43
与list、str、tuple一样,bool可转化其他值:
>>> bool('I think, therefore I am')
True
>>> bool(42)
True
>>> bool('')
False
>>> bool(0)
False
2、if语句
name = input('What is your name? ')
if name.endswith('Gumby'):
print('Hello, Mr. Gumby')
3、else子句
name = input('What is your name?')
if name.endswith('Gumby'):
print('Hello, Mr. Gumby')
else:
print('Hello, stranger')
4、elif子句
num = int(input('Enter a number: '))
if num > 0:
print('The number is positive')
elif num < 0:
print('The number is negative')
else:
print('The number is zero')
5、代码块嵌套
name = input('What is your name? ')
if name.endswith('Gumby'):
if name.startswith('Mr.'):
print('Hello, Mr. Gumby')
elif name.startswith('Mrs.'):
print('Hello, Mrs. Gumby')
else:
print('Hello, Gumby')
else:
print('Hello, stranger')
6、复杂条件
与赋值一样,python也支持链式比较:0 < age < 100
7、断言
assert的使用:
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
还可以对断言做出说明:
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: The age must be realistic
5、循环
1、while循环
x = 1
while x <= 100:
print(x)
x += 1
2、for循环
一般用于遍历
words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
print(word)
>>> range(0, 10)
range(0, 10)
>>> list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range和切片一样,包含起始,不包含结束。
一般情况起始位置为0,那就可以简写,只写结束位置:
>>> range(10)
range(0, 10)
要打印1-100的数字:
for number in range(1,101):
print(number)
3、迭代字典
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
for循环还支持序列解包:
for key, value in d.items():
print(key, 'corresponds to', value)
4、迭代工具
1、并行迭代
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print(names[i], 'is', ages[i], 'years old')
zip迭代工具:
>>> list(zip(names, ages)) #用zip进行缝合并用list转换成列表
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
#在循环中进行解包
for name, age in zip(names, ages):
print(name, 'is', age, 'years old')
序列长度不同时,函数zip将在最短序列用完后停止缝合:
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
2、迭代时获取索引
比如,想替换一个字符串列表中包含子串“xxx”的字符串,
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
s = ["asd", "bxxx", "fasd"]
for index, string in enumerate(s):
if "xxx" in string:
s[index] = 'sss'
print(index)
print(s)
执行结果:
1
['asd', 'sss', 'fasd']
Process finished with exit code 0
3、反向迭代和排序后再迭代
指的是函数reversed和sorted的使用
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', '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返回一个可迭代对象。不用关心可迭代对象是什么,只管在for循环或join方法中使用就行。只是不能进行切片、索引操作,如果一定要做,徐要那个list对对象进行转换。
5、跳出循环
1、break
找出小于100的最大平方值:
from math import sqrt
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print(n)
break
break用于结束循环。上例找到后不需再执行,用break结束循环。
2、continue
用的没有break多,用于结束当前迭代,并跳到下一次迭代开头:
for x in seq:
if condition1: continue
if condition2: continue
if condition3: continue
do_something()
do_something_else()
do_another_thing()
etc()
很多情况下只用一条if:
for x in seq:
if not (condition1 or condition2 or condition3):
do_something()
do_something_else()
do_another_thing()
etc()
3、while True/break
while True:
word = input('Please enter a word: ')
if not word: break
# 使用这个单词做些事情:
print('The word was ', word)
这种就是实现小工具不断输入的方式:while Ture让循环永不结束,当满足一定条件时结束当前的循环,并得到一个结果,然后程序继续运行。
6、循环中的else子句
from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print(n)
break
else:
print("Didn't find it!")
6、简单推导
>>> [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)]
相当于:
result = []
for x in range(3):
for y in range(3)
result.append((x, y))
使用多个for部分时,也可添加if子句:
>>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
7、pass、del、exec
1、什么都不做
if name == 'Ralph Auldus Melish':
print('Welcome!')
elif name == 'Enid':
# 还未完成……
pass
elif name == 'Bill Gates':
2、del删除
>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#255>", line 1, in ?
x
NameError: name 'x' is not defined
>>> x = ["Hello", "world"]
>>> y = x
>>> y[1] = "Python"
>>> x
['Hello', 'Python']
>>> del x
>>> y
['Hello', 'Python']
3、exec和eval执行字符串及计算其结果
exec将字符串当做代码执行:
>>> exec("print('Hello, world!')")
Hello, world!
eval用于计算用字符串表示的python表达式的值。
>>> eval(input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6 + 18 * 2
42
结束。