python基础教程学习笔记五

第五章 条件 循环和其他语句
Print 和import 的更多信息
使用逗号输出
>>> print('age:',32)
age: 32


两条打印语句在同一行输出:
>>> name='retacn'
>>> saluation='mr.'
>>> greeting='hello'
>>> print(greeting,saluation,name)
hello mr. retacn
>>> print(greeting+',',saluation,name)
hello, mr. Retacn


把某事件作为另一事件导入
从模块导入函数
Import somemodule
from somemodule import somefunction
From somemodule import somefunction,anotherfunction,yetanotherfunction
From somemodule import *
如果两个模块拥有同一函数,
可以使用第一种方式导入,引用方式如下
Module1.open()
Module2.open()


可以给模块设置别名,或是给函数设置别名,示例代码如下:
Import math as foobar
Foobar.sqrt(4)


From math import sqrt as foobar
Foobar(3)


赋值魔法
序列解包
多个赋值操作同时进行
>>> x,y,z=1,2,3
>>> print(x,y,z)
1 2 3


变量交换
>>> x,y=y,x
>>> print(x,y,z)
2 1 3


链式赋值,将同一个值,赋值给多个变量
>>> x=y=1
>>> print(x,y)
1 1


增量赋值
>>> x=2
>>> x+=1
>>> x*=2
>>> x
6


语句块
冒号表示语句块的开始,当回退到和已闭合的块一样的缩进量里,表示结束
This is a line
This is a another line:
This is another block
Continuing the same block
The last line of this block
Rhere we escaped the inner block






条件和条件语句
下面的值在作为布尔表达式的时候,会被解释器看作是false
False none 0 “” () [] {}


If条件语句
name=input('what is your name?')
if name.endwith('retacn'):
If name.startwith(‘mr’)
print("hello,mr.retacn!")
Else:
Print(‘hello,retacn’)
Elif name.endwith(‘yue’):
Print(‘hello,mr.yue’)
Else :
Print(‘hello,stranger’)


比较运算符:
==
>
<
>=
<=
!=
Is
Is not
In
Not in


布尔运算符
And
Or 
Not 


断言 assert






循环
#while循环
>>> x=1
>>> while x<=100:
print(x)
x+=1


# for 循环
>>> words=['this','is','an','ex','parrot']
>>> for word in words:
print(word)


#循环遍历字典元素
>>> d={'x':1,'y':2,'z':3}
>>> for key in d:
print (key,'corresponds to',d[key])
y corresponds to 2
x corresponds to 1
z corresponds to 3
#也可以使用序列解包的方式:
>>> for key,value in d.items():
print(key,'corresponds to',value)


并行迭代
>>> names=['retacn','yue']
>>> ages=['32','33']
>>> for i in range(len(names)):
print(names[i],'is',ages[i],'years old')



retacn is 32 years old
yue is 33 years old


>>> for name,age in zip(names,ages):
print(name,'is',age,'years old')



retacn is 32 years old
yue is 33 years old




编号迭代
For index,string in enumerate(strings):
If ‘xxx’ in string:
Strings[index]=[‘changeWord’]


跳出循环 
Break
continue


列表式推导式 轻量级循环
>>> [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]






三人行
Pass 程序什么都不作,示例代码如下:
If name==’retacn’
Print(‘wlecome’)
Else:
Pass




Del 会移除对象的引用,也会移除那个名这本身
exec

原文地址:https://www.cnblogs.com/retacn-yue/p/6194206.html