pythonelse中的空語句怎麼寫
- 綜合知識
- 關注:1.43W次
Python中用於多個選擇, else if 用 elif表示。
例如:
>>> x = 3
>>> if x<1:
print " x is less than 1. "
elif x<5:
print " x is less than 5. "
elif x<7:
print " x is less than 7. "
else:
print "x is not less than 7. "
該 if 語句從上往下判斷,在第二個判斷上是True, 則執行其對應的語句。 列印出x is less than 5. 之後就忽略掉剩下 elif 和 else.
2.python語言中if與else是如何匹配的python裡不能用括號來表示語句塊,也不能用開始/結束標誌符來表示,而是靠縮排來表示。
if a == 1:
print a
if b == 1:
print b
else
print c上面的這個else是和if b == 1 配對的。
if a == 1:
print a
if b == 1:
print b
else
print c而這個else是和if a == 1 配對的。
3.Python輸入語句python while迴圈語句
python 程式設計中 while 語句用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。其基本形式為:
while 判斷條件:
執行語句……
執行語句可以是單個語句或語句塊。判斷條件可以是任何表示式,任何非零、或非空(null)的值均為true。
當判斷條件假false時,迴圈結束。
例項:
#!/usr/bin/python
count = 0
while (count 0: # 非雙數時跳過輸出
continue
print i # 輸出雙數2、4、6、8、10
i = 1
while 1: # 迴圈條件為1必定成立
print i # 輸出1~10
i += 1
if i > 10: # 當i大於10時跳出迴圈
break
無限迴圈
如果條件判斷語句永遠為 true,迴圈將會無限的執行下去,如下例項:
#coding=utf-8
#!/usr/bin/python
var = 1
while var == 1 : # 該條件永遠為true,迴圈將無限執行下去
num = raw_input("enter a number :")
print "you entered: ", num
print "good bye!"
以上例項輸出結果:
enter a number :20
you entered: 20
enter a number :29
you entered: 29
enter a number :3
you entered: 3
enter a number between :traceback (most recent call last):
file "test.py", line 5, in
num = raw_input("enter a number :")
keyboardinterrupt
注意:以上的無限迴圈你可以使用 ctrl+c 來中斷迴圈。
迴圈使用 else 語句
在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區別,else 中的語句會在迴圈正常執行完(即 for 不是通過 break 跳出而中斷的)的情況下執行,while … else 也是一樣。
#!/usr/bin/python
count = 0
while count
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/6ylvnz.html