1.结构体
customer = {
“age”: “23”,
“name”: “mary”,
“is_verifyed”: True
}
print(customer[“name”])
print(customer.get(“age”))#与上式相同,get只能用于结构体
print(customer.get(“friend”, “Jame”))#赋给新变量一个值
2.翻译(结构体)
phone = input("Phone: ")
dictionary = {
“1”: “one”,
“2”: “two”,
“3”: “three”,
“4”: “four”
}
output = “”
for ch in phone:
output += dictionary.get(ch, “!”) + " "
#get函数表明:如果检测到了就输出,否则输出!
print(output)
3.分割字符串
phone = input(">")
output = phone.split(" ")#这里是用空格作为分割依据,你可以随意设定
print(output)
4.自定义函数def
(1)不带返回值
def happy(first, last): #这里的first和last是形参
print(f""“I am happy
how are you {first}{last}
Darling “””)
#两空行,这样比较规范
happy(“marry”,“waston”)#这里的是实参
happy(last=“marry”, first=“waston”)#这里是关键字参数
(2)带返回值
def square(number):
return number * number
5.重命名变量
右键点击refactor
6.input(" “)函数的返回值是字符串
如果想要得到数字,需要int(input(” "))
7.处理错误,防止程序崩溃
try:
age = int(input(“Age:”))
income = 20
risk = income / age
print(age)
except ZeroDivisionError: #这里考虑错误类型
print(“Age can not be zero”)
except ValueError:
print(“Invalid value”)
8.定义class
(1)
class Point: #首字母大写
def move(self):
print(“Move”)
def draw(self):
print("Draw")
point1 = Point()
point1.draw()
9.class加上构造
(1)
class Point: #构造
def init(self, x, y): #self 是类的实例化对象
self.x = x
self.y = y
#构造
def move(self):
print("Move")
def draw(self):
print("Draw")
point1 = Point(10, 2)
print(point1.y)
(2)在class中引用参数必须加上self.
class Person:
def init(self, name):
self.name = name
def talk(self):
print(f"Hi, I am {self.name}")
10.class加上继承
class Mammal:
def walk(self):
print(“walk”)
class Dog(Mammal):
pass # python不能有空类
class Cat(Mammal):
pass
dog1 = Dog()
dog1.walk()