程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python函數

編輯:Python

#定義(做功能)函數
用於封裝一個特定的功能,表示一個功能或模塊

def attack():
print(12)
print(34)
attack()
#形式參數
def attack_01(count):
for i in range(count):
print(i)
attack_01(3)#實際參數
def print_list(list01):
for i in list01:
for j in i:
print(j,end=" ")
print()
list01=[
[1,2,3,44],
[4,5,5,5,65,87],
[7,5]
]
print_list(list01)
list01 = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
for c in range(1,4):
for r in range(1,4):
list01[r][c-1], list01[c-1][r] = list01[c-1][r],list01[r][c-1]
print(list01)

函數返回值
函數執行返回的結果,用return來

def fun01(num):
print("hello world)
return 20
re = fun01(10)#返回20

需求:定義兩個數字相加的函數

def add(number01,number02):
result = number + number02
return result
num01=int(input())
num02=int(input())
result=add(num01,num02)
print(result)
""" 古代的秤一斤是16兩 練習:在控制台中獲取兩,計算是幾斤幾兩 """
# liang = float(input("請輸入兩:"))
# jing = int(liang // 16)
# liang_1 = liang % 16
#
# print(str(liang)+"兩是"+str(jing)+"斤"+str(liang_1)+"兩")
def chang(liang):
ing = int(liang // 16)
liang_1 = liang % 16
return ing, liang_1
liang = float(input("請輸入兩:"))
result = chang(liang)
print(str(liang) + "兩是" + str(result[0]) + "斤零" + str(result[1]) + "兩")
def dengji(score):
""" 根據成績計算等級 的函數 :param score: :return: """
if score < 0 or score > 100:
return "輸入有誤"
elif score >= 90:
return "優秀"
elif score >= 80:
return "良好"
elif score >= 60:
return "及格"
elif 0 <= score:
return "不及格"
score = int(input("請輸入成績:"))
result=dengji(score)
print(result)
#不建議方法的返回值可能是多種
def is_leap_year(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def Calculate_monthly(year, month):
""" 計算年月 :param year: :return: """
if month < 1 or month > 12:
return -1
elif month == 2:
return 29 if is_leap_year(year) else 28
elif month == 4 or month == 6 or month == 9 or month == 11:
return 30
else:
return 31
month = int(input("請輸入一個月份:"))
year = int(input("請輸入一個年份:"))
print(Calculate_monthly(year, month))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved