2025 Python Input 完全指南 | 從入門到高手必懂的技巧!


Python Input(輸入) 是程式設計中最基礎且不可或缺的一部分,Python 作為當今最流行的程式語言之一,其靈活性和強大的功能讓它成為開發者的首選。無論你是剛入門的新手,還是已經有一定經驗的高手,掌握 Python 的輸入(Input)操作都是必不可少的技能。本文將帶你從基礎到進階,全面解析 Python 的輸入操作,並分享一些實用技巧,讓你在 2025 年依然能輕鬆駕馭 Python!

Python Input

基礎輸入:Python Input 函數

基本用法 :

Python 中最基本的輸入方式是使用內建的 input() 函數。它會從標準輸入(通常是鍵盤)讀取用戶輸入,並返回一個字串。

name = input("Enter your name: ")
print(f"Hello, {name}!")

注意input() 返回的數據類型永遠是字串(str)。如果需要其他類型,必須進行類型轉換。

基礎輸入:類型轉換

由於 input() 返回的是字串,我們通常需要將其轉換為其他數據類型,例如整數或浮點數。

age = int(input("Enter your age: "))
height = float(input("Enter your height (in meters): "))
print(f"Age: {age}, Height: {height} meters")

常見的類型轉換函數

  • int():轉換為整數
  • float():轉換為浮點數
  • bool():轉換為布林值

進階輸入:以空格或逗號的多值輸入

假設用戶輸入一行數字並用空格分隔,可以使用 .split() 解析:

numbers = input("Enter numbers separated by spaces: ").split()
numbers = [int(num) for num in numbers]  # Convert to a list of integers
print(f"Sum of numbers: {sum(numbers)}")

或者,如果使用者輸入 1,2,3,4,5,可用 .split(",") 處理:

numbers = input("Enter numbers separated by commas: ").split(",")
numbers = [int(num) for num in numbers]
print(f"Maximum number: {max(numbers)}")

進階輸入:讀取多行輸入

有時候,我們需要一次性讀取多行輸入,可用 sys.stdin.read()

print("Enter multiple lines (type 'END' to finish):")
lines = []
while True:
    line = input()
    if line == "END":
        break
    lines.append(line)

print("\nYour input:")
print("\n".join(lines))

進階輸入:從檔案讀取輸入

當輸入來自檔案時,可用 open() 讀取內容:

with open("data.txt", "r") as file:
    content = file.read()
    print("File contents:")
    print(content)

進階輸入:讀取標準輸入

sys.stdin.read() 可一次讀取標準輸入的所有內容,適用於處理大數據或競賽題目:

import sys
data = sys.stdin.read()
print("Input received:")
print(data)

進階輸入:讀取命令列參數

當需要處理腳本參數時,可使用 argparse

import argparse

parser = argparse.ArgumentParser(description="Process command-line input")
parser.add_argument("name", type=str, help="Enter your name")
args = parser.parse_args()

print(f"Hello, {args.name}!")

運行方式:

python script.py John

處理異常輸入

輸入可能不符合預期,例如輸入非數字字符。為了避免程式崩潰,我們可以使用 try-except 結構來捕獲異常。

try:
    age = int(input("Enter your age: "))
    print(f"Your age is: {age}")
except ValueError:
    print("Invalid input! Please enter an integer.")

結論

Python 的輸入操作看似簡單,但其中蘊含了許多技巧和細節。從基礎的 input() 函數到進階的 argparse 和 sys.stdin,掌握這些技能將讓你在開發中更加得心應手。希望這份指南能幫助你從入門到高手,全面掌握 Python 的輸入操作!