if陳述句
- if陳述句的基本用法
if 運算式:
陳述句塊
運算式中可以是一個單純的布林值或者變數,也可以是比較運算式或邏輯運算式(例如:a>b and a!=c),如果運算式為真,則執行陳述句塊:如果運算式為假,就跳過陳述句塊,繼續執行后面的陳述句,
a=1
b=2
if(a<b)
print(a+b)
and表示并且or表示或者
if…else 陳述句的基本用法如下:
if 運算式:
陳述句塊 1
else:
陳述句塊 2
使用 if…else 陳述句時,運算式可以是一個單純的布林值或變數,也可以是比較運算式或 邏輯運算式,如果滿足條件,則執行 if 后面的陳述句塊,否則,執行 else 后面的陳述句塊,在 使用 else 陳述句時,else 一定不可以單獨使用,它必須和保留字 if 一起使用,
if…elif…else陳述句
- if…elif…else 陳述句的基本用法如下:
if 運算式 1:
陳述句塊 1
elif運算式 2:
陳述句塊 2
elif運算式 3:
陳述句塊 3
else:
陳述句塊 n
使用 if…elif…else 陳述句時,運算式可以是一個單純的布林值或變數,也可以是比較表達 式或邏輯運算式,如果運算式為真,執行陳述句;而如果運算式為假,則跳過該陳述句,進行下 一個 elif 的判斷,只有在所有運算式都為假的情況下,才會執行 else 中的陳述句,
While 回圈
while回圈,只要條件為真,會一直執行,
示例
只要i小于10,列印i:
i = 1
while i < 10:
print(i)
i += 1
注意: 記住增加i,否則回圈將永遠執行,
接下來是示例代碼
- 第一個游戲石頭剪子布,這個是if elif else 的示范代碼
import random
print('請輸入石頭剪子布')
print('石頭為0 剪子為1 布為2')
user=int(input('enter: '))
computer=random.randint(0,2)
if(user == 0 and computer == 0):
print("平局")
elif(user == 0 and computer == 1):
print("人獲勝")
elif(user == 0 and computer == 2):
print("計算機獲勝")
elif(user == 1 and computer == 0):
print("計算機獲勝")
elif(user == 1 and computer == 1):
print("平局")
elif(user == 1 and computer == 2):
print("人獲勝")
elif(user == 2 and computer == 0):
print("人獲勝")
elif(user == 2 and computer == 1):
print("計算機獲勝")
elif(user == 2 and computer == 2):
print("平局")
- 判斷質數
a=int(input('enter:'))
for i in range(2,a):
if a%i==0:
print('不是質數')
break
else:
print('a是質數')
break
一定要加break否則輸進去大的數字會一直回圈
- 輸出1000以內的水仙花數
i = 100
a = 0
b = 0
c = 0
number =0
print('1000的以內水仙花數:')
while i < 1000:
a = i //100
b = (i - a *100 ) // 10
c = (i % 10)
if i == a ** 3 + b ** 3 + c ** 3 :
print(i)
i += 1
如果覺得寫的不錯給個關注球球了!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/253009.html
標籤:其他
