python的结构_Python结构的选择,python,之
python運行符優先級
注:
同一優先級計算順序從右往左
邏輯運算的重要規則
A and B: 當 A 為 False 時,不管 B 為何值,表達式為 False,否則表達式結果為B
A or B: 當 A 為 True 時,不管 B 為何值,表達式為 True,否則表達式結果為B
測試運算符
成員運算符(in、not in)
成員運算符用于在指定的序列中查找某個值是否存在。
n = [1,2,3,4,5,'a']
if 'a' in n:
print('IN')
if 'a' not in n:
print('IN')
else:
print('NOT IN')
# 輸出:
# IN
# NOT IN
身份測試(is、is not)
測試兩個變量是否指向同一對象
n = [1,2,3]
m = n
if n is m:
print('同一對象')
else:
print('不是同一對象')
# 輸出:同一對象
m = [2,2,2]
if n is m:
print('同一對象')
else:
print('不是同一對象')
# 輸出:不是同一對象
條件運算符
格式:
表達式1 if 表達式 else 表達式2
運算規則
先求if后面表達式的值,如果為True,則求表達式1,并以表達式1的值作為條件運算的結果,如果為False,以表達式2的值作為條件運算符結果。
x,y = 40,50
z = x if x==y else y
print('%06.2f'%(z))
#輸出:050.00
選擇結構的實現
選擇和循環結構中,條件表示的值為False的情況有:
Flase、0、0.0、空值None、空序列對象(空列表、空元組、空集合、空字典、空字符串)、空range對象、空迭代對象
單分支選擇結構
if 表達式:
語句塊
雙分支選擇結構
if 表達式:
語句塊
else:
語句塊
多分支選擇結構
if 表達式1:
語句塊
elif 表達式2:
語句塊
elif 表達式3:
語句塊
...
elif 表達式n
語句塊
[else:
語句塊]
最后一個else 可以不寫
選擇結構的嵌套
if 表達式1:
if 表達式2:
語句塊
else:
語句塊
if 表達式1:
if 表達式2:
語句塊
else:
語句塊
還有其他的就省略了
選擇結構程序舉例
水仙花數
輸入一個整數,判斷它是否為水仙花數。所謂水仙花數,指這樣的一些3位整數:各位數字的立方和等于該數本身,例如153 = 1^3 + 5^3 + 3^3 ,因此153是水仙花數。
def fun():
x = int(input("請輸入一個3位數整數"))
# input 函數返回值為字符串,所以需要強制轉換
x1 = x % 100
x2 = (x / 10) % 10
x3 = x % 10
if(x == x1**3 + x2**3 + x3**3):
print('{}水仙花數'.format(x))
else:
print('{}不是水仙花數'.format(x))
return 0
def main():
fun()
main()
輸入:請輸入一個3位數整數153
輸出:153不是水仙花數
時間輸出
輸入一個時間(小時:分鐘:秒),輸出該時間經過5分30秒后的時間。
def fun(hour,minute,second):
second +=30
if second > 60:
second -= 60
minute +=1
minute +=5
if second > 60:
minute -=60
hour +=1
while hour > 24:
hour -= 24
print('{}:{}:{}'.format(hour,minute,second))
def main():
hour = int(input("請輸人小時:"))
minute = int(input("請輸入分鐘:"))
second = int(input("請輸入秒:"))
fun(hour,minute,second)
main()
# 輸入:
# 請輸人小時:8
# 請輸入分鐘:12
# 請輸入秒:56
# 輸出:
# 8:18:26
工資計算
(1)工作時間超過120小時,超過部分加發15%
(2)工作時間低于60小時,扣發700元
(3)其余按84元每小時計發。
輸入員工的工號和該員工的工作時數,計算應發工資:
def fun(gh,gz):
sum = 0
if gz > 120:
sum += (gz-120)*84*1.15 + gz*84
else:
if gz>=60:
sum = gz*84
else:
sum = gz*84 -700
print("{}號職工應發工資{}".format(gh,sum))
def main():
gh,gz = eval(input("分別輸入工號和工作時長,以逗號分隔"))
fun(gh,gz)
main()
#輸入:
# 分別輸入工號和工作時長110,60
#110號職工應發工資5040
月的天數
輸入年月,求該月的天數
每年 1 3 5 7 8 10 12月有31天,4 6 9 11月有30天,閏年2月29天,平年2月28天
年份能被4整除,但不能被100整除,或者能被400整除的年均是閏年
def fun(year,month):
_31 = [1,3,5,7,8,10,12]
_30 = [4,6,9,7]
if month in _31:
print("{}月有31天".format(month))
return 0
if month in _30:
print("{}與有30天".format(month))
return 0
flag = (year % 4) == 0 and (year % 100) != 0 or year % 400 == 0
print("2月有{}天".format( 29 if flag else 28 ))
def main():
year = int(input("year="))
month = int(input("month="))
fun(year,month)
main()
# 輸入:
# year=2014
# month=12
# 輸出:
# 12月有31天
# 輸入:
# year=2000
# month=2
# 輸出:
# 2月有29天
總結
以上是生活随笔為你收集整理的python的结构_Python结构的选择,python,之的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python xlsx 图片_实例11:
- 下一篇: java filter函数的用法_5分钟