目錄
(1)注釋
(2)縮進
(3)變量和數據類型
變量定義
數據類型
(4)輸入和輸出
輸出:print() 函數
輸入:input() 函數
(1)注釋
注釋是代碼中用于解釋說明的部分,不會被執行。
單行注釋:使用 #
,#
后面的內容是注釋。
# 這是一個單行注釋
print("Hello, World!") # 這也是注釋,用于解釋代碼
多行注釋:使用三引號 """
或 '''
,可以包含多行內容。
"""
這是一個多行注釋
可以包含多行內容
"""
多行注釋常用于函數或模塊的文檔說明,也可以用于臨時注釋掉代碼塊。
(2)縮進
Python 使用縮進來表示代碼塊,縮進是強制性的,錯誤的縮進會導致語法錯誤。
標準縮進:通常使用 4 個空格。
示例:
if True:print("Hello, World!") # 正確的縮進
如果縮進錯誤,代碼會報錯:
if True:
print("Hello, World!") # 縮進錯誤,會導致 IndentationError
縮進還可以用于循環、函數等代碼塊:
for i in range(3):print(f"這是第 {i + 1} 次循環")
(3)變量和數據類型
Python 是一種動態類型語言,變量不需要聲明類型,直接賦值即可。
變量定義
x = 10 # 定義一個變量 x,賦值為 10
name = "Kimi" # 定義一個變量 name,賦值為字符串 "Kimi"
數據類型
Python 中常見的數據類型包括:
整數(int):表示整數。
age = 25
print(type(age)) # 輸出:<class 'int'>
浮點數(float):表示小數。
pi = 3.14
print(type(pi)) # 輸出:<class 'float'>
字符串(str):用單引號 '
或雙引號 "
包裹。
greeting = "Hello, World!"
name = 'Kimi'
print(type(greeting)) # 輸出:<class 'str'>
列表(list):用方括號 []
包裹,可以包含多個元素,元素可以是不同類型。
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "Kimi", 3.14, True]
print(type(numbers)) # 輸出:<class 'list'>
print(numbers[0]) # 輸出:1(訪問列表的第一個元素)
元組(tuple):用圓括號 ()
包裹,不可變。
point = (1, 2)
colors = ("red", "green", "blue")
print(type(point)) # 輸出:<class 'tuple'>
print(colors[1]) # 輸出:"green"(訪問元組的第二個元素)
字典(dict):用花括號 {}
包裹鍵值對,鍵必須是不可變類型。
person = {"name": "Kimi", "age": 25, "city": "Shanghai"}
print(type(person)) # 輸出:<class 'dict'>
print(person["name"]) # 輸出:"Kimi"(通過鍵訪問值)
集合(set):用花括號 {}
包裹,無序且去重。
my_set = {1, 2, 3, 4, 4, 5}
print(my_set) # 輸出:{1, 2, 3, 4, 5}(自動去重)
print(type(my_set)) # 輸出:<class 'set'>
(4)輸入和輸出
Python 提供了簡單的輸入和輸出函數。
輸出:print()
函數
print("Hello, World!") # 輸出字符串
print(100) # 輸出整數
print(3.14) # 輸出浮點數
print([1, 2, 3]) # 輸出列表
print({"name": "Kimi"}) # 輸出字典
print()
函數還可以通過參數控制輸出格式:
print("Hello", "World", sep="-", end="!\n") # 輸出:Hello-World!
輸入:input()
函數
input()
函數用于從用戶獲取輸入,返回的是字符串類型。
name = input("Enter your name: ") # 提示用戶輸入名字
print(f"Hello, {name}!") # 使用 f-string 格式化字符串
示例:完整的輸入輸出程序
# 提示用戶輸入年齡
age = input("Enter your age: ")
age = int(age) # 將輸入的字符串轉換為整數
print(f"You are {age} years old.")if age >= 18:print("You are an adult.")
else:print("You are a minor.")