原创: 叫我詹躲躲 来源: 掘金 链接: juejin.im/post/5f05e1…
print('hello world!') 复制代码
python -v 复制代码
message = 'hello world!' print(message) 复制代码
name = 'jetty' print(name.title()) #Jetty 首字母大写 print(name) jetty name.upper() #JEETY 转大写 name.lower() #jetty 转小写 复制代码
first_name = 'hongzhu' last_name = 'zhan' full_name = last_name +" "+ first_name print(full_name) zhan hongzhu 复制代码
language = 'python/nJavascript/nC/nRust' print(language) 打印 python Javascript C Rust 复制代码
_blank = ' python ' print(_blank.rstrip()) #去除右侧空白 print(_blank.strip()) #去除两侧空白 print(_blank.lstrip()) #去除左侧空白 复制代码
num = 2.340 print(int(num)) #整型 2 print(float(num)) #浮点型 2.34 复制代码
color = ['red','green','yellow','pink'] #访问元素 print(color[0]) ##red #修改 color[0] = 'black' #添加元素 color.append('orange') #插入元素 color.insert(0,'blue') #插到第一位 print(color) #删除元素 del color[0] #删除当前元素 color.pop() #删除数组最后一个元素 color.remove('red') #删除红色 复制代码
num_list = [1,2,3,4,2,1,3,1,2] num_list.sort() print(num_list) [1, 1, 1, 2, 2, 2, 3, 3, 4] 复制代码
num_list = [1,2,3,4,2,1,3,1,2] print(sorted(num_list)) [1, 1, 1, 2, 2, 2, 3, 3, 4] 复制代码
num_list = [1,2,3,4,2,1,3,1,2] num_list.reverse() print(num_list) [2, 1, 3, 1, 2, 4, 3, 2, 1] 复制代码
num_list = [1,2,3,4,2,1,3,1,2] print(len(num_list)) 9 复制代码
num_list = [1,2,3,4,2,1,3,1,2] for i in num_list: print(i,end=" ") #一行显示 复制代码
num_list = [1,2,3,4,2,1,3,1,2] for i in range(len(num_list)): print(num_list[i],end=" ") 复制代码
squares = [] for i in range(1,6): squares.append(i**2) print(squares) [1, 4, 9, 16, 25] 复制代码
num_list = [1,2,3,4,2,1,3,1,2] print(max(num_list)) 4 print(min(num_list)) 1 print(sum(num_list)) 19 复制代码
squeres = [value**2 for value in range(1,11)] print(squeres) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 复制代码
odd_number =[] for i in range(1,11,2): odd_number.append(i) print(sum(odd_number)) 复制代码
three_nmu = [] for i in range(3, 91): if (i % 3==0): three_nmu.append(i) print(three_nmu) 复制代码
squares = [] for i in range(3,11): squares.append(i**3) print(squares) 复制代码
squares = [i**3 for i in range(3,11)] print(squares) 复制代码
num_list = [1,2,3,4,2,1,3,1,2] print(num_list[0:5]) [1, 2, 3, 4, 2] #从第一个开始取值到第五位 print(num_list[:5]) [1, 2, 3, 4, 2] #默认会从第一个开始取值 print(num_list[5:]) [1, 3, 1, 2] #取后面的4位 复制代码
dimensions = (100,300) print(dimensions[0]) 100 for i in dimensions: print(i) 100 300 复制代码
num_list = [1, 2, 3, 4, 2, 1, 3, 1, 2] for i in num_list: if i == 2: print(i) 复制代码
num_list = [1, 2, 3, 4, 2, 1, 3, 1, 2] for i in num_list: if i != 2: print(i) 复制代码
num_list = [1, 2, 3, 4, 2, 1, 3, 1, 2] for i in num_list: if i >=1 and i <=2: print(i) 复制代码
alien = {'color':0,'points':1} print(alien['color']) ##color 复制代码
alien = {'color':0,'points':1} alien['color'] = 'red' print(alien) {'color': 'red', 'points': 1} 复制代码
alien = {'color':0,'points':1} del alien['color'] print(alien) 复制代码
people_nums1 = {'name':'jetty','name1':'jack'} people_nums2 ={'name':'kitty','name1':'james'} peoples = [people_nums1,people_nums2] for i in peoples: print(i) 复制代码
ipt = input('你是小黄么?1(true) or 2(false)?') if ipt =='1': print('是本人') else: print('不是本人') 复制代码
print(4 % 2) 0 print(4 // 2) 2 复制代码
count = 0 arr = [] while count < 20: for j in range(1, 100): if j % 11 == 0: count = count+1 arr.append(j) print(arr) 复制代码
#简单求和 def num_sum(arr): result =0 for i in arr: result =result+i return result print(num_sum([1,2,3,4])) 10 复制代码
def num_sum(arr=[1,2,3]): result =0 for i in arr: result =result+i return result print(num_sum()) 6 复制代码
def make_prize(*top): return top print(make_prize(1)) print(make_prize(1,2,3)) print(make_prize(1,3,4,5)) print(make_prize(1,1,1,1,1)) #返回 (1,) (1, 2, 3) (1, 3, 4, 5) (1, 1, 1, 1, 1) 复制代码
# 随机数 import random print(random.randint(1,19)) 复制代码
class Dog(): def __init__(self,name,age): self.name =name self.age = age def sit(self): print(self.name+''+self.age) dog = Dog('jeety',24) print(dog.name) 复制代码
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year def getCarName(self): print(self.model) car = Car('audi','ad4',2016) print(car.make) 复制代码
class Car(): def __init__(self,name): self.name = name class Elastic(Car): def __init__(self, name): super().__init__(name) myTesla = Elastic('tesla') print(myTesla.name) 复制代码
class Car(): def __init__(self,make,name,color): self.make = make self.name = name self.color = color def getCarName(self): print('获取车的名字为'+self.name+'获取汽车的颜色'+self.color) class Batery(): def __init__(self,batery='60'): self.batery = batery def discribe_batery(self): print('This car has'+str(self.batery)+'batery') class Elatrity(Batery): def __init__(self, batery): super().__init__(batery) self.batery = Batery() elatrity = Elatrity('100') print(elatrity.discribe_batery()) 复制代码
f = open('file.txt',mode="w",encoding='utf-8') print(f) f.write('叫我詹躲躲/n') f.write('叫我詹躲躲1/n') f.close() 复制代码
import json numbers = [1,2,23,3,4,5,6,7,87] filename = 'numbers.json' with open(filename,'w') as f_obj: json.dump(numbers,f_obj) 复制代码
import json username = input('存储输入的数据') filename = 'numbers.json' with open(filename,'w') as f_obj: json.dump(username,f_obj) 复制代码
import json filename = 'numbers.json' with open(filename) as f_obj: username = json.load(f_obj) print('Welcome back',username) 复制代码
import json filename = 'numbers.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: username = input('存储输入的数据') with open(filename,'w') as f_obj: json.dump(username,f_obj) else: print('Welcome back',username) 复制代码
import json def get_username(): filename = 'numbers.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username def get_greeting(): username = get_username() if username: print('Welcome back',username) else: username = input('存储输入的数据') filename = 'numbers.json' with open(filename,'w') as f_obj: json.dump(username,f_obj) print('Welcome back',username) get_greeting() 复制代码
f = open('index.txt',encoding='utf-8') s = f.read() print(s) f.close() 复制代码
f = open('index.txt',mode="w",encoding='utf-8') f.write('叫我詹躲躲n') f.write('叫我詹躲躲1n') f.close() 复制代码
import random random.randint() #随机数 import jieba #结巴 import wordcloud #词云 jieba.lcut('分割中文词语的序列') #分割中文词语的序列 word_cloud = wordCloud(font_path='msyh.ttc').generate('分割中文词语') #生成词云对象 word_cloud.to_file('123.png') #保存到图片 复制代码
#面向对象编程 class Person: def __init__(self,name,sex,birthday): self.name = name self.sex = sex self.birthday = birthday def say(self,word): print(f'{self.name}说:"{word}"') zhang_san = Person('张三','男','2020202') zhang_san.say('12121') 复制代码
lastname = 'hello' firstname = 'world' print('我的名字是%s %s' %(lastname,firstname)) 复制代码
%c #字符 %s #通过str来格式化 %i #有符号十进制整数 %d #有符号十进制整数 %u #无符号十进制整数 %o #八进制整数 %x #十六进制整数(小写字母) %e #索引符号(小写e) %E #索引符号(大写E) %f #浮点实数 %g #%f和%e的简写 %G #%f和%E的简写 复制代码
name = '老夫子' age = 28 print('姓名:{},年龄{}'.format(name,age)) #姓名:老夫子,年龄28 复制代码
#特点: #1.使用lambda关键字创建函数 #2.没有名字的函数 #3.匿名函数冒号后面的表达式有且只有一个,是表达式不是语句 #4.自带return 复制代码
def computer(x,y): #计算两数和 return x+y M = lambda x,y:x+y print(M(1,2)) 复制代码
result = lambda a,b,c:a*b*c print(result(12,121,1)) 复制代码
age = 15 print('可以参军' if age>18 else '继续上学') #直接调用 result = (lambda x,y:x if x>y else y)(2,5) 复制代码
#阶乘函数 def factorial(n): if n==1: return 1 else: return n*factorial(n-1) pass print(factorial(3)) 复制代码
import os 文件操作模块 def findFile(file_path): listRs = os.listdir(file_path) 得到该路径所有的文件夹 for fileItem in listRs: full_path = os.path.join(file_path,fileItem) if os.path.isdir(full_path): 判断是否为文件夹 findFile(full_path) else: print(fileItem) pass pass else: return findFile('F://7.代码学习') 复制代码
abs(-27) #绝对值 round(21.1123) #浮点近似值 pow(2,3) #幂 2**3 divmod(10,3) # 商余 max(1,2,3,4) #最大值 min(1,2,3,4) #最小值 sum(1,2,3,4) #求和 eval() #动态执行表达式 复制代码
int #整型 float #浮点型 str #字符类型 ord #返回对应字符的ASCII chr #数字转字符 ASCII bool #boolean bin # 转换二进制 hex #转换为十六进制 oct #八进制 list #元祖转列表 tuple #元祖 dict #创建字典 bytes #转为字节 复制代码
#all 用于判定给定的可迭代参数中的所有元素是否都为TRUE,如果是返回TRUE,否则返回FALSE,除了0,空,False 外都算TRUE def all(iterable): for ele in iterable: if not ele: return False return True li = [1,2,3,4,5,6,False] print(all(li)) ##False 复制代码
#全部为false,返回false def any(iterable): for ele in iterable: if ele: return False return True li = [0,False,''] print(any(li)) ##False 复制代码
li = ['a','b','c'] for index,item in enumerate(li,7): print(index,item) #改下标 7 a 8 b 9 c 复制代码
set1 = {'1','2'} set2 = {'11','1'} #添加 add set1.add('3') #清空 clear() set1.clear() #取差集 difference set1.difference(set2) ##set1取set1中有的 #取交集 set1.intersection(set2) #取并集 set1.union(set2) set1 | set2 #末尾移除 set1.pop() #指定移除 set1.discard(3) #更新 update 合并一起去重 set1.update(set2) 复制代码
1-10,20-30,35-40 def threeSum(a1,a2,a3): return sum(a1+a2+a3) a1 = list(range(1,11)) a2 = list(range(20,31)) a3 = list(range(35,41)) print(threeSum(a1,a2,a3)) 复制代码
def computers(): for i in range(1,101): for j in range(1,34): if i+j==100 and 3*j+i/3 ==100: print('大和尚有{}个,小和尚有{}个'.format(j,i)) pass computers() #大和尚有25个,小和尚有75个 复制代码
li = [1,1,1,2,2,2,2,3,2,2,3,4,2,1,1] def findUnionNumber(li): for item in li: if li.count(item)==1: return item pass print(findUnionNumber(li)) 复制代码
dict ={} for key in li: dict[key] = dict.get(key,0)+1 print(dict) 复制代码
from collections import Counter a = [1, 2, 3, 1, 1, 2] result = Counter(a) print(result) 复制代码
import pandas as pd a = pd.DataFrame([[1,2,3], [3,1,3], [1,2,1]]) result = a.apply(pd.value_counts) print(result) 复制代码
li = [1,2,3,3,2,3,4,4,5,1,2,1] def uniqueNum(li): set1 = set(li) for i in set1: li.remove(i) set2 = set(li) for j in set2: set1.remove(j) return set1 print(uniqueNum(li)) 复制代码
#面向过程编程 根据业务从上到下开始编程 #类的结构 #类名 属性 方法 class People: name = 'zhan', age = 20, def eat(self): print('正在吃饭') #创建对象 people = People() people.eat() 复制代码
在类的内部,使用def定义的为实例方法,第一个参数为self,实例方法归实例所有
class People: name = 'zhan', age = 20, def eat(self): print('正在吃饭') #创建对象 people = People() people.eat() #添加属性 people.name2 = 'zhan' people.age2 = 22 复制代码
class People: # 初始化的操作,实例属性,自动执行 def __init__(self): self.name = 'zhan' self.age = 20 def eat(self): print('正在吃饭') #创建对象 people = People() people.eat() 复制代码
class People: # 初始化的操作,实例属性,自动执行 def __init__(self, name, age): self.name = name self.age = age def eat(self,food): print(self.name+food) #创建对象 people = People('叫我詹躲躲', 20) people.eat('正在吃饭') people.eat('洗澡') people.eat('跑步') 复制代码
#类似于js里面的this class Person: def eat(self): print(id(self)) pass pass person = Person() person.eat() print(id(person)) #self和对象指向同一个内存地址,self就是对象的引用 # <__main__.Person object at 0x0000020864815CC0> 复制代码
#__init__ :初始化实例属性 # __str__ :自定义对象的格式 # __new__ :对象实例化 class Animal: def __str__(self): return '3213213123123' pass pass animal = Animal() print(animal) class Animal: def __str__(self): return '3213213123123' pass pass def __new__(cls,*args,**kwargs): print("----new执行---") return object.__new__(cls) 真正创建对象实例的 pass animal = Animal() print(animal) #__new__ 和__init__的区别 #__new__ 类的实例化方法,必须返回实例,否则创建不成功 #__init__数据属性的初始化工作,认为是实例的构造方法,接受实例化self并对其进行构造 #__new__ 至少一个参数是cls,代表要实例化的类 #__new__ 执行要比__init__早 复制代码
# 属性: # name:玩家名称 # blood:血量 # 方法: # tong() 捅一刀,掉10滴血 # kanren() 砍一刀掉15滴血 # chiyao() 补血10滴血 # __str__打印玩家的状态 class Role: def __init__(self,name,blood): self.name = name self.blood = blood pass 砍人 def tong(self,enemy): enemy.blood -=10 info = '【%s】捅了【%s】一刀'%(self.name,enemy.name) print(info) pass 砍人 def kanren(self,enemy): enemy.blood -=15 info = '【%s】砍了【%s】一刀'%(self.name,enemy.name) print(info) pass 吃药 def chiyao(self): self.blood +=10 info = '【%s】吃了一口药,增加10滴血'%(self.name) print(info) pass def __str__(self): return '%s还剩下%s的血量'%(self.name,self.blood) xmcx = Role('西门吹雪',100) ygc = Role('叶孤城',100) while True: if xmcx.blood<=0 or ygc.blood<=0: break print('*********************') xmcx.tong(ygc) xmcx.kanren(ygc) print('*********************') ygc.tong(xmcx) ygc.chiyao() print('*********************') print(xmcx) print(ygc) """ ********************* 【西门吹雪】捅了【叶孤城】一刀 【西门吹雪】砍了【叶孤城】一刀 ********************* 【叶孤城】捅了【西门吹雪】一刀 【叶孤城】吃了一口药,增加10滴血 ********************* 西门吹雪还剩下50的血量 叶孤城还剩下25的血量 ********************* 【西门吹雪】捅了【叶孤城】一刀 【西门吹雪】砍了【叶孤城】一刀 ********************* 【叶孤城】捅了【西门吹雪】一刀 【叶孤城】吃了一口药,增加10滴血 ********************* 西门吹雪还剩下40的血量 叶孤城还剩下10的血量 ********************* 【西门吹雪】捅了【叶孤城】一刀 【西门吹雪】砍了【叶孤城】一刀 ********************* 【叶孤城】捅了【西门吹雪】一刀 【叶孤城】吃了一口药,增加10滴血 ********************* 西门吹雪还剩下30的血量 叶孤城还剩下-5的血量 """ 复制代码
class Fruit: def __init__(self,name,color): self.name = name self.color = color def showColor(self): print('%s的颜色为%s'%(self.name,self.color)) apple = Fruit('苹果','红色').showColor() orange = Fruit('橘子','黄色').showColor() watermelen = Fruit('西瓜','绿色').showColor() 复制代码
class CkeckSelf: def __str__(self): print(id(self)) pass CkeckSelf().__str__() selfObj = CkeckSelf() print(id(selfObj)) 复制代码
class Animal: def __init__(self, color, name, age): self.color = color self.name = name self.age = age def run(self): print('%s在跑步'%(self.name)) pass def eat(self): print('%s在吃东西' %(self.name)) pass def __str__(self): return '%s岁的%s的%s'%(self.age,self.color,self.name) cat = Animal('黑色','小猫',2) dog = Animal('白色','小狗',3) cat.run() dog.run() print(cat) print(dog) """ 小猫在跑步 小狗在跑步 2岁的黑色的小猫 3岁的白色的小狗 """ 复制代码
1、显示所有学生信息 2、新建学生信息 3、查询学生信息 4、修改学生信息 5、删除学生信息 0、退出系统 复制代码
student_data = [ { 'id': 123456, 'name': 'Tom', 'sex': '男', 'address': '迪士尼' }, { 'id': 123457, 'name': 'Jerry', 'sex': '女', 'address': '伦敦' }, ] 复制代码
def beauty_list(datas): for index, student in enumerate(datas): print(f'序号:{index}', end="t") print(f'姓名:{student["name"]}', end="t") print(f'性别:{student["sex"]}', end="t") print(f'地址:{student["address"]}') 复制代码
def input_name(): while True: name = input('输入名字:').strip() if name: return name else: continue 复制代码
def choose_sex(): print('1(男) | 2(女)') n = input('选择性别') if n == '1': return '男' else: return '女' 复制代码
def show_all(): beauty_list(student_data) 复制代码
def create_student(): sid = random.randint(1000, 10000) name = input_name() sex = choose_sex() address = input('地址:') student = { 'id': sid, 'name': name, 'sex': sex, 'address': address } student_data.append(student) 复制代码
def find_student(): name = input_name() for i in student_data: if i['name'] == name: print(i) return else: print('无该学生任何信息') 复制代码
def edit_student(): name = input_name() for student in student_data: if student['name'] == name: print(student) student['name'] = input_name() student['sex'] = choose_sex() student['address'] = input('地址:') return else: print('查无此人') 复制代码
def delete_student(): name = input_name() for student in student_data: if student['name'] == name: student_data.remove(student) return else: print('查无此人') while True: print(''' ******************** 欢迎使用学生管理系统 1、显示所有学生信息 2、新建学生信息 3、查询学生信息 4、修改学生信息 5、删除学生信息 0、退出系统 ******************** ''' ) op = input('请输入序号:') if op == '1': print(student_data) show_all() elif op == '2': create_student() elif op == '3': find_student() elif op == '4': edit_student() elif op == '5': delete_student() else: print('退出系统') break 复制代码
本文使用 mdnice 排版