能够完成某个工做的代码块。这是能够用来构建更大程序的一个小部分。函数
1) def 关键字ui
2)函数名及后面跟随的括号spa
3)冒号与for循环,while循环,if语句中同样code
提醒:函数没被调用前不是主程序的一部分。orm
print_nums()blog
1)一个参数游戏
def print_nums(num): for i in range(num): print(i) print_nums(3)
2)两个参数:get
def add(n1, n2): print("{} + {} = ?".format(n1, n2)) print(n1 + n2) add(3, 5)
def add2(n1, n2, n3): print("{} + {} + {} = ?".format(n1, n2, n3)) print(n1 + n2 + n3) add2(3, 5, 9)
def add3(n1, n2): return n1 + n2 sum = add3(3, 5) print("sum = {}".format(sum))
def multi_table(num): i = 1 while i <= num: text = "" # for j in range(1, i+1): j = 1 while j <= i: text += "{}*{}={:2} ".format(i, j, i*j) j += 1 print(text) i += 1
def print_shape(row, col): for i in range(row): line = "" for j in range(col): line += "*" print(line)
def choice_box(): import easygui as g msg = "输入你喜欢的颜色" title = "游戏互动" choices = ["红色", "绿色", "蓝色", "青色"] return g.choicebox(msg, title, choices)