Python大部分基础语法的300行代码示例
在补习Python基础语法的同时,我编写了一个包含Python大部分基础语法的例子,便于自己复习语法,也便于大家入门Python。
一、目标读者
- 有其他语言基础但没有了解过Python的读者。
- 了解部分Python基础语法但没有实践过的读者。
- 完全不懂程序但准备入门Python的(建议逐步学习)。
二、这个例子长啥样
整个程序包含了138个知识点,虽然看似很多,但每个知识点在代码中只用了一句,便于理解。在Python中,利用#
号进行注释,缩进表示隶属关系。
i = int(input())
if i > 0:
print('hello world') # 一定要有之前的缩进,以表示这条语句属于if
else:
print('world hello')
三、300行例子代码
# 注:在python中需要注意代码之间的缩进,通常以一个tab的距离表示隶属关系
import os # 1、利用import语句进行导入模块
import math, copy, random, time
from collections import Counter # 2、利用from...import ....进行导入
import numpy as np # 3、利用as关键字重命名包名,以后再使用就可以直接用np了
def hello_world(): # 4、利用def关键字创建函数
yourname = input('你好,请输入你的名字:') # 5、输入函数,input()
print('欢迎来到Python的世界,', yourname) # 6、输出函数,print()
print('让我们开始学习吧~')
def hello_twice():
global yourname, yourheight, yourweight # 7、利用global关键字定义全局变量
yourname = input('请输入你的名字:')
yourheight = input('请输入你的身高:')
yourweight = input('请输入你的体重:')
# Python中字符串的部分操作
def deviding_line():
word1 = 'i am line' # 8、字符串的创建
word2 = word1.upper() # 9、字符串的函数,upper()
word3 = word1.lower() # 10、lower()函数
word4 = word1.title() # 11、title()函数
words = [word1, word2, word3, word4] # 12、[]可以创建一个列表
line = '-' * 40 # 13、利用*运算符创建串
endReturn = line + words[random.randint(0, 3)] + line # 14、字符串连接
return endReturn # 16、函数返回值
# 学习Python中的数字模型
def study_number():
num1 = input('请输入一个数字:')
print('你输入的是数字%s' % num1, '它的类型为:', type(num1)) # 17、输出函数格式控制
num2 = int(input('再输入一个数字:')) # 19、利用int()函数进行数值类型转换
num3 = float(input('再输入一个数字:')) # 20、float()函数转换为浮点数类型
print('num1+num2={}'.format(int(num1) + num2)) # 21、数字加法
print('num1-num2={}'.format(int(num1) - num2)) # 23、数字减法
print('num1*num2={}'.format(int(num1) * num2)) # 25、数字乘法
print('num2//num3={:.3f}'.format(num2 // num3)) # 26、数字整除
print('num2/num3={:.4f}'.format(num2 / num3)) # 27、数字除法
print('num2%num3={:.4f}'.format(num2 % num3)) # 28、求余数
print('num1**num2={}'.format(int(num1) ** num2)) # 30、幂运算
one, two, three = True, True, False # 32、bool值
print('and运算符:', one and two, one and three) # 33、and运算
print('or运算符:', one or two, one or three) # 34、or运算符
print('not运算符:', not one, not two, not three) # 35、not运算符
# 学习Python中的列表模型
def study_list(length): # 36、带有参数的函数
l1 = [1, 2, 3, 4, 5, 9.0] # 37、创建列表
l2 = list(range(10, 10 + length)) # 38、创建列表
l3 = l2 # 41、将l2的引用赋给l3
l3[0] = 99 # 43、更新列表值
l4 = l2.copy() # 45、复制一个l2给l4
l4[0] = 999
del l4[0] # 47、del语句进行删除列表值
l4.append(30) # 48、给列表添加值
l4.extend(l1) # 49、给列表追加一个序列多个值
l4.reverse() # 50、列表反转
l4.sort() # 51、sort()函数,将列表进行排序
# 学习Python中的元组模型
def study_tuple(length: int) -> bool: # 52、解释参数类型的函数创建
tuple1 = (1, 2, 3, 4) # 53、创建元组
tuple2 = tuple(range(10, 10 + length)) # 54、利用tuple创建元组
try: # 57、Python中的异常处理
tuple1[0] = 9 # 58、元组的不可改变性
except TypeError:
print('元组插入失败')
finally: # 59、finally内语句无论如何都会执行
print('不管插入成不成功我都会执行')
tuple3 = tuple1 + tuple2 # 60、通过+号进行合并为另一个元组
return True
def study_dict(): # 学习Python中的字典模型
dict1 = {1: '一', 2: '二', 3: '三', 4: '四'} # 61、创建字典
dict2 = dict(one=1, two=2, three=3)
dict3 = dict(zip([6, 7, 8, 9], ['Six', 'Seven', 'Eight', 'Nine']))
print(dict1[1], dict2['one'], dict3[6]) # 63、通过字典的键访问
dict1[1] = '壹' # 65、修改字典内容
dict1[5] = '五' # 66、添加字典
dict6 = dict1.copy() # 68、字典的复制
dict6[1] = 'One'
dict1.clear() # 69、字典的清空
def study_set(): # Python中集合的学习
set1 = set(['You', 'Are', 'Not', 'Beautiful']) # 71、利用set()函数进行创建集合
set2 = {'You', 'Are', 'So', 'Beautiful'} # 72、利用{}创建集合
set1.add('Me too') # 79、集合添加元素
set3.clear() # 81、清空集合,集合变为空
def study_Some_functions(): # Python中一些函数
list1 = [1, 2, 3, 4, 5, 6] # 列表
tuple1 = (11, 12, 13, 14, 15, 16) # 元组
set1 = set(list1) # 集合
dict1 = dict(zip([1, 2, 3, 4, 5], ['one', 'Two', 'Three', 'Four', 'Five'])) # 字典
print(max(list1), max(tuple1), max(set1), max(dict1)) # 82、max()函数
print(min(list1), min(tuple1), min(set1), min(dict1)) # 83、min()函数
print(sum(list1), sum(tuple1), sum(set1), sum(dict1)) # 84、sum()函数
print(len(list1), len(tuple1), len(set1), len(dict1)) # 85、len()函数
for i in range(5):
print(i)
def study_Slice(): # Python的切片操作
str
1 = 'I hope one day, I can find you, my sweet dream'
list1 = list(range(10))
print(str1[:]) # 102、切片格式为str[start:end:step]
print(str1[::-1]) # 103、反转
print(str1[:15]) # 104、只有end时
print(str1[15:]) # 105、只有start时
print(str1[::2]) # 106、步长为2
def study_loop_select(): # Python中的循环和选择语句
list1 = [1, 2, 3, 4, 5]
num = int(input('while循环,输入你想要循环的次数:'))
i = 1
while i <= num: # 108、while循环
if i < 5: # 109、if选择语句
print('我打印了', i, '次')
elif i < 10:
print('打印了', i, '次,真累啊')
elif i < 15:
print('打印太多啦,再打印我就要停止了...')
elif i < 20:
print('continue...')
i += 1
continue # 110、continue语句
else:
print('累死我了,休息。都', i, '次了~_~')
break # 111、break语句
i += 1
time.sleep(0.5) # 112、time.sleep(second)
def study_expression_deduction(): # 114、Python表达式推导
list1 = [i for i in range(10)] # 115、列表推导式
list2 = [x for x in range(20) if x % 2 == 0] # 116、添加if条件的列表推导式
print(list1, '<list1--------------list2>', list2)
def study_files(): # Python中的文件操作
filepath = input('请输入你的文件路径(输入quit退出):')
if filepath == 'quit':
return True
try:
file = open(filepath, 'w') # 121、打开文件,'w'为写格式打开
file.write('哈哈,现在开始写文件') # 122、向文件写入字符串
file.close() # 123、关闭文件
file = open(filepath, 'r') # 122、以'r'读格式打开
print('从文件中读出的内容:\n', file.read()) # 123、read()函数
except FileNotFoundError:
print('文件未找见请重新输入')
study_files() # 124、递归调用
except:
print('出现错误,请重新输入路径')
study_files()
class Users(): # 125、面向对象编程
def __init__(self, name, height, weight): # 126、类的构造方法
self.name = name
self.height = height
self.weight = weight
self.yanzhi = 100
def display(self): # 127、类方法
print('大家好,我是{},身高{},体重{},颜值超高{}'.format(self.name, self.height, self.weight, self.yanzhi))
if __name__ == "__main__": # 128、程序从这里开始运行
hello_world() # 129、调用函数
deviding_line()
hello_twice() # 132、global变量的作用
user = Users(yourname, yourheight, yourweight) # 133、实例化对象
user.display() # 134、对象调用方法
chooseinformation = '''Input the number of the function you want to Run(quit is exit):
1、study_number 2、study_list
3、study_tuple 4、study_dict
5、study_set 6、study_Some_functions
7、study_Slice 8、study_loop_select
9、study_expression_deduction
10、study_files
'''
while True: # 136、while循环进行运行程序
input('按键继续') # 137、等待按键
print(chooseinformation)
num = input('输入序号:')
if num == 'quit':
break
elif num == '1':
study_number()
elif num == '2':
study_list(10)
elif num == '3':
study_tuple(10)
elif num == '4':
study_dict()
elif num == '5':
study_set()
elif num == '6':
study_Some_functions()
elif num == '7':
study_Slice()
elif num == '8':
study_loop_select()
elif num == '9':
study_expression_deduction()
elif num == '10':
study_files()
deviding_line()
print('哈哈,恭喜你,这个程序结束咯~')
四、总结
这个程序包含了Python的一些基本语法,比如列表、元组、字典、集合、字符串的基本操作,有面向对象的类,循环语句,选择语句,函数的创建,包的导入,文件的读取,切片,表达式推导等。
但这依旧是Python中最基础的部分,想要精通一门语言,需要多动手实践。只有不断实践,不断探索,你才能掌握Python的精髓。