print
函數(shù)用于顯示或打印輸出。
print("Hello, World!")
input
函數(shù)用于從用戶獲取輸入,輸入內(nèi)容默認(rèn)為字符串類型。
name = input("Enter your name: ")
若需要其他數(shù)據(jù)類型的輸入,需要進(jìn)行類型轉(zhuǎn)換。
# 獲取整數(shù)輸入
age = int(input("Enter your age: "))
# 獲取浮點(diǎn)數(shù)輸入
height = float(input("Enter your height: "))
range
函數(shù)返回一個(gè)數(shù)字序列,例如,range(0, n)
生成從 0 到 n-1 的數(shù)字。
# 生成 0 到 9 的數(shù)字序列
numbers = list(range(10))
print(numbers) # 輸出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 生成 2 到 10 的偶數(shù)序列
even_numbers = list(range(2, 11, 2))
print(even_numbers) # 輸出: [2, 4, 6, 8, 10]
注釋用于提高代碼的可讀性,不會被編譯器或解釋器執(zhí)行。
# 這是一個(gè)單行注釋
"""
這是一個(gè)多行注釋,
可以跨越多行。
"""
轉(zhuǎn)義序列是在字符串字面量或字符中使用時(shí),不表示自身的字符序列,而是被翻譯成另一個(gè)字符。
print("Hello\nWorld!") # 輸出: Hello\nWorld!(兩行)
print("This is a backslash: \\") # 輸出: This is a backslash: \
print("This is a single quote: \'") # 輸出: This is a single quote: '
print("Name\tAge\tCountry") # 輸出: Name Age Country
print("Hello\bWorld!") # 輸出: HelloWorld!(退格)
print("\110\145\154\154\157") # 輸出: Hello(八進(jìn)制表示)
print("\x48\x65\x6c\x6c\x6f") # 輸出: Hello(十六進(jìn)制表示)
print("Hello\rWorld!") # 輸出: World!(回車,覆蓋前面的內(nèi)容)
Python 字符串是由字符組成的序列,可以通過索引單獨(dú)訪問每個(gè)字符。
可以使用單引號或雙引號創(chuàng)建字符串。
string1 = 'Hello'
string2 = "World"
字符串中每個(gè)字符的位置從 0 開始,依次遞增。
string = "Hello"
print(string[0]) # 輸出: H
print(string[4]) # 輸出: o
切片用于從給定字符串中獲取子字符串。
string = "Hello, World!"
print(string[0:5]) # 輸出: Hello
print(string[7:]) # 輸出: World!
print(string[:5]) # 輸出: Hello
print(string[::2]) # 輸出: Hlo, Wr!
如果字符串中的所有字符都是字母數(shù)字,則返回 True,否則返回 False。
print("Hello123".isalnum()) # 輸出: True
print("Hello 123".isalnum()) # 輸出: False
如果字符串中的所有字符都是字母,則返回 True,否則返回 False。
print("Hello".isalpha()) # 輸出: True
print("Hello123".isalpha()) # 輸出: False
如果字符串中的所有字符都是十進(jìn)制數(shù)字,則返回 True,否則返回 False。
print("12345".isdecimal()) # 輸出: True
print("12.34".isdecimal()) # 輸出: False
如果字符串中的所有字符都是數(shù)字,則返回 True,否則返回 False。
print("12345".isdigit()) # 輸出: True
print("Hello123".isdigit()) # 輸出: False
如果字符串中的所有字符都是小寫字母,則返回 True,否則返回 False。
print("hello".islower()) # 輸出: True
print("Hello".islower()) # 輸出: False
如果字符串中的所有字符都是空白字符,則返回 True,否則返回 False。
print(" ".isspace()) # 輸出: True
print("Hello".isspace()) # 輸出: False
如果字符串中的所有字符都是大寫字母,則返回 True,否則返回 False。
print("HELLO".isupper()) # 輸出: True
print("Hello".isupper()) # 輸出: False
將字符串轉(zhuǎn)換為小寫。
print("Hello".lower()) # 輸出: hello
將字符串轉(zhuǎn)換為大寫。
print("hello".upper()) # 輸出: HELLO
移除字符串開頭和結(jié)尾的空白字符。
print(" Hello, World! ".strip()) # 輸出: Hello, World!
Python 列表是用方括號括起來的逗號分隔值的集合,可以包含不同數(shù)據(jù)類型的元素。
list1 = [1, 2, 3, 4, 5]
list2 = ["apple", "banana", "cherry"]
list3 = [1, "apple", 3.14, True]
列表中每個(gè)元素的位置從 0 開始,依次遞增。
list = [10, 20, 30, 40, 50]
print(list[0]) # 輸出: 10
print(list[4]) # 輸出: 50
返回指定值的第一個(gè)元素的索引。
list = [10, 20, 30, 40, 50]
print(list.index(30)) # 輸出: 2
在列表末尾添加一個(gè)元素。
list = [10, 20, 30]
list.append(40)
print(list) # 輸出: [10, 20, 30, 40]
將一個(gè)給定列表(或任何可迭代對象)的元素添加到當(dāng)前列表的末尾。
list1 = [10, 20, 30]
list2 = [40, 50]
list1.extend(list2)
print(list1) # 輸出: [10, 20, 30, 40, 50]
在指定位置添加一個(gè)元素。
list = [10, 20, 40, 50]
list.insert(2, 30)
print(list) # 輸出: [10, 20, 30, 40, 50]
移除指定位置的元素并返回它。
list = [10, 20, 30, 40, 50]
removed_element = list.pop(2)
print(removed_element) # 輸出: 30
print(list) # 輸出: [10, 20, 40, 50]
移除列表中第一個(gè)出現(xiàn)的指定值。
list = [10, 20, 30, 40, 50]
list.remove(30)
print(list) # 輸出: [10, 20, 40, 50]
移除列表中的所有元素。
list = [10, 20, 30]
list.clear()
print(list) # 輸出: []
返回具有指定值的元素?cái)?shù)量。
list = [10, 20, 10, 30, 10]
print(list.count(10)) # 輸出: 3
反轉(zhuǎn)列表的順序。
list = [10, 20, 30, 40, 50]
list.reverse()
print(list) # 輸出: [50, 40, 30, 20, 10]
對列表進(jìn)行排序。
list = [30, 10, 40, 20, 50]
list.sort()
print(list) # 輸出: [10, 20, 30, 40, 50]
元組是用括號括起來的逗號分隔值的集合,可以包含不同數(shù)據(jù)類型的元素。
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ("apple", "banana", "cherry")
tuple3 = (1, "apple", 3.14, True)
元組中每個(gè)元素的位置從 0 開始,依次遞增。
tuple = (10, 20, 30, 40, 50)
print(tuple[0]) # 輸出: 10
print(tuple[4]) # 輸出: 50
返回元組中指定值出現(xiàn)的次數(shù)。
tuple = (10, 20, 10, 30, 10)
print(tuple.count(10)) # 輸出: 3
在元組中查找指定值并返回其位置。
tuple = (10, 20, 30, 40, 50)
print(tuple.index(30)) # 輸出: 2
集合是用花括號括起來的多個(gè)值的集合,是無序且不帶索引的。
set1 = {"apple", "banana", "cherry"}
set2 = set(["apple", "banana", "cherry"])
向集合中添加一個(gè)元素。
set = {"apple", "banana", "cherry"}
set.add("orange")
print(set) # 輸出: {'apple', 'banana', 'cherry', 'orange'}
移除集合中的所有元素。
set = {"apple", "banana", "cherry"}
set.clear()
print(set) # 輸出: set()
從集合中移除指定元素。
set = {"apple", "banana", "cherry"}
set.discard("banana")
print(set) # 輸出: {'apple', 'cherry'}
返回兩個(gè)或更多集合的交集。
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "banana", "apple"}
print(set1.intersection(set2)) # 輸出: {'apple', 'banana'}
檢查一個(gè)集合是否是另一個(gè)集合的子集。
set1 = {"apple", "banana"}
set2 = {"apple", "banana", "cherry"}
print(set1.issubset(set2)) # 輸出: True
從集合中移除一個(gè)元素。
set = {"apple", "banana", "cherry"}
removed_element = set.pop()
print(removed_element) # 輸出: 'apple'(或另一個(gè)隨機(jī)元素)
print(set) # 輸出: {'banana', 'cherry'}(或另一個(gè)組合)
從集合中移除指定元素。
set = {"apple", "banana", "cherry"}
set.remove("banana")
print(set) # 輸出: {'apple', 'cherry'}
返回兩個(gè)或更多集合的并集。
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "banana", "apple"}
print(set1.union(set2)) # 輸出: {'apple', 'banana', 'cherry', 'google'}
字典是無序的鍵值對集合,用花括號括起來,要求字典中的鍵是唯一的。
dict1 = {"name": "John", "age": 30, "city": "New York"}
可以通過放置兩個(gè)花括號來創(chuàng)建一個(gè)空白字典。
empty_dict = {}
dict = {"name": "John", "age": 30}
dict["city"] = "New York"
print(dict) # 輸出: {'name': 'John', 'age': 30, 'city': 'New York'}
如果指定的鍵已經(jīng)存在,則其值將被更新。
dict = {"name": "John", "age": 30}
dict["age"] = 35
print(dict) # 輸出: {'name': 'John', 'age': 35}
使用 del
關(guān)鍵字刪除指定的鍵值對。
dict = {"name": "John", "age": 30, "city": "New York"}
del dict["age"]
print(dict) # 輸出: {'name': 'John', 'city': 'New York'}
返回字典中元素(鍵值對)的數(shù)量。
dict = {"name": "John", "age": 30, "city": "New York"}
print(len(dict)) # 輸出: 3
移除字典中的所有元素。
dict = {"name": "John", "age": 30, "city": "New York"}
dict.clear()
print(dict) # 輸出: {}
返回指定鍵的值。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.get("name")) # 輸出: John
返回一個(gè)包含字典中每個(gè)鍵值對的元組的列表。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.items()) # 輸出: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
返回一個(gè)包含字典中鍵的列表。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.keys()) # 輸出: dict_keys(['name', 'age', 'city'])
返回一個(gè)包含字典中值的列表。
dict = {"name": "John", "age": 30, "city": "New York"}
print(dict.values()) # 輸出: dict_values(['John', 30, 'New York'])
用指定的鍵值對更新字典。
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
dict1.update(dict2)
print(dict1) # 輸出: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
在 Python 中,縮進(jìn)是指代碼塊使用空格或制表符進(jìn)行縮進(jìn),以便解釋器能夠輕松執(zhí)行 Python 代碼。
縮進(jìn)應(yīng)用于條件語句和循環(huán)控制語句??s進(jìn)指定了根據(jù)條件要執(zhí)行的代碼塊。
if
、elif
和 else
語句是 Python 中的條件語句,它們實(shí)現(xiàn)了選擇結(jié)構(gòu)(決策結(jié)構(gòu))。
age = 20
if age >= 18:
print("You are an adult.")
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("D")
num = 10
if num > 0:
if num % 2 == 0:
print("Positive and even")
else:
print("Positive and odd")
else:
print("Non-positive")
循環(huán)或迭代語句會反復(fù)執(zhí)行一個(gè)語句,直到控制表達(dá)式為假。
Python 的 for 循環(huán)設(shè)計(jì)用于處理任何序列(如列表或字符串)中的項(xiàng)。
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
while 循環(huán)是一種條件循環(huán),只要條件為真,就會重復(fù)執(zhí)行內(nèi)部的指令。
count = 0
while count < 5:
print(count)
count += 1
break 語句允許程序跳過代碼的一部分。break 語句終止它所在的循環(huán)。
for num in range(10):
if num == 5:
break
print(num) # 輸出: 0, 1, 2, 3, 4
continue 語句跳過循環(huán)的其余部分,并導(dǎo)致下一次迭代發(fā)生。
for num in range(10):
if num % 2 == 0:
continue
print(num) # 輸出: 1, 3, 5, 7, 9
函數(shù)是一段執(zhí)行特定任務(wù)的代碼塊。你可以將參數(shù)傳遞給函數(shù)。它有助于使我們的代碼更加有組織和易于管理。
在定義函數(shù)之前使用 def
關(guān)鍵字。
def greet(name):
print(f"Hello, {name}!")
每當(dāng)在程序中需要該代碼塊時(shí),只需調(diào)用該函數(shù)的名稱。如果在定義函數(shù)時(shí)傳遞了參數(shù),那么在調(diào)用函數(shù)時(shí)也需要傳遞參數(shù)。
greet("John") # 輸出: Hello, John!
函數(shù)的 return 語句將指定的值或數(shù)據(jù)項(xiàng)返回給調(diào)用者。
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 輸出: 8
參數(shù)是定義和調(diào)用函數(shù)時(shí)括號內(nèi)傳遞的值。
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("John", 30) # 輸出: Hello, John! You are 30 years old.
文件處理是指讀取或?qū)懭胛募械臄?shù)據(jù)。Python 提供了一些函數(shù),允許我們操作文件中的數(shù)據(jù)。
file = open("example.txt", "r")
file = open("example.txt", "r")
# 操作文件
file.close()
read
函數(shù)包含不同的方法:read()
、readline()
和 readlines()
。
read()
返回文件中的所有內(nèi)容。readline()
返回文件中的一行。readlines()
返回一個(gè)包含文件中各行的列表。file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
此函數(shù)將字符串序列寫入文件。
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
異常是導(dǎo)致程序流程中斷的不尋常情況。
這是 Python 中的基本 try-catch 塊。當(dāng) try 塊拋出錯誤時(shí),控制權(quán)轉(zhuǎn)到 except 塊。
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
如果 try 塊沒有引發(fā)任何異常,并且代碼成功運(yùn)行,則執(zhí)行 else 塊。
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print(f"Result: {result}")
無論 try 塊的代碼是否成功運(yùn)行,還是 except 塊的代碼被執(zhí)行,finally 塊的代碼都將被執(zhí)行。finally 塊的代碼將強(qiáng)制執(zhí)行。
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("This will always execute.")
這是一種主要關(guān)注使用對象和類的編程方法。對象可以是任何現(xiàn)實(shí)世界的實(shí)體。
在 Python 中編寫類的語法。
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}!")
可以通過以下方式實(shí)例化對象:
obj = MyClass("John")
obj.greet() # 輸出: Hello, John!
self 參數(shù)是類中任何函數(shù)的第一個(gè)參數(shù)。它可以有不同的名稱,但在類中定義任何函數(shù)時(shí)必須有此參數(shù),因?yàn)樗糜谠L問類的其他數(shù)據(jù)成員。
構(gòu)造函數(shù)是類的特殊函數(shù),用于初始化對象。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
通過使用繼承,我們可以創(chuàng)建一個(gè)類,該類使用另一個(gè)類的所有屬性和行為。新類被稱為派生類或子類,而被獲取屬性的類被稱為基類或父類。
它提供了代碼的可重用性。
filter 函數(shù)允許處理可迭代對象并提取滿足給定條件的項(xiàng)。
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 輸出: [2, 4]
用于查找一個(gè)類是否是指定類的子類。
class Parent:
pass
class Child(Parent):
pass
print(issubclass(Child, Parent)) # 輸出: True
以下是 Python 編程語言的一些高級主題,如迭代器和生成器。
用于創(chuàng)建可迭代對象的迭代器。
numbers = [1, 2, 3, 4, 5]
iterator = iter(numbers)
print(next(iterator)) # 輸出: 1
print(next(iterator)) # 輸出: 2
用于動態(tài)生成值。
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
counter = count_up_to(5)
print(next(counter)) # 輸出: 1
print(next(counter)) # 輸出: 2
裝飾器用于修改函數(shù)或類的行為。它們通常在要裝飾的函數(shù)定義之前調(diào)用。
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
用于設(shè)置屬性 'name'。
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
用于刪除屬性 'name'。
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.deleter
def name(self):
del self._name
更多建議: