Python学习笔记Day5
元祖
可以存储项目列表,但与列表不同,元祖是不可变的,无法改变。
python中有一个叫做解压缩的特性,不仅适用于元祖,也适用于列表
numbers=(1,2,3)
x,y,z = numbers
字典
字典中每个键值都是唯一的,不允许重复获得键值使用get方法,如果字典中没有这个key我们可以提供默认值
增加更改键值
customer = {
"name":"h",
"age":25,
"is_verified":True
}
customer["name"] ="c"
customer["birth"]="1997 0725"
print(customer.get("birth"))
print(customer.get("name"))
Phone = input("phone")
number={
"1": "ONE",
"2": "TWO",
"3": "THREE"
}
output = ""
for ch in Phone:
output += number.get(ch,"!")+ " "
print(output)
对输入字符串进行分割成单个
message = input(">")
words = message.split(' ')###分割方法
print(words)
message = input(">")
words = message.split(' ')
emojis = {
":)" :"😊",
":(" :"😒"
}
output = ""
for word in words:
output += emojis.get(word,word) + " "###(word,word)个人理解为检索到的用表情符号输出,检索不到直接输出检索内容
print(output)
函数
def 函数名()
def greet_user(first_name,last_name):
print(f'hi {first_name} {last_name}')
print("welcome")
print("start")
greet_user(last_name="chao",first_name="he")##关键字参数可以无需在意参数位置,大多数时选用关键字参数增加代码可读性
print("finish")
程序异常处理
Process finished with exit code 0,成功退出无错误
Process finished with exit code 1,代码崩溃
try:
age = int(input('age:'))
income = 10000
risk = income / age
print(age)
except ZeroDivisionError:##0除法误差
print('被除数不能为0')
except ValueError:##值误差
print('Invalid value')
类,对象,属性,方法的浅见
类就是对某种设定的一个大的集合,譬如黑猫,白猫都是猫。猫就是一个类,是抽象的,对象则是一个具体化的实例,譬如黑猫,白猫。方法则是对对象进行操作,譬如猫进食,玩耍。属性则是在过程中对对象进行赋值
譬如猫的颜色是黑色和白色。
构造函数
个人理解为就是给对象实例增加属性,譬如猫的颜色
继承
先定义一个类,在后续过程中,其他的类可以使用该类
class Activity:
def walk(self):
print("walk")
class Dog(Activity):
pass
class Cat(Activity):
pass
dog1 = Dog()
dog1.walk()