python学习--函数例子
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的python学习--函数例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷 P1550 浇水
- 下一篇: CPU排行-台式