Python第四天 流程控制 if else條件判斷 for循環 while循環

Python第四天   流程控制   if else條件判斷   for循環 while循環

 

 

目錄html

Pycharm使用技巧(轉載)java

Python第一天  安裝  shell  文件python

Python次日  變量  運算符與表達式  input()與raw_input()區別  字符編碼  python轉義符  字符串格式化web

Python第三天 序列  5種數據類型  數值  字符串  列表  元組  字典正則表達式

Python第四天   流程控制   if else條件判斷   for循環 while循環shell

Python第五天   文件訪問    for循環訪問文件    while循環訪問文件   字符串的startswith函數和split函數數據庫

Python第六天   類型轉換express

Python第七天   函數  函數參數   函數變量   函數返回值  多類型傳值    冗餘參數   函數遞歸調用   匿名函數   內置函數   列表表達式/列表重寫django

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去取下一個值

相關文章
相關標籤/搜索