# 語法講義
請善用ctrl + f找你想要的語法
###### tags: `HackerSir`
[toc]
## 輸入輸出
<table>
<tbody>
<tr>
<td>輸入</td>
<td>input</td>
</tr>
<tr>
<td>輸出</td>
<td>output</td>
</tr>
</tbody>
</table>
```python=
name = input() # 輸入到name裡
print('hello') # 輸出hello
print(name) # 輸出name的值
print('hello', name) # 輸出hello 名字,中間隔一個空格
```
## 變數
變數名稱 = 值
```python=
# 把a的值設成3
a = 3
# 把b的值設成輸入的值,之後轉成整數
b = int(input())
print(a + b)
```
一些比較單純的型態
| 描述 | 名稱 | 轉換到這個型態 |
| ---- | ---- | ---- |
| 整數 | int | int() |
| 小數 | float | float() |
| 布林 | float | float() |
一些功能比較多的型態
| 描述 | 名稱 | 轉換到這個型態 |
| ---- | ---- | ---- |
| 字串 | string | str() |
| 列表 | list | list() |
| 字典 | dictionary | dict() |
## 數學
<table>
<tbody>
<tr>
<td>加法</td>
<td>+</td>
</tr>
<tr>
<td>減法</td>
<td>-</td>
</tr>
<tr>
<td>乘法</td>
<td>*</td>
</tr>
<tr>
<td>除法(小數)</td>
<td>/</td>
</tr>
<tr>
<td>取商數</td>
<td>//</td>
</tr>
<tr>
<td>取餘數</td>
<td>%</td>
</tr>
<tr>
<td>次方</td>
<td>**</td>
</tr>
</tbody>
</table>
```python=
a = 5
b = 3
print(a + b) # 8
print(a - b) # 2
print(a * b) # 15
print(a / b) # 1.6666666666666667
print(a // b) # 1
print(a % b) # 2
print(a ** b) # 125
```
## 條件判斷
if elif else
由上往下判斷,中間遇到一個成立的就會略過其他的
```python=
score = 97
if score >= 90:
print('學霸')
elif score >= 60:
print('及格')
else:
print('當掉')
# 輸出學霸
```
都用if的話就會每個獨立做判斷
```python=
score = 65
if score >= 90:
print('學霸')
if score >= 60:
print('及格')
if score >= 0:
print('當掉')
# 輸出:
# 及格
# 當掉
```
### 比較數字
<table>
<tbody>
<tr>
<td>等於</td>
<td>==</td>
</tr>
<tr>
<td>小於</td>
<td><</td>
</tr>
<tr>
<td>小於等於</td>
<td><=</td>
</tr>
<tr>
<td>大於</td>
<td>></td>
</tr>
<tr>
<td>大於等於</td>
<td>>=</td>
</tr>
</tbody>
</table>
```python=
my_score = 59
your_score = 99
if my_score == your_score:
print("我們同分欸")
elif my_score < your_score:
print("您好強")
elif my_score > your_score:
print("我好強")
# 輸出您好強
```
### 邏輯運算
<table>
<tbody>
<tr>
<td>真</td>
<td>True</td>
</tr>
<tr>
<td>假</td>
<td>False</td>
</tr>
<tr>
<td>且</td>
<td>and</td>
</tr>
<tr>
<td>或</td>
<td>or</td>
</tr>
<tr>
<td>否定</td>
<td>*</td>
</tr>
</tbody>
</table>
```python=
money = 50
price = 25
hungry = False
if money < price:
print("沒錢qwqb")
elif money >= price and not hungry:
print("錢夠但肚子不會餓,省下來吧")
elif money >= price and hungry:
print("有點餓,買個麵包吧")
# 輸出錢夠但肚子不會餓,省下來吧
```
## 迴圈
for迴圈: 主要用在知道會做幾次迴圈,或是要把列表裡的項目全部看過一遍時使用
```python=
for i in range(3):
print("我是數字" + str(i))
# 輸出:
# 我是數字0
# 我是數字1
# 我是數字2
```
```python=
fruits = ["香蕉", "奇異果", "葡萄"]
for fruit in fruits:
print(fruit)
# 輸出:
# 香蕉
# 奇異果
# 葡萄
```
while迴圈: 主要用在不知道要迴圈幾次,但是知道什麼時候要結束迴圈使用
```python=
name = input("請輸入你的名字(最多十個字): ")
# 只要名字的長度超過十個字就繼續迴圈,讓使用者重新輸入
while len(name) > 10:
print("你的名字太長了,可以縮寫一下嗎qwq")
name = input("請輸入你的名字(最多十個字): ")
# 迴圈結束後輸出使用者的名字
print("你的名字是:", name)
```
### 迴圈控制
<table>
<tbody>
<tr>
<td>略過這次執行,跳到下一次的迴圈</td>
<td>continue</td>
</tr>
<tr>
<td>終止迴圈執行</td>
<td>break</td>
</tr>
</tbody>
</table>
```python=
for i in range(5):
if i == 3:
# 數字是3的話會略過數數字的程式,跳到4繼續數
print("我不喜歡" + str(i) + ",不想數他")
continue
print("正在數數字" + str(i))
# 輸出:
# 正在數數字0
# 正在數數字1
# 正在數數字2
# 我不喜歡3,不想數他
# 正在數數字4
```
```python=
for i in range(5):
if i == 3:
# 數字是3的話會停止整個迴圈
print("我超級不喜歡" + str(i) + ",不想再數數了")
break
print("正在數數字" + str(i))
# 輸出:
# 正在數數字0
# 正在數數字1
# 正在數數字2
# 我超級不喜歡3,不想再數數了
```
## 函式
`def 函式名稱(參數):`宣告函式
```python==
# 沒有參數,純粹輸出問候
def say_hello():
print("hello :3")
# 呼叫say_hello
say_hello()
#輸出hello :3
```
括號裡面可以放參數,讓外面把數值傳進函式,在函式裡面做運算
```python=
# 用華氏溫度當參數,輸出攝氏溫度的值
def fahrenheit_to_celcius(f):
print((f - 32) * 5 // 9)
temperature = 70
# 把現在的溫度(華氏)傳入轉成攝氏的函式
fahrenheit_to_celcius(temperature)
# 輸出21
```
`return`可以把值傳回呼叫函式的地方,方便之後運用
```python=
# 用華氏溫度當參數,計算攝氏溫度的值
def fahrenheit_to_celcius(f):
# 改成傳回攝氏的值
return (f - 32) * 5 // 9
temperature = 70
# 把轉成攝氏的溫度記錄下來
temp_celcius = fahrenheit_to_celcius(temperature)
# 根據攝氏溫度輸出文字
if temp_celcius >= 30:
print('熱死')
elif temp_celcius >= 15:
print('剛好')
else:
print('冷死')
# 輸出剛好
```
## 模組
`import 模組名稱` 把模組底下的東西全部匯入,呼叫時寫`模組名稱.函式名稱`
```python=
# 使用random裡的shuffle和choice函式
import random
cards = [1, 2, 3, 4, 5]
random.shuffle(cards) # 洗牌
print(cards) # 輸出洗牌後的結果
print(random.choice(cards)) # 隨機選一張牌
```
`from 模組名稱 import 函式名稱` 只匯入模組底下指定的函式,呼叫時寫`函式名稱`就好了
```python=
# 使用random裡的shuffle和choice函式
from random import shuffle, choice
cards = [1, 2, 3, 4, 5]
shuffle(cards) # 洗牌
print(cards) # 輸出洗牌後的結果
print(choice(cards)) # 隨機選一張牌
```
`from 模組名稱 import *` 把所有東西匯入,呼叫時寫`函式名稱`就可以,但需要小心撞名
```python=
# 使用random裡的shuffle和choice函式
from random import *
cards = [1, 2, 3, 4, 5]
shuffle(cards) # 洗牌
print(cards) # 輸出洗牌後的結果
print(choice(cards)) # 隨機選一張牌
```
## 一些型態的功能
### 字串
<table>
<tbody>
<tr>
<td>取字串中的某個字</td>
<td>字串[索引值]</td>
</tr>
<tr>
<td>連結字串</td>
<td>字串 + 字串</td>
</tr>
<tr>
<td>重複字串</td>
<td>字串 * 整數</td>
</tr>
</tbody>
</table>
```python=
s = 'owo'
print(s + 'b')
print(s * 5)
# 輸出:
# owob
# owoowoowoowoowo
```
用for迴圈遍歷字串中的每一個字
```python=
message = "secret message"
for character in message:
if character == 's':
print('5', end='')
else:
print(character, end='')
# 輸出5ecret me55age
```
我知道沒人喜歡這個不過format真的好用qwqb
`字串.format()`做特殊格式設定
純粹填入變數:
```python=
s = '現在是{}{}點{}分'
time_of_day = '早上'
hour = 10
minute = 40
print(s.format(time_of_day, hour, minute))
# 輸出現在是早上10點40分
```
填入變數並做格式設定:
```python=
r = 1.61803
print("黃金比例是{:.3f}".format(r))
```
字串切割
<table>
<tbody>
<tr>
<td>字串[開始:結束]</td>
</tr>
<tr>
<td>字串[開始:結束:間隔]</td>
</tr>
</tbody>
</table>
```python=
s = "HackerSir"
print(s[0:6])
print(s[0:9:2])
# 輸出:
# Hacker
# HceSr
```
### 列表
<table>
<tbody>
<tr>
<td>創建新的列表</td>
<td>list() 或 []</td>
</tr>
<tr>
<td>新增項目</td>
<td>列表.append()</td>
</tr>
<tr>
<td>刪除項目</td>
<td>列表.remove()</td>
</tr>
<tr>
<td>清除所有項目</td>
<td>列表.clear()</td>
</tr>
<tr>
<td>排序所有項目</td>
<td>列表.sort()</td>
</tr>
<tr>
<td>取最大值</td>
<td>max(列表)</td>
</tr>
<tr>
<td>取最小值</td>
<td>min(列表)</td>
</tr>
<tr>
<td>取總和</td>
<td>sum(列表)</td>
</tr>
</tbody>
</table>
用for迴圈遍歷列表中的每個項目
```python=
scores = [31, 46, 24, 97, 74, 26, 83]
# 用for迴圈對每一個分數做調分
for i in range(len(scores)):
# 開根號後乘10
# 注意要對list裡的項目改值一定要用for i in range語法
# for score in scores中是把scores裡的東西複製一份,
# 沒辦法改動到scores的內容
scores[i] = round(scores[i] ** 0.5 * 10)
print(scores)
scores.sort()
print(scores)
# 輸出:
# [56, 68, 49, 98, 86, 51, 91]
# [49, 51, 56, 68, 86, 91, 98]
```
### 字典
<table>
<tbody>
<tr>
<td>創建新的字典</td>
<td>dict() 或 {}</td>
</tr>
<tr>
<td>新增項目</td>
<td>字典[鍵] = 值 或 字典.update()</td>
</tr>
<tr>
<td>刪除項目</td>
<td>字典.pop()</td>
</tr>
</tbody>
</table>
用for迴圈遍歷字典中的每個項目
```python=
menu = {'咖啡': 50, '綠茶': 25, '開水': 0}
for drink, price in menu.items():
print('飲料:', drink, '價格:', price)
# 輸出:
# 飲料: 咖啡 價格: 50
# 飲料: 綠茶 價格: 25
# 飲料: 開水 價格: 0
```