編寫簡單的Python程序是鞏固基礎的好方法。下面我將給出幾個簡單的Python程序示例,涵蓋了基本的數據類型、控制流、函數和文件操作。
示例1:Hello, World!
這是最簡單的Python程序,用于打印出 "Hello, World!"。
print("Hello, World!")
示例2:基本數據類型和運算符
這個程序演示了如何使用整數、字符串和布爾值,以及進行簡單的數學運算。
# 定義變量
x = 10
y = 5 # 使用運算符
sum = x + y
difference = x - y
product = x * y
quotient = x / y
remainder = x % y # 布爾值
is_greater = x > y
is_equal = x == y # 打印結果
print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)
print("Is x greater than y?", is_greater)
print("Is x equal to y?", is_equal)
示例3:條件語句和循環
這個程序使用?if
?語句和?for
?循環來執行不同的操作。
# 列表
numbers = [1, 2, 3, 4, 5] # for 循環
for num in numbers: if num % 2 == 0: print(num, "is even.") else: print(num, "is odd.") # if 語句
user_input = input("Enter a number: ")
number = int(user_input) if number > 0: print("The number is positive.")
elif number < 0: print("The number is negative.")
else: print("The number is zero.")
示例4:函數
這個程序定義了一個簡單的函數,該函數接受兩個參數并返回它們的和。
# 定義函數
def add_numbers(a, b): return a + b # 調用函數
result = add_numbers(5, 3)
print("The sum is:", result)
示例5:文件操作
這個程序演示了如何在Python中讀取和寫入文件。
# 寫入文件
with open("example.txt", "w") as file: file.write("Hello, this is an example file.") # 讀取文件
with open("example.txt", "r") as file: content = file.read() print("File content:", content)
請注意,在示例5中,我們在寫入文件時使用了?"w"
?模式,這會覆蓋文件中已有的內容(如果文件存在的話)。如果你想在文件的末尾添加內容而不是覆蓋它,你可以使用?"a"
(追加)模式。在讀取文件時,我們使用了?"r"
(讀取)模式。