---
# System prepended metadata

title: 2023-04-15 Python入門
tags: [已轉移]

---

# 2023-04-15 Python入門

###### tags: `python`

## random隨機產生整數
```python=
import random

# 隨機產生1~3之間的整數並存放到變數a
a = random.randint(1, 3)  # 指派

print(a)
```

```python=
import random

# 隨機產生1~3之間的整數並存放到變數a
a = random.randint(1, 3)  # 指派

print(a)

b = ['aaron', 'andy', 'abner']

random.shuffle(b)

print(b)
```

#### 猜數字
寫一成是
```
import random

# 隨機產生1~9之間整數
pc = random.randint(1, 9)
print('答案:', pc)

# 讓使用者輸入一個數字
player = input('請輸入1~9之間的整數:')

if pc == int(player):
    print('恭喜，猜對了')
else: # 當pc == player結果為False的時候, else裡面的程式碼會被執行
    print('可惜，猜錯了1')
    print('可惜，猜錯了2')
    print('可惜，猜錯了3')

print('可惜，猜錯了4')
print('可惜，猜錯了5')
```

#### if多重分支
```
student_score = int(input('請輸入成績:'))

if student_score == 100:
    print('棒')
elif student_score >= 90:
    print('好')
elif student_score >= 80:
    print('可')
elif student_score >= 70:
    print('OK')
elif student_score >= 60:
    print('恩')
else:
    print('不行')
```

#### 如果想讓所有幅條件的都執行
```
student_score = int(input('請輸入成績:'))

if student_score == 100:
    print('棒')

if student_score >= 90:
    print('好')

if student_score >= 80:
    print('可')

if student_score >= 70:
    print('OK')

if student_score >= 60:
    print('恩')
else:
    print('不行')
```

#### 
```python=
user = int(input('請輸入一個數字:'))

# if user % 2 == 1:
#     print('奇數')

# if user % 2 == 0:
#     print('偶數')


# if user % 2 == 1:
#     print('奇數')
# else:
#     print('偶數')

a = '奇數' if user % 2 == 1 else '偶數'
print(a)

print('奇數' if user % 2 == 1 else '偶數')
```

#### 猜拳遊戲
```python=
import random

data = ['剪刀', '石頭', '布']

# 電腦出拳
pc = random.randint(0, 2)  # 0=剪刀, 1=石頭, 2=布
print('電腦:', data[pc])

# 玩家出拳
player = int(input('請出拳(0=剪刀, 1=石頭, 2=布):'))
print('玩家:', data[player])

if pc == 0 and player == 1:
    print('你贏了')
elif pc == 0 and player == 2:
    print('你輸了')
elif pc == 1 and player == 0:
    print('你輸了')
elif pc == 1 and player == 2:
    print('你贏了')
elif pc == 2 and player == 0:
    print('你輸了')
elif pc == 2 and player == 1:
    print('你贏了')
else:
    print('平手')
```

#### while
```
import random

pc = random.randint(0, 5)
print('答案:', pc)

while True:
    player = int(input('請輸入一個數字:'))

    if pc == player:
        print('猜對了，你可以離開了')
        break # 結束迴圈
    else:
        print('猜錯了，請繼續...')

```

#### while練習
```python=
data = []

while True:
    user = input('請輸入一個數字(quit=離開):')

    if user.lower() == 'quit':
        print('結束')
        break
    else:
        data.append(int(user))

print(data)
```

#### set
```python=
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

c = a & b   # 交集, 位元運算and
print('交集:', c)
c = a | b   # 聯集, 位元運算or
print('聯集:', c)
c = a - b   # 差集
print('差集:', c)
c = a ^ b   # 對稱差集
print('對稱差集:', c)
```


#### unpack
```
a = [1, 2, 3, 4, 5, 6]
b = (5, 6, 7, 8)

a1, *a2, a3, a4 = a

b1, b2, b3, b4 = b

print(a1)
print(a2)
print(a3)
# print(b4)
```


#### dict
```
a = {'aa':3, 'bb':4}

a['aa'] = 99
a['cc'] = 999  # 對著不存在的key指派資料，該筆資料就會新增

del a['bb']

print(a, len(a))
print(a.keys())
print(a.values())
```

#### range()
```
a = range(0, 10)
print(list(a))

a = range(1, 10, 2)
print(list(a))

a = range(10, 0, -2)
print(list(a))


for n in range(0, 100):
    print(n)
```

#### 階乘
```
a = int(input('請輸入一個數字:'))

result = 1

for n in range(1, a + 1):
    result *= n

print(f'{a}的階乘為{result}')
```

#### 
```python=
a = [3, 4, 9, 23, 48]

for n in a:
    if n % 2 == 1:
        continue
    
    print(n)
```

#### for-comprehension
```
a = [30, 40, 55, 49, 68, 23, 12]

# b = []
# for n in a:
#     b.append(n + 30)

b = [n + 30 for n in a]

print(b)
```

#### 幾A幾B遊戲
```python=
import random

a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
random.shuffle(a)

answer = a[0] + a[1] + a[2] + a[3]

print(f'答案是: {answer}')

guess_count = 0 # 紀錄猜幾次

while True:
    player = input('請輸入四個數字(不可重複):')
    guess_count += 1 # 增加次數

    # 判斷輸入的是不是數字
    try:
        int(player)
    except:
        print('輸入的數字有問題')
        continue

    # 判斷數字有沒有重複
    if len(set(player)) != 4:
        print('數字不可重複')
        continue

    # 猜對了
    if answer == player:
        print(f'猜對了，總共猜了{guess_count}次.')
        break

    # 提示A跟B
    how_many_a = 0
    how_many_b = 0

    # 算出幾A
    if answer[0] == player[0]:
        how_many_a += 1

    if answer[1] == player[1]:
        how_many_a += 1

    if answer[2] == player[2]:
        how_many_a += 1

    if answer[3] == player[3]:
        how_many_a += 1

    # 算出幾B
    if player[0] in answer and player[0] != answer[0]:
        how_many_b += 1

    if player[1] in answer and player[1] != answer[1]:
        how_many_b += 1

    if player[2] in answer and player[2] != answer[2]:
        how_many_b += 1

    if player[3] in answer and player[3] != answer[3]:
        how_many_b += 1

    print(f'{how_many_a}A{how_many_b}B, 目前已經猜了{guess_count}次')
```
        
#### 連續技
```
a = 'abcdef'  # a.b.c.d.e.f

# b = '.'.join(a)
# print(b)

# c = b.replace('.', '-')
# print(c)

# d = c.replace('-', '')
# print(d)


print('.'.join(a).replace('.', '-').replace('-', ''))
```
