--- title: 'Python Challenge Day 4 - Power' disqus: hackmd --- ## Python Challenge Day 4 - Power ### DESCRIPTION The goal is to create a function of two inputs number and power, that "raises" the number up to power (ie multiplies number by itself power times). ### Examples: ```gherkin= numberToPower(3, 2) // -> 9 ( = 3 * 3 ) numberToPower(2, 3) // -> 8 ( = 2 * 2 * 2 ) numberToPower(10, 6) // -> 1000000 ``` ### Note: Math.pow and some other Math functions like eval() and ** are disabled. 程式邏輯 --- 目的:給兩個input(number,power),得出number的power次方。 例外:不能使用Math.pow,也不能使用eval()與** 1. 當power等於0,number的0次方為1,所以先給定一個值為1(test=1) 2. 用for迴圈執行條件式(test = test * number),執行次數為power的值 Solution --- ``` python def number_to_pwr(number, p): test = 1 for i in range(p): test = test * number return test ``` * 使用 def 關鍵字來定義函數(number_to_pwr) * [test *= number] = [test = test * number] * 如果p=3,for迴圈會執行四次(0,1,2,3),當number=3會回傳如下: 第0次, test=1 * 3, test=3 第1次, test=3 * 3, test=9 第2次, test=9 * 3, test=27 第3次, test=27 *3 , test=81 ## 參考資源 :::info * [Kata](https://www.codewars.com/kata/562926c855ca9fdc4800005b) :::