---
# System prepended metadata

title: Python Challenge Day 3 - Powers of 2

---

---
title: 'Python Challenge Day 3 - Powers of 2'
disqus: hackmd
---


## Python Challenge Day 3 - Powers of 2
### DESCRIPTION

Complete the function that takes a non-negative integer n as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to n ( inclusive ).


### Examples:

```gherkin=
n = 0  ==> [1]        # [2^0]
n = 1  ==> [1, 2]     # [2^0, 2^1]
n = 2  ==> [1, 2, 4]  # [2^0, 2^1, 2^2]
```
程式邏輯
---
目的：以正整數 n 作為輸入的函數，並輸出 2 的所有平方的列表，平方指數的範圍為 0 到 n（含）。
1. 給串列空值，可以放進欲輸出的值 list=[ ]
2. 使用迴圈，給出範圍條件 for i in range(0, n+1)
3. 將數值加進 list, list.append ( 2**i )


Solution
---
``` python
def powers_of_two(n):
    list=[]
    for i in range(0,n+1):
        list.append(2 ** i)
    return list
```


* 使用 def 關鍵字來定義函數（powers_of_two）
* 在Python中，次方的運算用的符號是** 
* 使用 for 迴圈; for 變數 in range(起始值,結束值,間隔值)
* in range 的結束值預設為n-1, 所以需要+1才會等於n


## 參考資源

:::info
* [Kata](https://www.codewars.com/kata/57a083a57cb1f31db7000028)
:::

