---
# System prepended metadata

title: For loop examples in python
tags: [python]

---

---
title: For loop examples in python
tags: python
---
[TOC]

# Example 1. 單層迴圈
目標：抽出班上若干位同學
輸入：要抽出幾人
輸出：抽籤結果
- Example code:
```python=
import random
names = ["季倢楓", "翁暐婷", "楊淯雯", "蔡采陵", "巴俊評", "陳孟璡", "吳長恩", "蕭宇晉", "賴冠廷", "謝嘉宏"]

n = int(input('How many students do you want to pick? '))
for i in range(n):
	print(names[random.randint(0, len(names) - 1)])
```
- Demo:
![](https://i.imgur.com/Mxsg7qS.png)

> You will learn list in Ch.8

---
# Example
```python=
print('告訴我一個整數範圍的上限和下限，我可以告訴你7的倍數有幾個，分別為哪些。')
low = int(input('下限: '))
up  = int(input('上限: '))

if low <= up:
    counter = 0
    # range(x, y) 會產生 [x, y) 之間的數字，因此若要包含y，需要加上1
    for number in range(low, up+1):
        if number % 7 == 0:
            counter = counter + 1
            print(str(counter) + ': ' + str(number))
else:
    print('錯誤，下限大於上限')
```
```
告訴我一個範圍的上限和下限，我可以告訴你7的倍數有幾個，分別為那些。
下限: 1
上限: 30
1: 7
2: 14
3: 21
4: 28

告訴我一個範圍的上限和下限，我可以告訴你7的倍數有幾個，分別為那些。
下限: 100
上限: 50
錯誤，下限大於上限
```
---
# Example
目標：印出m*n的矩形
輸入：長(m) 寬(n)
輸出結果
- Example code:
```python=
m,n=map(int,input('Input length and width:').split())
for i in range(n):
    print("*",end='')
    for j in range(m-2):
        if  i!=0 and i!=n-1:   #非第一列或最後一列
            print(" ",end='')
        else:
            print("*",end='')
    print("*")
```
- Demo:
![](https://i.imgur.com/eu6B5tM.png)

[我 Po 這裏ㄡ](https://moodle.ncnu.edu.tw/mod/forum/view.php?id=609622&forceview=1)
