AI智能
改变未来

Python语法2

[toc]###选择结构if,elif,else,使用时注意条件的先后顺序通过缩进四个空格来区分代码块

# 从控制台输入age = int(input("请输入一个年龄"))if age >= 18:print("成年")elif age < 0:print("输入错误")else:print("未成年")

###循环结构for,whil,如果做循环一般使用while,for循环一般用于遍历

# 计算1-100和的值i = 0cum = 0while i < 100:i += 1# 在Python没有++,--方法cum += iprint(cum)# 计算10的阶乘cum = 1i = 1while i < 10:cum = cum * ii = i + 1print(cum)# 直接遍历字典只能获取keydict1 = {"k1": "v1", "k2": "v2", "k3": "v3"}for key in dict1:print(key)# 获取valuefor key in dict1:print(key, dict1.get(key))# 使用items方法,返回二元组类型for i in dict1.items():print(i, type(i))# 用两个变量进行接收二元组for i, j in dict1.items():print(i, j)5050362880k1k2k3k1 v1k2 v2k3 v3(\'k1\', \'v1\') <class \'tuple\'>(\'k2\', \'v2\') <class \'tuple\'>(\'k3\', \'v3\') <class \'tuple\'>k1 v1k2 v2k3 v3

###文件读写

# 读文件f1 = open("data/data1", mode="r", encoding="utf8")# mode="r", encoding="utf8"也可以省略print(f1.read(10))  # 读取指定字符个数print(f1.readline())  # 读取一行print(f1.readlines())  # 读取所有行,并以list存储f1.close()# 写文件f2 = open("data/write1", mode="w")# w表示写文件覆盖写,a表示追加写# write只能写stringf2.write("1\\n")# writelines可以写列表f2.writelines(["1", "2", "3"])f2.close()# 读写文件# 每次读写都需要close关闭,所以可以用with open,可以自动关闭with open("data/data1") as f1:with open("data/write2", mode="w") as f2:f2.writelines(f1.readlines())D:\\ALanzhishujia\\soft\\python\\python.exe C:/Users/19768/PycharmProjects/PythonLearning/demo3.pyBeautifulis better than ugly.[\'Explicit is better than implicit.\\n\', \'Simple is better than complex.\\n\', \'Complex is better than complicated.\\n\', \'Flat is better than nested.\\n\', \'Sparse is better than dense.\\n\', \'Readability counts.\\n\', "Special cases aren\'t special enough to break the rules.\\n", \'Although practicality beats purity.\\n\', \'Errors should never pass silently.\\n\', \'Unless explicitly silenced.\\n\', \'In the face of ambiguity, refuse the temptation to guess.\\n\', \'There should be one-- and preferably only one --obvious way to do it.\\n\', "Although that way may not be obvious at first unless you\'re Dutch.\\n", \'Now is better than never.\\n\', \'Although never is often better than *right* now.\\n\', "If the implementation is hard to explain, it\'s a bad idea.\\n", \'If the implementation is easy to explain, it may be a good idea.\\n\', "Namespaces are one honking great idea -- let\'s do more of those!\\n"]

###函数

# 计算圆的面积def area_of_cycle(r):pi = 3.14print(pi * r * r)area_of_cycle(2)# 计算1-n的和def sum_1_to_n(n):cum = 0i = 1while i < n + 1:cum = cum + ii = i + 1print(cum)sum_1_to_n(10)# 计算1-n的阶乘def jieCheng(n):i = 1cum = 1while i <= n:cum = cum * ii = i + 1print(cum)jieCheng(10)# 递归实现阶乘def recursion(n):if n == 1:return 1return n * recursion(n - 1)print(recursion(10))# 计算x的n次方def power(x, n):print(x ** n)power(2, 3)# 传入大量的数求和,可以传入list中list1 = [i for i in range(1, 101)]def sum_nums_with_list(l):cum = 0for i in l:cum += iprint(cum)sum_nums_with_list(list1)# 可变参数 *,可以不用list直接传入数# args相当于一个listdef sum_nums_with_args(*args):cum = 0for i in args:cum += iprint(cum)sum_nums_with_args(1, 2, 3, 4, 5)# 等价于list2 = [1, 2, 3, 4, 5]sum_nums_with_args(list2[0], list2[1], list2[2], list2[3], list2[4])sum_nums_with_args(*list2)# 关键字参数**# **后的参数相当于传入的值进入一个字典def regsiter(name, age, address, phone, **kw):dict1 = {"name": name, "age": age, "address": address, "phone": phone, "others": kw}print(dict1)regsiter("张三", "18", "合肥", "139")regsiter("张三", "18", "合肥", "139", year="2021", month="10")# 命名关键字参数# 检查传入参数是否有year,monthdef regsiter2(name, age, address, phone, **kw):if "year" in kw.keys():print("year")if "month" in kw.keys():print("month")dict1 = {"name": name, "age": age, "address": address, "phone": phone, "others": kw}print(dict1)regsiter2("张三", "18", "合肥", "139", year="2021", month="10")# 匿名函数# 对list中每一个元素进行平方list3 = [1, 2, 3]def func(x):return x * xprint(list(map(func, list3)))# 因为要写一个函数太过函索,所以可以使用lambda简化print(list((map(lambda x: x ** x, list3))))

结果:

###类和对象类是对象抽象,对象时类的具体实现三大特性:封装,继承,多态

# 定义一个Person类# 封装:类里面封装属性,方法class Person():# 定义一个构造方法# 类的属性需要定义在构造方法中# 类中所有得方法第一个参数都是self,在调用时会自动转入def __init__(self, id, name, age, gender):self.id = idself.name = nameself.age = ageself.gender = gender# 这个属性不需要通过传参,直接写死self.common = "我是猪"# 如果某个属性不想公开,可以在属性之前加上__self.__secret = "这是一个秘密"# 定义方法def run(self):print("%s 跑的很快" % (self.name))return 1# 相当于java中的tostringdef __str__(self):return "class Person(%d %s %d %s)" % (self.id, self.name, self.age, self.gender)# 封装方法def __test(self):print("测试封装方法")# 实例化 构造对象person = Person(1001, "张三", 18, "男")print(person)print(person.name)print(person.run())# 调用封装的属性,通过 _类型__属性名 获取print(person._Person__secret)# 调用封装的方法person._Person__test()print("----------------------------------------------")# 继承class Teacher(Person):def __init__(self, id, name, age, gender, subject):# 直接得到父类的属性super(Teacher, self).__init__(id, name, age, gender)self.subject = subject# 写个teach的方法def teach(self):print("%s教的%s很棒" % (self.name, self.subject))# 重写Person的tostring方法def __str__(self):return "class Teacher:%d %s %d %s %s" % (self.id, self.name, self.age, self.gender, self.subject)teacher = Teacher(1002, "张老师", 33, "女", "语文")print(teacher)print(teacher.name)# 这里可以直接使用父类的方法print(teacher.run())print(teacher.teach())print("---------------------------------")# 多态# 父类引用指向子类对象def runTwice(c):c.run()c.run()runTwice(person)runTwice(teacher)

结果:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Python语法2