復利函數:
1 #!/user/bin/env python 2 #-*-coding:utf-8 -*- 3 #Author: qinjiaxi 4 def invest(amount, rate, time): 5 print('princical amount: {}'.format(amount)) 6 for t in range(1, time + 1): 7 amount = amount * (rate + 1) 8 print('year {}: {}'.format(t, amount)) 9 invest(2000, 0.5, 5)
搖骰子猜大小(一次三個篩子)
思路:首先定義一個搖骰子函數,得到三個篩子隨機結果並存入一個列表中(這個過程中需要導入random函數);然后定義一個區分大小的函數,規定什么樣的結果返回大,什么時候返回小;最后定義一個游戲啟動函數,先給出系統默認大小結果的列表,然后將用戶的猜測(輸入)進行對比,其中用到判斷等一些操作。源碼:
1 #!/user/bin/env python 2 #-*-coding:utf-8 -*- 3 #Author: qinjiaxi 4 import random 5 #一次搖三個骰子並將結果存在列表中 6 def role_a_dice(number = 3, point = None ): 7 print('Let\'s play a game') 8 if point is None: 9 point = [] 10 while number > 0: 11 point.append(random.randint(1, 6)) 12 number -= 1 13 return point 14 #將結果轉換成'大小'字符串 15 def dice_reslut(total): 16 isBig = 11 <= total <= 18 17 isSmall = 3 <= total <= 10 18 if isBig: 19 return "Big" 20 if isSmall: 21 return "Small" 22 def start_game(): 23 print("-----GAME START-----") 24 choices = ['Big', 'Small'] 25 U_choices = input('pls enter your choice:') 26 if U_choices in choices: 27 points = role_a_dice()#調用函數搖骰子得到三個骰子的結果 28 totals = sum(points)#三次結果相加得到最終點數 29 resluts = dice_reslut(totals)#調用函數得到將最終點數轉換成字符串 30 if U_choices == resluts: 31 print('點數是:{}恭喜你猜對了'.format(points)) 32 else: 33 print('點數是:{}抱歉猜錯了'.format(points)) 34 else: 35 print('Invalid words.') 36 start_game() 37 start_game()