參考鏈接: 用Python鏈接比較運算符
1.if條件判斷語句:?
if 要判斷的條件(True):
? ? 條件成立的時候,要做的事情
elif 要判斷的條件(True):
? ? ....
elif 要判斷的條件(True):
? ? ....
else:
? ? 條件不成立的時候要做的事情
?
示例: 判斷學生分數等級: 100——90(包括90):A 90——80:B 80——70:C 70——0:D?
score = int(input('請輸入學生的分數:'))
if 90 <= score <=100 :
? ? print('A')
elif 80 <= score < 90 :
? ? print('B')
elif 70 <= score < 80 :
? ? print('C')
else :
? ? print('D')
?
2. 邏輯運算符號:?
and
條件1 and 條件2
兩個條件同時滿足,就返回True
只要有一個條件不滿足,就返回False
?
or
條件1 or 條件2
兩個條件只要有一個滿足,就返回True
兩個條件都不滿足的時候,就返回False
?
示例:?
>>> a = 1
>>> b = 2
>>> c = 3? ?# 變量賦值
>>> a < b and b < c? ?# 同時滿足 才為True
True
>>> a < b and b == c? ?# 有一個不滿足即為 False
False
>>> a < b or b == c? ?# 有一個對就是 True
True
>>> a > b or b > c? ?# 只有全部都錯的時候才為? ?False
False
>>>?
?
練習題: 需求: 1.從控制臺輸入要出的拳 —石頭(1)/剪刀(2)/布(3) 2.電腦隨即出拳 3.比較勝負?
import random
# 1.從控制臺輸入要輸出的拳 ---石頭(1)/剪刀(2)/布(3)
player = int(input('請輸入你要出的拳頭:---石頭(1)/剪刀(2)/布(3)'))
# 2.讓電腦隨即出拳
computer = random.randint(1,3)
print('玩家:%d,電腦:%d' %(player,computer))
if ((player == 1 and computer == 2) or
? ? (player == 2 and computer == 3) or
? ? (player == 3 and computer == 1)):
? ? print('玩家勝利~~~')
elif player == computer:
? ? print('平局~~~~')
else:
? ? print('玩家輸了~~~')
?
2.判斷閏年? 用戶輸入年份year, 判斷是否為閏年 year能被4整除但是不能被100整除 或者 year能被400整除, 那么就是閏年;?
year=int(input('請輸入年份: '))
if (year%400 == 0 or (year%4 == 0 and year%100 != 0)) :
? ? print('%d 是閏年' %year)
else :
? ? print('%d 不是閏年' %year)
?
3.隨機選擇一個三位以內的數字作為答案。用戶輸入一個數字,程序會提示大了或是小了.?
import random
user=float(input('please input a number :? '))
sys=random.randint(0, 999)
if user > sys :
? ? print('大于\t' ,end='')
elif user < sys :
? ? print('小于\t' ,end='')
else :
? ? print('等于\t' ,end='')
print(sys)
?
4 . 輸入年、月,輸出本月有多少天。?
year=int(input('請輸入年份:? '))
mon=int(input('請輸入月份:? '))
if mon == 2 :
? ? if (year%400 == 0 or (year%4 == 0 and year%100 != 0)) :
? ? ? ? print('%d 年 %d 月 是29天' %(year,mon))
? ? else :
? ? ? ? print('%d 年 %d 月 是28天' %(year,mon))
elif (mon == 4 or mon == 6 or mon == 9 or mon ==11):
? ? print('%d 年 %d 月 是30天' %(year,mon))
else : print('%d 年 %d 月 是31天' %(year,mon))
?
方法二:?
year=int(input('請輸入年份:? '))
mon=int(input('請輸入月份:? '))
day = [0,31,28,31,30,31,30,31,31,30,31,30,31]
day2 = [0,31,29,31,30,31,30,31,31,30,31,30,31]
if (year%400 == 0 or (year%4 == 0 and year%100 != 0)) :
? ? print('%d 年 %d 月 是%d天' %(year,mon,day2[mon]))
else :
? ? print('%d 年 %d 月 是%d天' %(year,mon,day[mon]))
?
5 . 根據用于指定月份,打印該月份所屬的季節 提示: 3,4,5 春季 6,7,8 夏季 9,10,11 秋季 12, 1, 2 冬季?
Month = int(input('please input the month 1-12? :'))
if (3<= Month <= 5) :
? ? print('%d month is Spring' %Month)
elif (6 <= Month <= 8) :
? ? print('%d month is Summer' %Month)
elif (9<= Month <= 11) :
? ? print('%d month is Autumn' %Month)
else:
? ? print('%d month is winter' %Month