I/O
我们用输入做一个简单的小游戏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 adjective1=input ("Enter an adjective(description): " ) noun1=input ("Enter a noun(person,place,thing): " ) adjective2=input ("Enter an adjective(description): " ) verb1=input ("Enter a verb ending with 'ing': " ) adjective3=input ("Enter an adjective(description): " )print (f"Today I went to a {adjective1} zoo" )print (f"In an exhibit,I saw a {noun1} " )print (f"{noun1} was {adjective2} and {verb1} " )print (f"I was {adjective3} !" )
f 是 Python 中的 “格式化字符串前缀”,可以直接在字符串中嵌入变量、表达式 ,并让 Python 自动计算并替换其值 。
1 2 3 4 Today I went to a dangerous zoo In an exhibit,I saw a Richard Richard was wonderful and fucking I was joyful!
Python 中支持使用逻辑符号 and、or、not 来进行逻辑判断:
1 2 3 4 5 6 7 8 sunny=true temperature = int (input ("Enter the temperature: " ))if temperature > 30 and temperature < 40 : print ("It's hot outside" )elif temperature < 30 or not sunny: print ("It's cold outside" )else : print ("It's not hot outside" )
String in Python
相比于 C/C++ 中,在Python中,字符串在使用上相对来说更加灵活,方法也更丰富。
1.大小写转换
str.capitalize():将字符串的第一个字符大写,其余字符小写。
1 2 name = "hello world" print (name.capitalize())
str.casefold():将字符串转换为小写,支持更多语言(如德语)。
1 2 name = "HELLO WORLD" print (name.casefold())
1 2 name = "HELLO WORLD" print (name.lower())
1 2 name = "hello world" print (name.upper())
str.swapcase():将字符串中的大小写互换。
1 2 name = "Hello World" print (name.swapcase())
str.title():将字符串中每个单词的首字母大写。
1 2 name = "hello world" print (name.title())
2.查找与替换
str.find(sub[, start[, end]]):查找子字符串,返回第一次出现的索引,未找到返回 -1。
1 2 name = "hello world" print (name.find("world" ))
str.rfind(sub[, start[, end]]):从右向左查找子字符串,返回第一次出现的索引,未找到返回 -1。
1 2 name = "hello world" print (name.rfind("o" ))
str.replace(old, new[, count]):替换字符串中的子字符串。
1 2 name = "hello world" print (name.replace("world" , "python" ))
3.判断
str.isalnum():判断字符串是否只包含字母和数字。
1 2 name = "hello123" print (name.isalnum())
str.isalpha():判断字符串是否只包含字母。
1 2 name = "hello" print (name.isalpha())
str.isdigit():判断字符串是否只包含数字。
1 2 num = "123" print (num.isdigit())
str.islower():判断字符串是否全部为小写。
1 2 name = "hello" print (name.islower())
str.isupper():判断字符串是否全部为大写。
1 2 name = "HELLO" print (name.isupper())
4.统计
str.count(sub[, start[, end]]):统计子字符串出现的次数。
1 2 name = "hello world" print (name.count("o" ))
DataStructures
(I)List
可以存储任意类型 的数据,动态改变大小 ,类似于 CPP 中的vector动态数组,用方括号[]表示,元素之间用逗号隔开。
1.列表的创建
使用方括号 []创建列表。
使用 list() 函数将其他可迭代对象转换为列表。
1 2 3 my_list=[1 ,str ,1.2 ,'hello' ]print (my_list)
1 2 3 4 5 6 empty_list = [] fruits = ["apple" , "banana" , "cherry" ] numbers = list (range (5 ))
2.访问列表元素
使用索引访问列表元素(索引从 0 开始)。
使用负数索引从列表末尾访问元素。
1 2 3 fruits = ["apple" , "banana" , "cherry" ]print (fruits[0 ]) print (fruits[-1 ])
3.修改列表元素
1 2 3 fruits = ["apple" , "banana" , "cherry" ] fruits[1 ] = "blueberry" print (fruits)
4.其他操作列表的方法
添加元素
1 2 3 fruits = ["apple" , "banana" ] fruits.append ("cherry" )print (fruits) # 输出: ['apple' , 'banana' , 'cherry' ]
extend():将另一个可迭代对象的元素添加到列表末尾。
1 2 3 fruits = ["apple" , "banana" ] fruits.extend(["cherry" , "orange" ])print (fruits)
1 2 3 fruits = ["apple" , "banana" ] fruits.insert(1 , "cherry" )print (fruits)
删除元素
1 2 3 fruits = ["apple" , "banana" , "cherry" ] fruits.remove("banana" )print (fruits)
pop():删除并返回指定位置的元素(默认删除最后一个元素)。
1 2 3 fruits = ["apple" , "banana" , "cherry" ] fruits.pop(1 ) print (fruits)
1 2 3 fruits = ["apple" , "banana" , "cherry" ] fruits.clear()print (fruits)
查找元素
1 2 fruits = ["apple" , "banana" , "cherry" ]print (fruits.index("banana" ))
1 2 fruits = ["apple" , "banana" , "cherry" , "banana" ]print (fruits.count ("banana" )) # 输出: 2
排序与反转
1 2 3 numbers = [3, 1, 4, 1, 5, 9] numbers.sort() print(numbers) # 输出: [1, 1, 3, 4, 5, 9]
1 2 3 fruits = ["apple" , "banana" , "cherry" ] fruits.reverse()print (fruits)
1 2 3 4 5 6 7 fruits = ["banana" ,"apple" , "cherry" ]print (sorted (fruits))print (fruits)''' ['apple', 'banana', 'cherry'] ['banana', 'apple', 'cherry'] '''
列表的遍历
使用 for 循环遍历列表。
1 2 3 fruits = ["apple" , "banana" , "cherry" ]for fruit in fruits: print (fruit)
列表的切片
使用切片操作获取列表的子集。
语法:list[start:stop:step]
1 2 3 4 numbers = [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]print (numbers[2 :5 ]) print (numbers[::2 ]) print (numbers[::-1 ])
列表的复制
使用切片或 copy() 方法复制列表。
1 2 3 fruits = ["apple" , "banana" , "cherry" ] fruits_copy = fruits[:] fruits_copy2 = fruits.copy()
列表推导式
使用列表推导式快速生成列表。
1 2 3 4 5 6 7 squares = [x**2 for x in range (10 )]print (squares) evens = [x for x in range (10 ) if x % 2 == 0 ]print (evens)
列表的嵌套
列表可以包含其他列表,形成嵌套列表。
1 2 3 4 5 6 matrix = [ [1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ] ]print (matrix[1 ][2 ])
列表的其他操作
1 2 3 4 5 6 7 fruits = ["apple" , "banana" , "cherry" ]print (len (fruits)) in 和 not in :检查元素是否在列表中。 ```python fruits = ["apple" , "banana" , "cherry" ]print ("banana" in fruits) + 和 *:列表的拼接和重复。
1 2 3 4 list1 = [1 , 2 , 3 ] list2 = [4 , 5 , 6 ]print (list1 + list2) print (list1 * 2 )
(II) Tuple
在 Python 中,元组(Tuple) 是一种不可变的序列类型,用于存储一组有序的元素。元组与列表(list)类似,但元组一旦创建,其内容不可修改。
不可变性 :元组一旦创建,其元素不能被修改、添加或删除。
有序性 :元组中的元素是有序的,可以通过索引访问。
异构性 :元组可以存储不同类型的元素(如整数、字符串、列表等)。
支持嵌套 :元组可以嵌套其他元组或列表。
元组使用圆括号 () 定义,元素之间用逗号 , 分隔。
元组的创建
1 2 3 4 5 6 7 8 9 10 11 my_tuple = (1 , 2 , 3 )print (my_tuple) mixed_tuple = (1 , "hello" , 3.14 , [1 , 2 , 3 ])print (mixed_tuple) empty_tuple = ()print (empty_tuple)
如果元组只有一个元素,需要在元素后面加一个逗号 ,,否则会被认为是普通括号。
1 2 single_element_tuple = (42 ,) not_a_tuple = (42 )
元组的遍历
1 2 3 4 5 6 7 8 9 10 my_tuple = (10 , 20 , 30 , 40 , 50 )print (my_tuple[0 ]) print (my_tuple[-1 ]) print (my_tuple[1 :4 ])
元组是不可变的,因此不能修改、添加或删除元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 my_tuple = (1 , 2 , 3 ) my_tuple[0 ] = 10 my_tuple.append(4 ) del my_tuple[0 ] my_tuple=(4 ,5 ,6 ) tuple1 = (1 , 2 , 3 ) tuple2 = (4 , 5 , 6 ) combined_tuple = tuple1 + tuple2print (combined_tuple)
元组的基本操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 tuple1 = (1 , 2 , 3 ) tuple2 = (4 , 5 , 6 ) combined_tuple = tuple1 + tuple2print (combined_tuple) my_tuple = (1 , 2 , 3 ) repeated_tuple = my_tuple * 3 print (repeated_tuple) my_tuple = (1 , 2 , 3 , 4 , 5 )print (len (my_tuple)) my_tuple = (1 , 2 , 3 , 4 , 5 )for item in my_tuple: print (item) my_tuple = (10 , 20 , 30 ) a, b, c = my_tupleprint (a, b, c) nested_tuple = ((1 , 2 ), (3 , 4 ), [5 , 6 ])print (nested_tuple)
元组与列表的区别
特性
元组 (tuple)
列表 (list)
可变性
不可变
可变
语法
使用圆括号 ()
使用方括号 []
性能
访问速度更快,占用内存更少
访问速度较慢,占用内存较多
适用场景
存储不可变数据(如常量、配置等)
存储可变数据(如动态集合等)、
(III) Dictionaries
字典dict,字典中的元素是键值对 ,类似与CPP中的unordered_map,底层原理是哈希表 (Hash Table),用花括号{}表示,字典中的键必须是唯一的,而值可以是任意类型的数据。键-值对之间用冒号 分隔,元素之间用逗号 分隔
1 2 3 4 my_dict={'name' :'richard' ,'age' :18 ,'city' :'Nanjing' }print (my_dict['name' ]) print (my_dict['age' ]) print (my_dict['city' ])
字典的创建
1 2 3 4 5 6 7 8 9 10 11 12 my_dict = {"name" : "Alice" , "age" : 25, "city" : "New York" }print (my_dict) # 输出: {'name' : 'Alice' , 'age' : 25, 'city' : 'New York' } empty_dict = {}print (empty_dict) # 输出: {} my_dict = dict(name ="Alice" , age =25, city ="New York" )print (my_dict) # 输出: {'name' : 'Alice' , 'age' : 25, 'city' : 'New York' }
通过键来访问字典的值
1 2 3 4 5 6 7 8 9 10 11 12 my_dict = {"name" : "Alice" , "age" : 25 , "city" : "New York" }print (my_dict["name" ]) print (my_dict.get("name" )) print (my_dict.get("gender" )) print (my_dict.get("gender" , "unknown" ))
修改,插入,删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 my_dict = {"name" : "Alice" , "age" : 25 , "city" : "New York" } my_dict["age" ] = 26 print (my_dict) my_dict["gender" ] = "female" print (my_dict) del my_dict["city" ]print (my_dict) age = my_dict.pop("age" )print (age) print (my_dict) my_dict.clear()print (my_dict)
其他操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 my_dict = {"name" : "Alice" , "age" : 25 , "city" : "New York" }for key in my_dict: print (key)for value in my_dict.values(): print (value)for key, value in my_dict.items(): print (f"{key} : {value} " ) my_dict = {"name" : "Alice" , "age" : 25 , "city" : "New York" }print ("name" in my_dict) print ("gender" in my_dict) print (my_dict.keys()) print (my_dict.values()) print (my_dict.items()) dict1 = {"name" : "Alice" , "age" : 25 } dict2 = {"city" : "New York" , "gender" : "female" ,"age" :15 } dict1.update(dict2)print (dict1)
字典推导式
1 2 3 squares = {x: x**2 for x in range (5 )}print (squares)
Loops
While-loops
在Python中,while循环的基本用法和 C/C++ 基本相同,唯一需要注意的是Python中不加花括号 并且要注意缩进
1 2 3 4 count = 0 while count < 5 : print (f"Count is: {count} " ) count += 1
for-loops
列表
1 2 3 fruits=['apple' ,'banana' ,'orange' ]for fruit in fruits: print (fruit)
字符串
1 2 for char in 'hello' : print (char)
range()范围函数
range(start, stop, step)
生成从 start 开始到 stop-1 的整数序列,步长为 step
1 2 3 4 5 6 7 8 9 for i in range(1, 10, 2): print(i) ''' 1 3 5 7 9 '''
字典
1 2 3 person={'name' :'richard' ,'age' :18 ,'city' :'Nanjing' }for key,value in person.items(): print (key,value)
使用 zip()
zip() 函数可以同时遍历多个序列。
1 2 3 4 names = ['Alice' , 'Bob' , 'Charlie' ] scores = [85 , 90 , 95 ]for name, score in zip (names, scores): print (f'{name} scored {score} ' )
其他语句
条件语句
1 2 3 4 5 6 if condition: do somethingelif another_condition: do something else else : do something else
with 语句
with语句用于简化资源的管理,能在代码块执行完毕后自动关闭资源。
1 2 3 with open ('file.txt' ,'r' ) as f: data=f.read() print (data)
try 语句
常用于捕获和处理可能发生的异常 。
try : 可能出现异常的代码
except : 特定类型的异常
else : 未发生异常的情况
finally : 无论是否发生异常都会执行
1 2 3 4 5 6 7 8 try : result=10 /0 except : print ('发生异常' )else : print ('没有发生异常' )finally : print ('finally' )
三元运算符
1 2 3 age=int (input ("Enter your age:" )) status="Adult" if age>=18 else "Child" print (status)
用for循环制作一个简易的倒计时程序
1 2 3 4 5 6 7 8 9 10 11 12 import time my_time=int (input ("Enter the time in seconds: " ))for x in range (my_time,0 ,-1 ): second=x%60 minute=int (x/60 )%60 hour=int (x/3600 ) print (f"{hour:02} :{minute:02} :{second:02} " ) time.sleep(1 )print ("Time's Up!" )
1 2 3 4 5 6 Enter the time in seconds: 4500 01:15:00 01:14:59 01:14:58 01:14:57 01:14:56
▶
什么时候使用 if__name__==__main__: ?
当我们在看一些开源项目时,经常能看到在结尾有一段“神秘代码”:
1 2 if __name__ == "__main__" : main()
或许会疑惑:没有这个其他代码也可以正常执行,为什么要有这一段代码呢?那么不妨先让我们看看__name__输出是什么:
1 2 3 if __name__=="__main__" : print (__name__)
当我们在其他文件中引用这个文件时:
1 2 3 4 5 6 7 8 import test_1if __name__=="__main__" : print (__name__)
这说明__name__在不同的地方是不一样的,当我们在当前文件中运行时,__name__为__main__,而当我们在其他文件中引用时,__name__为包名和模块名(__name__ 是 Python 解释器自带的「内置变量」(不需要我们手动定义」),它的作用是「标识当前模块的运行状态)。
当我们导入一个模块时,可能我们只是想调用里面的函数,而不是运行模块中的代码。
1 2 3 4 5 6 7 8 9 10 11 12 def add (a,b ): return a+bdef sub (a,b ): return a-bprint ("This is a simple calculator" ) num1=int (input ("Enter the first number: " )) num2=int (input ("Enter the second number: " ))print (f"The sum of {num1} and {num2} is {add(num1,num2)} " )print (f"The difference of {num1} and {num2} is {sub(num1,num2)} " )
1 2 3 4 5 6 7 8 9 import calculator num1=10 num2=20 print ("Using the calculator module" )print (f"The sum of {num1} and {num2} is {calculator.add(num1,num2)} " )print (f"The difference of {num1} and {num2} is {calculator.sub(num1,num2)} " )
让我们看看结果何如:
1 2 3 4 5 6 7 8 This is a simple calculator Enter the first number: 2 Enter the second number: 2 The sum of 2 and 2 is 4 The difference of 2 and 2 is 0 Using the calculator module The sum of 10 and 20 is 30 The difference of 10 and 20 is -10
可以看到我们明明只想要调用calculator模块中的add和sub函数,但是程序中却执行了calculator模块中的所有代码,包括打印提示信息和获取用户输入。这时,if __name__ == '__main__':就起作用了!
让我们对calculator.py稍作修改:
1 2 3 4 5 6 7 8 9 10 11 12 def add (a,b ): return a+bdef sub (a,b ): return a-bif __name__=="__main__" : print ("This is a simple calculator" ) num1 = int (input ("Enter the first number: " )) num2 = int (input ("Enter the second number: " )) print (f"The sum of {num1} and {num2} is {add(num1, num2)} " ) print (f"The difference of {num1} and {num2} is {sub(num1, num2)} " )
运行结果如下:
1 2 3 Using the calculator module The sum of 10 and 20 is 30 The difference of 10 and 20 is -10
Class Variables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Car : def __init__ (self,model,year,color,for_sale ): self .model=model self .year=year self .color=color self .for_sale=for_sale car1=Car("Mustang" ,2024 ,"red" ,False ) car2=Car("Corvette" ,2025 ,"blue" ,True )print (car1.model)print (car1.year)print (car1.color)print (car1.for_sale)
我们还可以将类单独放在一个文件中,使用模块化的方法导入到主程序中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Car : cars_owner="Richard" cars_num=0 def __init__ (self,model,year,color,for_sale ): self .model=model self .year=year self .color=color self .for_sale=for_sale Car.cars_num+=1
1 2 3 4 5 6 7 from car import Car car1=Car("Mustang" ,2024 ,"red" ,False ) car2=Car("Corvette" ,2025 ,"blue" ,True )print (Car.cars_num)
Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Animal : def __init__ (self,name ): self .name=name self .is_alive=True def eat (self ): print (f"{self.name} is eating!" ) def sleep (self ): print (f"{self.name} is sleeping!" )class Dog (Animal ): def speak (self ): print ("WOOF!" )class Cat (Animal ): def speak (self ): print ("MEOW!" )class Mouse (Animal ): print ("SOUEEK!" ) dog=Dog("Scooby" ) cat=Cat("Garfield" ) mouse=Mouse("Mickey" )print (dog.is_alive)
Abstract
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 from abc import ABC,abstractmethodclass Vehicle (ABC ): @abstractmethod def go (self ): pass @abstractmethod def stop (self ): pass class Car (Vehicle ): def go (self ): print ("You drive the car" ) def stop (self ): print ("You stop the car" )class Motorcycle (Vehicle ): def go (self ): print ("You drive the motorcycle" ) def stop (self ): print ("You stop the motorcycle" ) car=Car() motorcycle=Motorcycle()
SuperFunction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Shape : def __init__ (self,color,is_filled ): self .color=color self .is_filled=is_filled def describe (self ): print (f"It's {self.color} and {'filled' if self.is_filled else 'not filled' } ." )class Circle (Shape ): def __init__ (self,color,is_filled,radius ): super ().__init__(color,is_filled) self .radius=radius def describe (self ): super ().describe() print (f"It's a corcle with an area of {3.14 *self.radius*self.radius} cm^2." ) circle=Circle(color="red" ,is_filled=True ,radius=5 ) circle.describe()