Python第四天 流程控制 if else条件判断 for循环 while循环

Python第四天   流程控制   if else条件判断   for循环 while循环

目录

Pycharm使用技巧(转载)

Python第一天  安装  shell  文件

Python第二天  变量  运算符与表达式  input()与raw_input()区别  字符编码  python转义符  字符串格式化

Python第三天 序列  5种数据类型  数值  字符串  列表  元组  字典

Python第四天   流程控制   if else条件判断   for循环 while循环

Python第五天   文件访问    for循环访问文件    while循环访问文件   字符串的startswith函数和split函数

Python第六天   类型转换

Python第七天   函数  函数参数   函数变量   函数返回值  多类型传值    冗余参数   函数递归调用   匿名函数   内置函数   列表表达式/列表重写

Python第八天  模块   包   全局变量和内置变量__name__    Python path

Python第九天  面向对象  类定义   类的属性    类的方法    内部类   垃圾回收机制   类的继承 装饰器

Python第十天   print >> f,和fd.write()的区别    stdout的buffer  标准输入 标准输出  标准错误   重定向 输出流和输入流

Python第十一天    异常处理  glob模块和shlex模块    打开外部程序和subprocess模块  subprocess类  Pipe管道  operator模块   sorted函数   生成器  walk模块   hashlib模块

Python第十二天     收集主机信息     正则表达式  无名分组   有名分组

Python第十三天   django 1.6   导入模板   定义数据模型   访问数据库   GET和POST方法    SimpleCMDB项目   urllib模块   urllib2模块  httplib模块  django和web服务器整合  wsgi模块   gunicorn模块

Python第十四天 序列化  pickle模块  cPickle模块  JSON模块  API的两种格式

Python第十五天  datetime模块 time模块   thread模块  threading模块  Queue队列模块  multiprocessing模块  paramiko模块  fabric模块  

Python流程控制


函数,循环,if条件,类定义等后面有block,block要缩进,因此这些语句后面要加上冒号,这是python的语法
python的冒号和java、c中的{}是一样的
block是一组语句
注:Python使用缩进作为其语句分组的方法,建议使用4个空格


#!/usr/bin/python

score = int(raw_input("Please input a num: "))
if score >= 90:
print 'A'
print 'very good'
elif score >= 80:
print 'B'
print 'good'
elif score >= 70:
print 'C'
print 'pass'
else:
print 'D'

print 'End'



条件判断


逻辑值(bool)包含了两个值:
- True:表示非空的量(比如:string,tuple,list,set,dictonary),所有非零数。
- False:表示0,None,空的量等。


elif语句:
- if expression1:
statement1(s)
elif expression2:
statement2(s)
else:
statement2(s)

if else判断例子

#!/usr/bin/python

score = int(raw_input("Please input a num: "))
if score >= 90:
    print 'A'
    print 'very good'
elif score >= 80:
    print 'B'
    print 'good'
elif score >= 70:
    print 'C'
    print 'pass'
else:
    print 'D'

print 'End'

raw_input输入是字符串,需要用int()函数进行转换

循环



print 相当于Linux的echo命令
print  xx ,   加一个逗号不会换行,默认会换行

bb=['w','e']

for i in bb:
    print i,
w e




range函数 相当于Linux的seq 命令
range(start,stop,step)    倒序range(10,0,-1)
range可以快速的生成一个序列,返回是一个列表
range(I, j, [,步进值])
- 如果所创建对象为整数,可以用range
- i为初始值,不选默认为0
- j为终止值,但不包括在范围内
- 步进值默认为1.


xrange
生成一个可迭代的对象
xrange(start,stop,step)-> xrange object
a = xrange(10)
for i in xrange(10): print i

xrange只有在我们取的时候才生成值,更好的利用系统性能
    print (range(1,10))
    print (xrange(1,10))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    xrange(1, 10)







for循环
for
else
for循环如果正常结束,才会执行else语句。

列表重写法/列表生成式

#!/usr/bin/python

for i in range(1,11):
    if  i % 2 != 0:
        print i*2,
    
等价于
列表重写
print [i*2 for i in range(1,11)  if i % 2 != 0]



break
continue
pass:什么都不做,占位
exit():相当于shell里的exit命令,需要导入sys模块

#!/usr/bin/python

import sys
import time

for i in xrange(10):
if i == 3:
continue
elif i == 5:
continue
elif i == 6:
pass
elif i == 7:
sys.exit()
print i
else:
print 'main end'
print "hahaha"


在ipython里导入模块
In [9]: import random  随机数

In [10]: random.
random.BPF random.SystemRandom random.expovariate random.lognormvariate random.sample random.vonmisesvariate
random.LOG4 random.TWOPI random.gammavariate random.normalvariate random.seed random.weibullvariate
random.NV_MAGICCONST random.WichmannHill random.gauss random.paretovariate random.setstate
random.RECIP_BPF random.betavariate random.getrandbits random.randint random.shuffle
random.Random random.choice random.getstate random.random random.triangular
random.SG_MAGICCONST random.division random.jumpahead random.randrange random.uniform

In [10]: random.ra
random.randint random.random random.randrange

In [10]: random.randint(1,6)
Out[10]: 3

In [11]: random.randint(1,6)
Out[11]: 2


python内置函数,不需要导入模块就可以用的函数
https://docs.python.org/2/library/functions.html

Built-in Functions
abs()
all()
any()
basestring()
bin()
bool()
bytearray()
callable()
chr()
classmethod()
cmp()
compile()
complex()
delattr()
dict()
dir()
divmod()
enumerate()
eval()
execfile()
file()
filter()
float()
format()
frozenset()
getattr()
globals()
hasattr()
hash()
help()
hex()
id()
input()
int()
isinstance()
issubclass()
iter()
len()
list()
locals()
long()
map()
max()
memoryview()
min()
next()
object()
oct()
open()
ord()
pow()
print()
property()
range()
raw_input()
reduce()
reload()
repr()
reversed()
round()
set()
setattr()
slice()
sorted()
staticmethod()
str()
sum()
super()
tuple()
type()
unichr()
unicode()
vars()
xrange()
zip()
__import__()

while循环
whle循环,直到表达式变为假,才退出while循环,表达式是一个逻辑表达式,必须返回一个True或False。
语法:
while expression:
statement(s)
else
while循环如果正常结束,才会执行else语句。
while...else的语法结构是,while循环正常执行完了会执行else后面的代码
(也就是判断条件正常结束 while i <= 10:),如果没有正常执行完,即遇到了break,则不执行else后面的代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#__author__="huazai"
"""
pycharm 使用指南
Date:2016.08.12
"""

x =''
while x != 'q':
    x = raw_input("Please input something, q for quit: ")
    if not x:
        break
    if x == 'quit':
        continue
    print 'continue'
else:
    print 'world'


在python3中不像python2,这些内建函数range,map,filter,zip,dict.values 等返回的都是迭代器,遍历是每次通过next去取下一个值

原文地址:https://www.cnblogs.com/lyhabc/p/6290391.html