目錄
一.if語句
1.1 功能
1.2 語法
1.2.1:單分支,單重條件判斷
1.2.2:單分支,多重條件判斷
1.2.3:if+else
1.2.4:多分支if+elif+else
1.2.5:if語句小結
1.3 案例
1.4 三元表達式
二.while語句
2.1 功能
2.2 語法
2.2.1:基本語法
2.2.2:計數循環
2.2.3:無限循環
2.2.4:while與break,continue,else連用
2.2.5:while語句小結
2.3 案例
三.for語句
3.1 功能
3.2 語法
3.2.1:基本語法
3.2.2:遍歷序列類型
3.2.3:遍歷可迭代對象或迭代器
3.2.4:for基於range()實現計數循環
3.2.5:for與break,continue,else
3.2.6:for語句小結
一.if語句
1.1 功能
計算機又被稱作電腦,意指計算機可以像人腦一樣,根據周圍環境條件(即expession)的變化做出不同的反應(即執行代碼)
if語句就是來控制計算機實現這一功能
1.2 語法
1.2.1:單分支,單重條件判斷
if expression:
expr_true_suite
註釋:expession爲真執行代碼expr_true_suite
1.2.2:單分支,多重條件判斷
if not active or over_time >= 10:
print('Warning:service is dead')
warn_tag+=1
1.2.3:if+else
if expression:
expr_true_suite
else:
expr_false_suite
1.2.4:多分支if+elif+else
if expession1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expession3:
expr3_true_suite
else:
none_of_the_above_suite
1.2.5:if語句小結
if 後表達式返回值爲True則執行其子代碼塊,然後此if語句到此終結,否則進入下一分支判斷,直到滿足其中一個分支,執行後終結if
expression可以引入運算符:not,and,or,is,is not
多重expression爲加強可讀性最好用括號包含
if與else縮進級別一致表示是一對
elif與else都是可選的
一個if判斷最多隻有一個else但是可以有多個elif
else代表if判斷的終結
expession可以是返回值爲布爾值的表達式(例x>1,x is not None)的形式,也可是單個標準對象(例 x=1;if x:print('ok'))
所有標準對象均可用於布爾測試,同類型的對象之間可以比較大小。每個對象天生具有布 爾 True 或 False 值。空對象、值爲零的任何數字或者 Null 對象 None 的布爾值都是 False。
下列對象的布爾值是 False
三元表達式
語法:
expr_true_suite if expession else expr_false_suite
案例一:
>>> active=1
>>> print('service is active') if active else print('service is inactive')
service is active
案例二:
>>> x=1
>>> y=2
>>> smaller=x if x < y else y
>>> smaller
1
二.while語句
2.1 功能
while循環的本質就是讓計算機在滿足某一條件的前提下去重複做同一件事情(即while循環爲條件循環,包含:1.條件計數循環,2條件無限循環)
這一條件指:條件表達式
同一件事指:while循環體包含的代碼塊
重複的事情例如:從1加到10000,求1-10000內所有奇數,服務等待連接
2.2 語法
2.2.1:基本語法
while expression:
suite_to_repeat
註解:重複執行suite_to_repeat,直到expression不再爲真
2.2.2:計數循環
count=0
while (count < 9):
print('the loop is %s' %count)
count+=1
2.2.3:無限循環
count=0
while True:
print('the loop is %s' %count)
count+=1
tag=True
count=0
while tag:
if count == 9:
tag=False
print('the loop is %s' %count)
count+=1
while語句小結
條件爲真就重複執行代碼,直到條件不再爲真,而if是條件爲真,只執行一次代碼就結束了
while有計數循環和無限循環兩種,無限循環可以用於某一服務的主程序一直處於等待被連接的狀態
break代表跳出本層循環,continue代表跳出本次循環
while循環在沒有被break打斷的情況下結束,會執行else後代碼
2.3 案例
用戶登陸驗證
import getpass
account_dict={'alex':'123','eric':'456','rain':'789'}
count = 0
while count < 3:
name=input('用戶名: ').strip()
passwd=getpass.getpass('密碼: ')
if name in account_dict:
real_pass=account_dict.get(name)
if passwd == real_pass:
print('登陸成功')
break
else:
print('密碼輸入錯誤')
count+=1
continue
else:
print('用戶不存在')
count+=1
continue
else:
print('嘗試次數達到3次,請稍後重試')
三.for語句
3.1 功能
for 循環提供了python中最強大的循環結構(for循環是一種迭代循環機制,而while循環是條件循環,迭代即重複相同的邏輯操作,每次操作都是基於上一次的結果,而進行的)
3.2 語法
3.2.1:基本語法
for iter_var in iterable:
suite_to_repeat
註解:每次循環, iter_var 迭代變量被設置爲可迭代對象(序列, 迭代器, 或者是其他支持迭代的對 象)的當前元素, 提供給 suite_to_repeat 語句塊使用.
3.2.2:遍歷序列類型
name_list=['alex','eric','rain','xxx']
#通過序列項迭代
for i in name_list:
print(i)
#通過序列索引迭代
for i in range(len(name_list)):
print('index is %s,name is %s' %(i,name_list[i]))
#基於enumerate的項和索引
for i,name in enumerate(name_list,2):
print('index is %s,name is %s' %(i,name))
3.2.3:遍歷可迭代對象或迭代器
迭代對象:就是一個具有next()方法的對象,obj.next()每執行一次,返回一行內容所有內容迭代完後,
迭代器引發一 個 StopIteration 異常告訴程序循環結束. for 語句在內部調用 next() 並捕獲異常.
for循環遍歷迭代器或可迭代對象與遍歷序列的方法並無二致,只是在內部做了調用迭代器next(),並捕獲異常,終止循環的操作
很多時候你根本無法區分for循環的是序列對象還是迭代器
3.2.4:for基於range()實現計數循環
range()語法:
range(start,end,step=1):顧頭不顧尾
range(10):默認step=1,start=0,生成可迭代對象,包含[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1,10):指定start=1,end=10,默認step=1,生成可迭代對象,包含[1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1,10,2):指定start=1,end=10,step=2,生成可迭代對象,包含[1, 3, 5, 7, 9]
注:for基於range()實現計數循環,range()生成可迭代對象,說明for循環本質還是一種迭代循環
3.2.5:for與break,continue,else
同while
3.2.6:for語句小結
for循環爲迭代循環
可遍歷序列成員(字符串,列表,元組)
可遍歷任何可迭代對象(字典,文件等)
可以用在列表解析和生成器表達式中
break,continue,else在for中用法與while中一致
作業:用戶登錄驗證
表結構:
CREATE TABLE `user_login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '',
`pwd` varchar(20) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
代碼:
#!/usr/bin/python
#-*- coding: utf-8 -*-
import MySQLdb
import sys
sys.path.insert(0,"/etc/dbbin")
from lib import configgetter
getter = configgetter.Configuration("conf/mysql.cfg")
suser = "mysqlha"
spasswd = getter.passget("mysql",suser)
def MysqlSelect(host,port,db,sql,charset="utf8"):
try:
conn = MySQLdb.connect(host=host,port=port,user=suser,passwd=spasswd,db=db)
cursor = conn.cursor()
charsql = "set names %s" %charset
cursor.execute(charsql)
cursor.execute(sql)
result = cursor.fetchall()
return result
except Exception,ex:
print "execute is faild : %s" %sql
ex_info = str(ex)
print ex_info
return 2,ex_info
def UserLogin():
errcode = 0
while True:
name = raw_input('Please input user name:').strip()
pwd = raw_input('Please input user password: ').strip()
namesql = "select name from user_login where name = '%s'" % name
passwdsql = "select pwd from user_login where name = '%s'" % name
name_group = MysqlSelect('10.20.8.1',3488,'tt',namesql)
pwd_group = MysqlSelect('10.20.8.1',3488,'tt',passwdsql)
print errcode
if name_group != ():
if name == name_group[0][0] and errcode == 3:
print "%s user has been locked " % name
continue
if name == name_group[0][0]:
if pwd == pwd_group[0][0]:
print "%s login sucess" % name
break
else:
print "User password error,Please try again"
errcode += 1
else:
print " %s user not exists" % name
break
UserLogin()