python入门,300行代码例子

此随笔是微信公众号:Python技术迷文章内容,只用于学习使用。

1、目标读者

 

为了让这篇博文看着正式些,我得说一下本文的目标读者:

 

  • 没有了解过python,但有其他语言基础的读者

  • 了解部分python基础语法,但是没有编过程序练习的读者

  • 完全没有了解过python,但是知道部分程序理论的读者

  • 完全不懂程序,准备入门python的(不是很推荐)

  • 当然,如果你是python的大佬,还请大佬帮忙指出程序中不合理的地方。

 

2、 这个例子长啥样

 

写在程序之前

 

整个程序包含了138个知识点,哈哈,不要看着知识点多,其实每个知识点在代码中我就写了一句。所以这些知识点也就138行代码。

 

在python,可以利用#号进行注释,我的程序里面也都会采取#来讲解代码含义。同时给予知识点的编号。

 

并且,python利用代码间的缩进表示隶属关系,简单来说如下

i =int(input())
if i>0:
    print('hello world')  #一定要有之前的缩进,以表示这条语句属于if
else:
    print('world hello')

 

  好了,接下来给出我的300行例子吧👇

注:如果是初学,可以将每个函数单独截取阅读并运行查看。当然咯,代码不能光读不写,一定要动手去编。如果不动手编,可能看完运行完你依旧还是不是很懂(本例子可以直接跟着指令直接运行)

  1 #注:在python中需要注意代码之间的缩进,通常以一个tab的距离表示隶属关系
  2 
  3 
  4 import os #1、利用import语句进行导入模块,用逗号分隔可以导入多个包
  5 import math,copy,random,time
  6 from collections import Counter  #2、利用from...import ....进行导入
  7 import numpy as np  #3、利用as关键字重命名包名,以后再使用就可以直接用np了
  8 
  9 
 10 def hello_world():  #4、利用def关键字创建函数,简单来说:函数就是将具有独立功能的代码块组织成一个模块,需要的时候调用
 11 #创建函数格式:def name(参数1,参数2....):
 12 yourname = input('你好,请输入你的名字:')  #5、输入函数,input(),若input中有字符串可以输出
 13 print('欢迎来到Python的世界,',yourname)  #6、输出函数,print(),若要输出多个对象,利用逗号分隔
 14 print('让我们开始学习吧~')
 15 
 16 
 17 def hello_twice():
 18 global yourname,yourheight,yourweight  #7、利用global关键字定义全局变量,使之在整个程序运行周期能够被调用
 19 yourname = input('请输入你的名字:')
 20 yourheight = input('请输入你的身高:')
 21 yourweight = input('请输入你的体重:')
 22 
 23 
 24 #python中字符串的部分操作
 25 def deviding_line():
 26 word1 = 'i am line'  #8、字符串的创建,利用单引号' 或者双引号" 进行创建
 27 word2 = word1.upper()  #9、字符串的函数,利用运算符.进行调用,该语句中的upper()可以将字符串转换为全大写字母
 28 word3 = word1.lower()  #10、lower()函数,将字符串转换为全小写
 29 word4 = word1.title()  #11、title()函数,可以将字符串标题化
 30 #以上三个函数仅为字符串的部分函数
 31 words = [word1,word2,word3,word4]  #12、[]可以创建一个列表,列表可以存放很多的对象
 32 line = '-' * 40  #13、利用*运算符创建串,这里就是有40个-符号
 33 
 34 
 35 endReturn = line+words[random.randint(0,3)]+line #14、字符串可以利用+号直接相连
 36 #15、上面出现的random.randint()可以创建随机整数,0和3为随机数的上下限
 37 return endReturn  #16、函数返回值,可以在被调用时将这个值返回
 38 
 39 
 40 #学习python中的数字模型
 41 def study_number():
 42 num1 = input('请输入一个数字:')
 43 print('你输入的是数字%s'%num1,'可它的类型为:',type(num1)) #17、输出函数格式控制
 44 #18、type()函数可以返回该值的类型
 45 num2 = int(input('再输入一个数字:'))  #19、利用int()函数进行数值类型转换,将数字转换为int整型
 46 print('你输入的是数字%s' % num2, '它的类型为:', type(num2))
 47 num3 = float(input('再输入一个数字:'))  #20、float()函数可以转换为浮点数类型
 48 print('你输入的是数字%s' % num3, '它的类型为:', type(num3))
 49 print('num1+num2={}'.format(int(num1)+num2)) #21、数字加法
 50 # 22、format()函数格式化输出,在字符串中的{}符号将被替换为format()的参数
 51 print('num1-num2={}'.format(int(num1)-num2))   #23、数字减法
 52 print('num1*num2={}'.format(num1*num2)) #24、num1*num2并不会是你想要的数据,因为input()函数,默认输入为字符类型
 53 print('num1*num2={}'.format(int(num1) * num2))  #25、数字乘法
 54 print('num2//num3={:.3f}'.format(num2//num3)) #26、数字整除,同时{:.3f}表示输出格式小数点后面保留三位
 55 print('num2/num3={:.4f}'.format(num2/num3)) #27、数字除法,保留小数点后四位
 56 print('num2%num3={:.4f}'.format(num2 % num3)) #28、求余数
 57 print('num2%num3={:.4%}'.format(num2%num3)) #29、求余数,{:.4%}输出格式为百分比格式
 58 print('num1**num2={}'.format(int(num1)**num2))  #30、幂运算
 59 print('This is the {a},and {b}'.format(a='numbers',b='some operations')) #31、format多参数,标记位置对应输出
 60 
 61 
 62 one,two,three = True,True,False  #32、bool值
 63 print(one,two,three)
 64 print('and运算符:',one and two,one and three) #33、and运算,当两个值同时为真时才为真
 65 print('or运算符:',one or two,one or three) #34、or运算符,当两个值同假时为假
 66 print('not运算符:',not one,not two,not three)  #35、not运算符,得到相反的值
 67 
 68 
 69 #学习python中的列表模型
 70 def study_list(length): #36、带有参数的函数
 71 l1 = [1,2,3,4,5,9.0]   #37、创建列表,利用符号[]
 72 l2 = list(range(10,10+length))  #38、创建列表,也可以用list()
 73 #39、range()函数,可以创建一个整数列表,格式为range(start,end,step),start为开始位置,end为结束位置,前闭后开,step为步长
 74 print('l1的类型为:',type(l1))
 75 print(l1[1],l2[1])  #40、访问列表值,可以直接用list[num]的方式进行访问
 76 l3 = l2  #41、将l2的引用赋给l3
 77 print(id(l1),id(l2),id(l3)) #42、id()函数可以获取对象的内存地址,在这里可以看到l3的的地址和l2是一样的
 78 l3[0]=99  #43、更新列表值
 79 print('l2==l3么?',l2==l3)   #44、更新l3后依旧等于l2,因为l3和l2本来就是一个对象,不过换了个名字
 80 l4 = l2.copy()  #45、复制一个l2给l4,copy()创建一个一模一样的列表
 81 l4[0]=999
 82 print('l4==l2么?',l4==l2)  #46、此时l4不等于l2
 83 print('删除前',l4)
 84 del l4[0]  #47、del语句进行删除列表值,在python中del可以删除所有的变量
 85 print('删除后',l4)
 86 l4.append(30)  #48、给列表添加值
 87 l4.extend(l1)  #49、给列表追加一个序列多个值
 88 print('添加l1后:',l4)
 89 l4.reverse()  #50、列表反转
 90 print('反转后:',l4)
 91 l4.sort()  #51、sort()函数,将列表进行排序
 92 print('排序后:',l4)
 93 
 94 
 95 #学习python中的元组模型
 96 def study_tuple(length:int)->bool:  #52、解释参数类型的函数创建,->为返回值类型
 97 tuple1 = (1,2,3,4)  #53、创建元组,利用()符号,元组的特性是不可以改变
 98 tuple2 = tuple(range(10,10+length))  #54、利用tuple创建元组
 99 
100 
101 print(tuple1.count(1))  #55、元组函数count(),用于输出某个值的数量
102 print(tuple1.index(1)) #56、元组函数index(),可以按照索引得到值
103 try:    #57、python中的异常处理,try:语句内部如果出现错误则会转入到except中
104 tuple1[0] = 9  #58、因为元组的不可改变性,所以该语句会出错
105 except TypeError:
106 print('元组插入失败')
107 finally:  #59、finally内语句不管是否出现错误都会执行
108 print('不管插入成不成功我都会执行')
109 
110 
111 try:
112 print(id(tuple1),id(tuple2))
113 except:
114 return False
115 else:
116 tuple3 = tuple1+tuple2  #60、元组虽然不可改变,但是可以通过+号进行合并为另一个元组
117 print(tuple3,id(tuple3))
118 return True
119 
120 
121 def study_dict():  #学习python中的字典模型,字典是  键->值 的映射
122 dict1 = {1:'',2:'',3:'',4:''}  #61、以下为创建字典的5种方法
123 dict2 = dict(one=1,two=2,three=3)
124 dict3 = dict(zip([6,7,8,9],['Six','Seven','Eight','Nine']))
125 dict4 = dict([('One',1),('Two',2),('Three',3)])
126 dict5 = dict({1:'',2:'',3:'',4:''})
127 print(type(dict1),dict1==dict5)  #62、可以看到,dict1和dict5是等价的
128 print(dict1[1],dict2['one'],dict3[6],dict4['One'],dict5[1])  #63、通过字典的键访问
129 print(dict1.get(4)) #64、通过get函数访问内容
130 
131 
132 dict1[1] = '' #65、修改字典内容
133 dict1[5] = '' #66、添加字典
134 print(dict1)
135 print(1 in dict1, 6 in dict1, 7 not in dict1) #67、in和not in关键字,可以判断值是否在序列中
136 dict6 = dict1.copy()  #68、字典的复制
137 dict6[1] = 'One'
138 print(dict1,'<dict1------------dict6>',dict6)
139 
140 
141 dict1.clear() #69、字典的清空
142 print(dict1)
143 del dict1,dict2,dict3,dict4,dict5,dict6 #70、删除字典,也可以用del dict[key]的方式删除某个键
144 
145 
146 def study_set(): #python中集合的学习,集合中不存在相等的值
147 set1 = set(['You','Are','Not','Beautiful']) #71、利用set()函数进行创建集合
148 set2 = {'You','Are','So','Beautiful'}  #72、利用{}创建集合,创建空集合的时候不能用{},因为{}表示字典
149 set3 = set2.copy() #73、集合的复制
150 
151 
152 print(type(set1))
153 print(set1,set2)
154 print(set1|set2)  #74、集合或运算符,得到两个集合中所有元素
155 print(set1&set2)  #75、集合与运算符,得到两个集合共同元素
156 print(set1^set2)  #76、不同时包含于set1和set2的元素
157 print(set1-set2)  #77、集合差运算,得到set1有,set2没有的元素
158 print(set1<=set2,set3<=set2,set3<set2)  #78、<=符号,判断是否为子集,<符号,判断是否为真子集
159 
160 
161 
162 
163 set1.add('Me too') #79、集合添加元素
164 print('is语句用法',set3==set2,set3 is set2,set1 is not set2) #80、is和is not语句,is语句用于判断对象是否一样,==判断值是否一样
165 set3.clear()  #81、清空集合,集合变为空
166 print(set3)
167 del set3
168 
169 
170 def study_Some_functions(): #python中一些函数
171 list1 = [1,2,3,4,5,6]  #同学们,眼熟不,这就是之前的列表,下面的这些大家都认认是啥
172 tuple1 = (11,12,13,14,15,16)  #元组
173 set1 = set(list1)  #集合
174 dict1 = dict(zip([1,2,3,4,5],['one','Two','Three','Four','Five']))  #字典
175 
176 
177 print(max(list1),max(tuple1),max(set1),max(dict1))  #82、max()函数,得到序列中最大值
178 print(min(list1),min(tuple1),min(set1),min(dict1))  #83、min()函数,得到最小值
179 print(sum(list1),sum(tuple1),sum(set1),sum(dict1))  #84、sum()函数,得到序列和
180 print(len(list1),len(tuple1),len(set1),len(dict1))  #85、len()函数,得到序列长度
181 print(divmod(list1[0],tuple1[0]))  #86、divmod()函数,计算两个数的商和余数,结果两个格式为(商,余数)
182 print(list(enumerate(tuple1)))  #87、enumerate(),给元组添加一个索引
183 
184 
185 list2 = list(tuple1)  #88、利用list()将元组,字典等等转换为列表
186 list3 = list(set1)
187 list4 = list(dict1)
188 tuple2 = tuple(list1)  #89、利用tuple()将列表,字典等转换为元组
189 
190 
191 print(list2,list3,list4)
192 
193 
194 for i in range(len(list1)):  #90、for循环语句
195 print(list1[i],end=' ')  #91、print的属性end,可以使输出格式为end的内容,而不是默认换行
196 print()
197 for i in dict1:  #92、for循环遍历
198 print(i,dict1[i],end=' ')
199 
200 
201 list5 = list(reversed(list1))  #93、reversed()函数,可以反转序列
202 print('\n',list5)  #94、\n,换行符
203 
204 
205 testStr = "The mountains and rivers are different, the wind and the moon are the same"
206 words = testStr.split(' ')  #95、split()函数,以split()内参数分割字符串,返回一个列表
207 print(words)
208 words.sort(key=len)  #96、sort()函数,进行排序,参数key=len时,以字符串长度为标准排序
209 print('以长度排序:',words)
210 words.sort(key=len, reverse=True)  #97、reverse参数,结果反转
211 print('以长度排序并且反转:', words)
212 words.sort(key=str)  #98、以字典序进行排序
213 print('以字典序排序:',words)
214 
215 
216 ct = Counter(testStr)  #99、collections模块中的Counter,可以得到字符串中每个数字出现次数
217 print(ct)
218 ct.update('eeeexxxxxlllll')  #100、更新
219 print(ct)
220 print(ct.most_common(5))  #101、得到字符数最多的前五位
221 
222 
223 def study_Slice():  #python的切片操作,得到序列的部分内容
224 str1 = 'I hope one day, I can find you, my sweet dream'
225 list1 = list(range(10))
226 tuple1 = tuple(list1)
227 
228 
229 print(str1[:])  #102、切片格式为str[start:end:step],前闭后开,step可为正负,默认步长为1
230 print(str1[::-1])  #103、当步长为负数的时候,反转
231 print(str1[:15])  #104、只有end时,截取最开始到end
232 print(str1[15:])  #105、只有start时,截取从start到末尾的所有字符
233 print(str1[::2])  #106、步长为2
234 print(str1[1::2])
235 
236 
237 print(list1[:])  #107、和str一样
238 print(list1[2:])
239 print(list1[:2])
240 print(list1[::-1])
241 
242 
243 list1[1:5] = [10] #切片赋值,右边必须为一个可以遍历的序列
244 #list1[1:5] = 10   这样就会报错
245 print(list1)
246 
247 
248 def study_loop_select():  #python中的循环和选择语句
249 list1 = [1,2,3,4,5]
250 num = int(input('while循环,输入你想要循环的次数:'))
251 i = 1
252 while i<=num:  #108、while expression:当expression为真的时候进行循环
253 if i<5:  #109、if...elif...else选择语句,如果判断结果只有两个,可以使用if...else
254 print('我打印了',i,'')
255 elif i<10:
256 print('打印了',i,'次,真累啊')
257 elif i<15:
258 print('打印太多啦,再打印我就要停止了...')
259 elif i<20:
260 print('continue...')
261 i+=1
262 continue   #110、continue语句,用在循环中,continue后的所有语句都不允许,直接进入下次循环
263 print('我想我可能输出不了了')
264 else:
265 print('累死我了,休息。都',i,'次了~_~')
266 break  #111、break语句,运用在循环中,直接退出循环,所以,在本例子中,这个循环最多循环20次
267 i+=1
268 time.sleep(0.5)  #112、time库为python中的时间库,time.sleep(second)可以使程序暂停运行second秒
269 else:  #113、while循环后接一个else语句,当执行完所有循环后执行一次,可以省略(个人感觉用处不大)
270 print('while结束了')
271 
272 
273 for i in list1:   #113、for循环,上面代码有用到过
274 print(i,end=' ')
275 print()
276 for i in range(5):
277 print(i)
278 
279 
280 
281 
282 def study_expression_deduction(): #114、python表达式推导
283 list1 = [i for i in range(10)]   #115、利用该语句推导出列表
284 list2 = [x for x in range(20) if x%2==0]  #116、语句中增加if,满足if后表达式的才会是列表
285 print(list1,'<list1--------------list2>',list2)
286 
287 
288 print(deviding_line())  #117、函数可以在任何地方被调用,如果是自己调用自己就可以称为递归调用
289 
290 
291 list3 = [['_'] * 3 for i in range(3)]
292 print(list3)
293 
294 
295 fruits = ['Apple','Banana','Pear']
296 colors = ['Red','Yellow','Green']
297 suitcolor = [(color,fruit) for color,fruit in zip(colors,fruits)] #118、两个列表合并
298 print(suitcolor)
299 cartesian = [(color,fruit) for color in colors for fruit in fruits] #119、两个列表的笛卡尔积
300 print(cartesian)
301 
302 
303 dict1 = {fruit:color for fruit,color in suitcolor}  #120、字典的推导,只要是带有键值对的任何序列,都可以推导出字典
304 print(dict1)
305 
306 
307 def study_files():
308 filepath = input('请输入你的文件路径(输入quit退出):')
309 if filepath=='quit':
310 return True
311 try:
312 file = open(filepath,'w') #121、打开文件,'w'为写格式打开
313 file.write('哈哈,现在开始写文件')  #122、向文件写入字符串
314 file.close()  #123、关闭文件
315 file = open(filepath,'r')  #122、以'r'读格式打开
316 print('从文件中读出的内容:\n',file.read())  #123、read()函数可以得到文件内容
317 except FileNotFoundError:
318 print('文件未找见请重新输入')
319 study_files()  #124、这就是上面所说的递归调用
320 except:
321 print('出现错误,请重新输入路径')
322 study_files()
323 
324 
325 class Users():  #125、面向对象编程,python中创建类class,类包含有属性与方法,包括有私有变量,共有变量等等
326 def __init__(self,name,height,weight):  #126、类的构造方法,创建实例时自动调用
327 self.name = name
328 self.height = height
329 self.weight = weight
330 self.yanzhi = 100
331 
332 
333 def display(self): #127、类方法
334 print('大家好,我是{},身高{},体重{},颜值超高{}'.format(self.name,self.height,self.weight,self.yanzhi))
335 
336 
337 if __name__=="__main__":  #128、无论之前有什么,程序都会从这里开始运行
338 hello_world()  #129、所以这是运行的第一句,调用该函数
339 deviding_line()
340 try:
341 print(yourname)  #130、调用完hello_world()函数后,因为在hello_world()函数内部有一个yourname变量,所以我们进行输出,看在这里能不能找见这个变量
342 except:
343 print('  未能找见该变量  ')#131、不可能找见这个变量的,因为yourname是局部变量,只存在于hello_world()函数内部
344 deviding_line()
345 hello_twice()  #132、因为在该函数中定义了global语句,所以该函数中的变量在以下程序中都可以使用
346 
347 
348 user = Users(yourname,yourheight,yourweight) #133、实例化对象,创建Users类的实例
349 user.display()  #134、对象调用方法
350 
351 
352 #135、在python中,可以用三引号进行多行注释,但是如果用变量接收注释的话也可以是一个有格式的字符串,如下
353 chooseinformation = '''Input the number of the function you want to Run(quit is exit):
354 1、study_number2、study_list
355 3、study_tuple4、study_dict
356 5、study_set6、study_Some_functions
357 7、study_Slice8、study_loop_select
358 9、study_expression_deduction
359 10、study_files    
360 '''
361 deviding_line()
362 while True: #136、while循环进行运行程序,只有当输入quit时才会退出循环(不过你强制退出当然也可以退出)
363 input('按键继续') #137、为了让输出不那么快,等待按键后才输出以下内容
364 print(chooseinformation)
365 num = input('输入序号:')
366 #138、在以下if...elif...else选择中,我们来选择运行不同的函数
367 if num=='quit':
368 break
369 elif num=='1':
370 study_number()
371 elif num=='2':
372 study_list(10)
373 elif num=='3':
374 study_tuple(10)
375 elif num=='4':
376 study_dict()
377 elif num=='5':
378 study_set()
379 elif num=='6':
380 study_Some_functions()
381 elif num=='7':
382 study_Slice()
383 elif num=='8':
384 study_loop_select()
385 elif num=='9':
386 study_expression_deduction()
387 elif num=='10':
388 study_files()
389 deviding_line()
390 print('哈哈,恭喜你,这个程序结束咯~')

这个程序里面包含了python的一些基本语法,比如说有几种常见数据结构:列表,元组,字典,集合,字符串,也有他们的基本操作,有面向对象的类,循环语句,选择语句,函数的创建,包的导入,文件的读取,切片,表达式推导。

 

但是这依旧是python中最基础的部分,如果想要精通一门语言,没有自己的亲自实践,不一行行的去敲打键盘,不一个bug一个bug的去寻找,永远也难以掌握它的精髓。

 来源:https://blog.csdn.net/the_sangzi_home/article/details/

 

posted @ 2021-10-09 11:03  guide123  阅读(3349)  评论(0编辑  收藏  举报