---
# System prepended metadata

title: 資研 11/17 社課講義
tags: [社課講義, 資研]

---

# 資研 11/17 社課講義

[**提問表單**](https://forms.gle/z4dPC1JPV6uA2q9w7)
[**上課PPT**](https://www.canva.com/design/DAF0QOejvns/SzMwDrBD1hEhzIA65sld5A/view?utm_content=DAF0QOejvns&utm_campaign=designshare&utm_medium=link&utm_source=editor)

---

:::warning
**range()**

- 迭代函數
- range(start, end, step)
>start：預設為0；step：預設為1（<font color="#CE0000">間隔多少迭代一次</font>）
- 會從start數到end-1（共end-start個）

```python=
range(5)
# 0, 1, 2, 3, 4（共5個）

range(1, 5)
# 1, 2, 3, 4

range(1, 5, 2)
# 1, 3

range(5, 1, -1)
# 5, 4, 3, 2
```

:::

## For迴圈 For Loops

### 基本觀念

1. 架構
```python=
for [變數] in [可迭代物件]:
    [執行程式碼]
```
2. 用途：執行多次重覆程式碼
3. 可迭代物件：**range()**、**string**...

- 範例1. 印出1~5
```python=
for i in range(1, 6):
    print(i, end=' ')
```

- 範例2. 在一行內分別印出"Basic Program Group"的所有字元（含空格），並以逗點隔開
```python=
for i in 'Basic Program Group':
    print(i, end=',')
```
:::success
**若不希望多印出一個逗號**
**可以嘗試控制"最後一次不印出逗號"**
```python=
for i in 'Basic Program Group':
    # 最後一個字母恰為'p'
    if i == 'p': print(i)
    else: print(i, end=',')
```
```python=
A = "Basic Program Group"
n = len(A)
for i in range(n):
    if i == n-1: print(A[i])
    else: print(A[i], end=',')
```
:::

## **練習題**

**Zerojudge**

[**連結**](https://zerojudge.tw/)

:::spoiler c418.範例程式碼
```python=
a = int(input())
for i in range(1, a+1):
    print('*'*i)
```
:::

:::spoiler c419.範例程式碼
```python=
a = int(input())
for i in range(1, a+1):
    print('_'*(a-i)+'*'*i)
```
:::

:::spoiler c420.範例程式碼
```python=
a = int(input())
for i in range(1, a+1):
    print('_'*(a-i)+'*'*(2*i-1)+'_'*(a-i))
```
:::

:::spoiler b970.範例程式碼
```python=
a = int(input())
for i in range(a):
    print(f"{i+1}. I don't say swear words!")
    # print(i+1, ". I don't say swear words!", sep='')
```
:::

---

## 補充資料

**推薦網站：**[**W3Schools**](https://www.w3schools.com/)