Python 輸入與輸出 (Input/Output)

程式經常需要輸出結果給使用者看,或是接收使用者的輸入。

print() 函數用來在螢幕上輸出內容:

print("Hello, World!")
print(123)
print(3.14)

輸出多個值

用逗號分隔多個值,print() 會自動在它們之間加上空格:

name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# 輸出: Name: Alice Age: 25

自訂分隔符號 sep

使用 sep 參數可以自訂多個值之間的分隔符號:

print("apple", "banana", "orange", sep=", ")
# 輸出: apple, banana, orange

print("2024", "12", "08", sep="-")
# 輸出: 2024-12-08

自訂結尾字元 end

print() 預設會在結尾加上換行,使用 end 參數可以改變結尾字元:

print("Hello", end=" ")
print("World")
# 輸出: Hello World(在同一行)

print("Loading", end="...")
print("Done!")
# 輸出: Loading...Done!

格式化輸出

f-string(推薦)

Python 3.6+ 支援 f-string,是最簡潔的格式化方式:

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# 輸出: My name is Alice and I am 25 years old.

# 可以在 {} 中執行運算
price = 100
discount = 0.2
print(f"Final price: {price * (1 - discount)}")
# 輸出: Final price: 80.0

format() 方法

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# 輸出: My name is Alice and I am 25 years old.

# 使用索引
print("{0} is {1} years old. {0} likes Python.".format(name, age))
# 輸出: Alice is 25 years old. Alice likes Python.

數字格式化

pi = 3.14159265359

# 小數位數
print(f"{pi:.2f}")  # 3.14
print(f"{pi:.4f}")  # 3.1416

# 千分位
number = 1234567
print(f"{number:,}")  # 1,234,567

# 百分比
ratio = 0.856
print(f"{ratio:.1%}")  # 85.6%

# 對齊
print(f"{'left':<10}|")   # left      |
print(f"{'center':^10}|") #   center  |
print(f"{'right':>10}|")  #      right|

input() 輸入

input() 函數用來接收使用者的輸入:

name = input("請輸入你的名字: ")
print(f"Hello, {name}!")

執行時會等待使用者輸入並按 Enter:

請輸入你的名字: Alice
Hello, Alice!

input() 回傳字串

input() 永遠回傳字串型別,如果需要數字要自行轉換:

# 錯誤示範
age = input("請輸入年齡: ")
print(age + 1)  # TypeError! 字串不能和數字相加

# 正確做法
age = int(input("請輸入年齡: "))
print(age + 1)  # OK

# 輸入浮點數
price = float(input("請輸入價格: "))

一次接收多個輸入

# 用 split() 分割輸入
data = input("請輸入兩個數字(用空格分隔): ")
a, b = data.split()
print(f"a = {a}, b = {b}")

# 直接轉換為數字
x, y = map(int, input("請輸入兩個數字: ").split())
print(f"總和: {x + y}")