標籤:lse 多行 結束 secret 空格 運行 span 換行 bsp
1. if的格式
>>> 1<3
True 真
>>> 1>3
False 假
if 條件: 條件 + :
(tab)執行語句
(tab)執行語句 前置tab為if條件下執行trun(真)
.....
else:
(tab) 執行語句 執行false(假)
.......
判斷輸入數字是否為8
1 print(‘hi‘)2 temp= input (" number?")3 guess=int(temp)4 if guess==8:5 print("yes")6 else:7 print("on")8 print("88")9
添加大小提示 注意縮排
1 print(‘hi‘) 2 temp= input (" number?") 3 guess=int(temp) 4 if guess==8: 5 print("yes") 6 else: 7 if guess>8: 8 print("+") 9 else:10 print("-")11 print("88")12
2.while
while 條件:
條件為真(true)時執行
限定次數
1 print(‘hi‘) 2 temp= input (" number?") 3 guess=int(temp) 5 while guess != 8: 6 temp= input ("nonono") 7 guess=int(temp) 8 if guess == 8: 9 print("yes")10 else:11 if guess>8:12 print("+")13 else:14 print("-")16 print("88")
3. and or
python3中一行可以寫多個語句,使用“;”隔開。
舉例如:a = 4;c = 5
python3中一個語句可以分為多行書寫,使用反斜線‘\’或者使用括弧分解成幾行
print(‘I love \
python‘)
或
>>> ( I love and
python )
print\
("hh")
隨機數需要random模組,random.randint(a,b) 從a到b的隨機整數
為使用者提供三次機會嘗試,機會用完或者使用者猜中答案均退出迴圈
1 import random 2 times = 3 3 secret = random.randint(1,5) 4 print ("--------歡迎來到猜數字遊戲--------\n") 5 guess = 0 6 print ("猜一下1-5中的哪個值?:",end=" ") print預設是列印一行,結尾加換行。end=" "意思是末尾不換行,加空格 7 while (guess != secret) and (times > 0) : 8 guess = int(input()) 與c的scanf相同,可不輸出字串 9 times = times - 1 10 if guess == secret: 11 print("\n猜對了,你是怎麼這麼利害?!!\n") 12 print("但是猜對了也沒有獎勵\n") 13 else: 14 if guess > secret: 15 print("\n大了大了~\n") 16 else: 17 print("\n呵呵 小了~\n") 18 if times > 0: 19 print("再試一次把: ",end=" ") 20 else: 21 print("3次機會都用光了!~\n") 22 print("遊戲結束,不玩了^_^\n")
1 print(‘--------列印一列數字-----------‘)2 tmp = input(‘請輸入一個數字:‘)3 num = int(tmp)4 i = 15 while num:6 print(i)7 i = i + 18 num = num - 1
運行結果,輸入5
--------列印一列數字-----------
請輸入一個數字:5
1
2
3
4
5
1 print(‘--------列印一組符號-----------‘)2 tmp = input(‘請輸入組數:‘)3 fuhao = input(‘請輸入一個符號:‘)4 num = int(tmp)5 while num:6 print(‘ ‘ * num + fuhao * num) 重複num次空格與num次符號7 num = num - 1
--------列印一組符號-----------
請輸入組數:3
請輸入一個符號:0
000
00
0
寫一個程式,判斷給定年份是否為閏年。
1 temp = input(‘請輸入一個年份:‘) 2 while not temp.isdigit(): 3 temp = input("抱歉,您的輸入有誤,請輸入一個整數:") 4 5 year = int(temp) 6 if year/400 == int(year/400): 7 print(temp + ‘ 是閏年!‘) 8 else: 9 if (year/4 == int(year/4)) and (year/100 != int(year/100)):10 print(temp + ‘ 是閏年!‘)11 else:12 print(temp + ‘ 不是閏年!‘)
python 02 if while