← 返回大綱
第一章

基礎語法
與變數型別

Basic Syntax & Data Types

Scratch → Python

說出 → print()

Scratch
說出 "Hello, World!"
Python
print("Hello, World!")

可以 print 任何東西:

print("Hello!")          # 字串
print(42)                # 數字
print(3.14)              # 小數
print("1 + 1 =", 1 + 1) # 同時印多個,中間空格分隔
Hello!
42
3.14
1 + 1 = 2
Scratch → Python

變數設定

Scratch
將 score 設為 100
Python
score = 100

Python 用 = 指定值,不需要事先宣告:

name = "Ian"       # 字串
age = 18           # 整數
height = 175.5     # 小數
is_student = True  # 布林值

print(name, "今年", age, "歲")
Ian 今年 18 歲
概念

四種基本資料型別

型別英文範例說明
intInteger42, -10整數
floatFloat3.14, -0.5小數(浮點數)
strString"Hello", 'Hi'字串(文字)
boolBooleanTrue, False布林(真/假)
x = 42
print(type(x))       # <class 'int'>

y = "Hello"
print(type(y))       # <class 'str'>
type() 函式

type(變數) 可以查看變數的型別。

字串

字串 (str) 常用操作

name = "Python"

print(len(name))          # 6 — 字串長度
print(name.upper())       # PYTHON — 全大寫
print(name.lower())       # python — 全小寫
print(name[0])            # P — 第一個字元(索引從 0 開始)
print(name[0:3])          # Pyt — 切片

f-string(推薦的字串格式化方式)

name = "Ian"
age = 18
print(f"我叫 {name},今年 {age} 歲")
# 我叫 Ian,今年 18 歲
f-string 語法

在字串前加 f,然後用 {} 包住要嵌入的變數。

規則

變數命名規則

合法命名

name = "Ian"
my_score = 100
score2 = 95
_temp = 0
studentName = "Amy"

不合法命名

2score = 100    # 不能數字開頭
my-name = "Ian" # 不能用減號
class = "A"     # 不能用保留字
命名慣例(snake_case)

Python 習慣用底線分隔單字:my_scorefirst_nameis_logged_in

Python 保留字(不能當變數名):ifelseforwhiledefclassTrueFalseNone

型別轉換

型別轉換

不同型別之間可以互相轉換:

x = "42"
print(type(x))       # <class 'str'>

y = int(x)           # 字串轉整數
print(type(y))       # <class 'int'>
print(y + 1)         # 43

z = float("3.14")    # 字串轉小數
print(z)             # 3.14

s = str(100)         # 數字轉字串
print("分數:" + s)  # 分數:100
注意

"42" + 1 會出錯!字串和數字不能直接相加,需要先轉型。

Scratch → Python

詢問並等待 → input()

Scratch
詢問 "你叫什麼名字?" 並等待
Python
name = input("你叫什麼名字?")
name = input("請輸入你的名字:")
print(f"你好,{name}!")

age = int(input("請輸入年齡:"))  # input 回傳字串,需轉型
print(f"你今年 {age} 歲")
重要!

input() 的回傳值永遠是字串,如果要做數學運算,記得用 int()float() 轉型。

實作練習

動手試試看

建立 intro.py,完成以下程式:

# 請使用者輸入姓名和年齡
name = input("請輸入你的名字:")
age = int(input("請輸入你的年齡:"))

# 計算出生年份(假設今年是 2026)
birth_year = 2026 - age

# 用 f-string 輸出完整介紹
print(f"你好!我叫 {name}")
print(f"我今年 {age} 歲,出生於 {birth_year} 年")

第一章完成!

學會了 print、變數、資料型別與 input。