1.if語句
**語法:
if 條件1:(條件為真,執行縮排的語句塊)
if 條件2:(巢狀語句)
條件真縮排語句塊
else:(條件為假時執行)
條件假縮排語句塊
其餘語句
**多分支結構:
if 條件1:
語句塊1
elif 條件2:
語句塊2
#條件1不成立條件2成立時執行
elif 條件3:
語句塊3
else: #注意 else 一定要放在最後
語句
1.
while迴圈
三條件缺一不可:
初始值 | 迴圈條件 | 迴圈變數
*迴圈體外設定迴圈可執行的初始條件
*書寫需要重複執行的**(迴圈體)
*設定迴圈條件並且在迴圈體內部設定條件改變語句 (#很重要,否則很容易進入死迴圈)
#coding:utf-8
count = 1
while
count
<5:
print("so cold!") #重複執行的語句
count +=1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
so cold!
so cold!
so cold!
so cold!
process finished with exit code 0
***************************
2.常見的死迴圈
(1)count = 0
while
count
< 10:
print count
(2)count = 0
while
count
< 10:
print count
count -= 1
(3)count = 0
while
count
< 10:
print count
count +=1
(4)count = 0
while
count
< 10:
ifcount%2 ==0:
print count
(5)count = 0
while
count
< 10:
ifcount%2 ==0:
print count
(6)count = 0
while
count
< 10:
ifcount%2 == 0:
print count
***計算一元二次方程的解
#coding:utf-8
import math
while true:
a=float(raw_input("please enter a:"))
b=float(raw_input("please enter b:"))
c=float(raw_input("please enter c:"))
if a != 0:
delta = b**2 - 4*a*c
if delta < 0:
print("no solusion")
elif delta == 0:
s = -b/(2*a)
print ("s:"),s
else:
root=math.sqrt(delta)
s1 = (-b + root) / (2*a)
s2 = (-b - root) / (2*a)
print ("two distinct solusion are:"),s1,s2
ch=raw_input("q")
if ch == 'q':
break
***********************************
3.break 結束當前迴圈體
count = 0
while
count
< 5:
ifcount > 2:
break
#結束當前迴圈體
print('hello nihao !')
count +=1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
hello nihao !
hello nihao !
hello nihao !
process finished with exit code 0
******************************
4.continute 結束當次迴圈
count = 0
while
count
< 5:
count += 1
ifcount > 2:
continue
#j結束當次迴圈,不再進行print判斷
print("so cold today!")
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
so cold today!
so cold today!
process finished with exit code 0
語法:
for 變數 in 物件: #列舉物件中的每乙個元素
縮排語句塊(迴圈體)
#依次的遍歷物件中的每乙個元素,並賦值給變數,然後執行迴圈內的語句
#計算1+2+3+...+10的值
s = 0
for i in range(1,11):
s += i
print("sum is :",s)
sum is : 55
在mathm模組中,math.factorial()可以用來計算階乘
#求π的值
pi = 0
sign = 1
divisor = 1
for i in range(1,1000000):
pi += 4.0*sign / divisor
sign *= -1
#符號轉換
divisor += 2
print("pi is ",pi)
pi is 3.1415936535907742
format函式可以實現對齊
#猜測平方根
x = 2
low = 0
high = x
guess = (low + high) / 2
while
abs(guess ** 2 - x) > 0.001 :
if guess ** 2 > x :
high = guess
else :
low = guess
guess = (low + high) / 2
print (guess)
#次情況不能輸入小於1的數,考慮該如何解決
Python程式控制結構例項
一 編寫程式,生成乙個包含50個隨機整數的列表,然後刪除其中所有奇數。from random import ls for i in range 50 a randint 1,1000 if a 2 0 print ls 二 水仙花數 是指乙個三位整數,其各位數字的3次方和等於該數本身。例如 abc是...
Python入門(五) 程式控制結構
迴圈結構 順序結構只要按照解決問題的順序寫出相應的語句即可,是最簡單也是最常用的程式結構,執行順序是自上向下,依次執行。計算機之所以可以做許多自動化的任務,乙個重要的原因在於它可以通過特定語法自行判斷。分支結構其實就是根據判斷條件結果而選擇不同向前路徑的執行方式。使用方式如下 if 條件 語句塊 w...
python 3 程式控制結構
程式設計中的三種程式執行結構流程 順序結構 選擇結構和迴圈結構。1.python提供了乙個關鍵字pass,執行該語句的時候什麼也不會發生,可以用在選擇結構 函式和類的定義中,表示空語句。如果暫時沒有確定如何實現某個功能,或者只是想為以後的軟體公升級預留一點空間,可以使用pass關鍵字進行 佔位 2....