在 python 中,while … else 在迴圈條件為 false 時執行 else 語句塊:
#!/usr/bin/python
count= 0
while
count
<
5:
count, "
is less than 5"
count
= count+ 1
else
:
count, "
is not less than 5"
以上例項輸出結果為:
0numbers=[1,2,3,4,5]isless than 51
isless than 52
isless than 53
isless than 54
isless than 55
isnot
less than
5
even=[ ]
odd=[ ]
while len(numbers)>0:
number=numbers.pop()
if(number%2==0):
else:
猜大小的遊戲
#!/usr/bin/python# -*- coding: utf-8 -*-
import
randoms =
int(
random
.uniform(1
,10))#print(s)m =
int(
input
('輸入整數:'
))while
m !=s:
ifm
>s:
('大了')m
=int
(input
('輸入整數:'
))if
m print
('小了')m
=int
(input
('輸入整數:'
))if
m ==s:
('ok'
)break
;
猜拳小遊戲
#!/usr/bin/python測試結果:# -*- coding: utf-8 -*-
import
random
while1:
s =int(
random
.randint(1
,3))if
s ==1:
ind
="石頭"
elif
s ==2:
ind
="剪子"
elif
s ==3:
ind
="布"m =
raw_input
('輸入 石頭、剪子、布,輸入"end"結束遊戲:'
)blist =[
'石頭'
,"剪子"
,"布"]if
(m notin
blist
)and(m
!='end'
"輸入錯誤,請重新輸入!"
elif(m
notin
blist
)and(m
=='end'
"\n遊戲退出中..."
break
elif
m ==
ind
"電腦出了: "
+ind
+",平局!"
elif(m
=='石頭'
andind
=='剪子')or
(m =='剪子'
andind
=='布')or
(m =='布'
andind
=='石頭'
"電腦出了: "
+ind
+",你贏了!"
elif(m
=='石頭'
andind
=='布')or
(m =='剪子'
andind
=='石頭')or
(m =='布'
andind
=='剪子'
"電腦出了: "
+ind
+",你輸了!"
輸入搖篩子遊戲石頭、剪子、布,輸入
"end"
結束遊戲:石頭
電腦出了:
石頭,平局!
輸入石頭、剪子、布,輸入
"end"
結束遊戲:石頭
電腦出了:
剪子,你贏了!
輸入石頭、剪子、布,輸入
"end"
結束遊戲:
#!/usr/bin/env python3十進位制轉二進位制# -*- coding: utf-8 -*-
import
random
import
sysimport
time
result =
while
true
:result.(
int(
random
.uniform(1
,7)))result.(
int(
random
.uniform(1
,7)))result.(
int(
random
.uniform(1
,7)))print
result
count =0
index =2
pointstr =""
while
index
>=0:
currpoint
=result
[index
]count
+=currpoint
index -=1
pointstr
+=" "
pointstr
+=str
(currpoint)if
count
<=11:
sys.
stdout
.write
(pointstr
+" -> "
+"小"
+"\n"
)time
.sleep(1
)# 睡眠一秒
else
:sys
.stdout
.write
(pointstr
+" -> "
+"大"
+"\n"
)time
.sleep(1
)# 睡眠一秒
result
=
#!/usr/bin/pythonwhile迴圈 - 九九乘法表# -*- coding: utf-8 -*-
denum
=input
("輸入十進位制數:"
denum
,"(10)"
,binnum =
# 二進位制數
while
denum
>0:
binnum.(
str(
denum %2
))# 棧壓入
denum
//= 2
'= '
,while
len(
binnum
)>0:
import
sys sys
.stdout
.write
(binnum
.pop
())# 無空格輸出print ' (2)'
#!/usr/bin/python這是一些部落格主提供的非常好的例子值得借鑑學習。# -*- coding: utf-8 -*-
#九九乘法表i =
1whilei :
j =1whilej:
printj ,
"*",i ,
" = ",i
*j ,' ',if
i ==j :
break
j +=1if
j >=10:
break
"\n"
i +=1if
i >=10:
break
Python 迴圈語句 while語句的使用
python 中的迴圈語句有 for 和 while。python 迴圈語句的控制結構圖如下所示 while 迴圈 python 中 while 語句的一般形式 while 判斷條件 condition 執行語句 statements 另外,在 python 中沒有 do while 迴圈。例如下面...
python中if語句加while迴圈猜年齡遊戲
while迴圈語法 while 條件 print if語句就是判斷條件,兩者結合後就可以寫猜年齡遊戲 age1 25 定乙個正確年齡 guess true 定乙個變數為真 while guess 為真時執行下面語句 in age int input 輸入年齡 手輸年齡 if in age age1 ...
python之迴圈語句(while語句)
迴圈語句 迴圈語句 說明while 若為真,則迴圈,常與比較運算子使用 for若為真,則迴圈,常與成員運算子使用 continue 終止當前迴圈,進入下一迴圈 break 退出迴圈,執行下一命令 pass 不執行任何操作 while語句可以非常簡單的製造死迴圈 while true print 迴圈...