python学习--函数例子

 1 #!/usr/bin/env python3
 2 # -*- coding:utf-8 -*-
 3 
 4 #01 函数的定义,调用
 5 #生日歌
 6 def happy():
 7     print("Happy birthday to you!")
 8  
 9 def sing(person):
10     happy()
11     happy()
12     print("Happy birthday, dear", person + "!")
13     happy()
14 
15 def main():
16     sing("Mike")
17     print()
18     sing("Lily")
19     print()
20     sing("Elmer")
21 
22 main()
23 
24 
25 '''
26 02 改变参数值的函数:
27     函数的形参只接收了实参的值,给形参赋值并不影响实参
28     Python可以通过值来传递参数
29 什么是函数的形参 和 实参?
30     一种是函数定义里的形参,一种是调用函数时传入的实参
31 '''
32 
33 #例1 利息计算 addinterest1.py
34 def addInterest(balance,rate): # balance 和 rate 是函数addInterest的形参
35     newBalance = balance * (1 + rate)
36     balance = newBalance
37 
38 def main():
39     amount =1000
40     rate = 0.05
41     addInterest(amount,rate)  #amount 和rate 是函数addInterest 的实参
42     print(amount)
43 
44 main()
45 
46 #例2 利息计算 addinterest2.py
47 
48 def addInterest(balance, rate):
49     newBalance = balance * (1 + rate)
50     return newBalance
51 
52 def test():
53     amount = 1000
54     rate = 0.05
55     amount = addInterest(amount, rate)
56     print(amount)
57 
58 test()
59 
60 #例3: 处理多个银行账户的程序
61 #addInterest3.py
62 def createTable(principal, apr):
63     #为每一年绘制星号的增长图
64     for year in range(1,11):
65         principal = principal * (1 + apr)
66         print("%2d"%year, end = "")
67         total = caulateNum(principal)
68         print("*" * total)
69     print("0.0k        2.5k    5.0k    7.5k    10.0k")
70 def caulateNum(principal):
71     #计算星号数量
72     total = int(principal * 4 / 1000.0)
73     return total
74 def main():
75     print("This program plots the growth of a 10-year investment.")
76     # 输入本金和利率
77     principal = eval(input("Enter the init principal: "))
78     apr = eval(input("Enter the annualized interest rate: "))
79     #建立图表
80     createTable(principal,apr)
81 main()
原文地址:https://www.cnblogs.com/hayden1106/p/7792728.html