Python简单语法学习
# 基础
"""Jupyter Notebook 的快捷键: https://www.jianshu.com/p/72493e81a708"""
# 1. 打印关键字
import keyword
print(keyword.kwlist)
# 2. 打印语句
print("Hello\
Python\
Hello\
World")
# 3.变量不需声明 变量赋值为任意类型(动态语言)
a = 12
print(f"a:{a} type:{type(a)}")
a = "python"
print("a:", a, "type:", type(a))
# 输出对象地址
print(id(a))
del a
# print(a)
# 4. input 和 字符串连接
name = "John"
# + 连接
mes1 = name + " is a coder"
# ,连接
mes2 = name, " is a coder"
print(name, " is a coder")
# .join连接
mes3 = " ".join(mes2)
# 格式化
mes4 = "%s and %s is a coder" % (name, "Smith")
# f("{}")
mes5 = f"{name} is a coder"
print(f"{mes1}\n{mes2}\n{mes3}\n{mes4}\n{mes5}")
del mes1, mes2, mes3, mes4, mes5
# 5.input
name = input("请输入姓名:")
print("Hello", name)
# 流程控制
''' 流程控制 1 '''
# 6. 函数
def run():
print("car started...")
pass
def stop():
print("car stopped...")
pass
def error():
print("I can't understand...")
pass
# 7. 分支
# ==: 用来判断两个对象的值是否相等
# is: 判断两个变量是否引用的是同一个对象,底层判断的依据是两个变量的id是否相等
status = "stop"
def message(mes):
# 声明 status 为全局变量
global status
if mes in "start" and status in "stop":
run()
status = "start"
elif mes == "stop" and status == "start":
stop()
status = "stop"
elif mes in "start" and status in "start":
print("Car is already started")
elif mes in "stop" and status in "stop":
print("Car is already stopped")
else:
error()
# 8. 循环
while True:
order = input("请输入命令:")
if order not in ["END", "end"]:
message(order)
else:
print("finish")
break
del status
点击查看
练习
''' 流程控制 2 '''
# 9 * 9 乘法表
for i in range(1, 10, 1):
for j in range(1, i+1):
print(f"{i} * {j} = {i * j}", end="\t")
print()
'''斐波那契数列'''
def fibonacci(n):
if n==1 or n==2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
for i in range(1, 20):
print(fibonacci(i), end=" ")
fibonacci(10)
'''素数'''
import math
def sushu(start, end):
# 去掉1 0
if start<2:
start=2
# 定义返回结果
result= []
for i in range(start, end+1):
# 默认都是素数
flag = False
#从2作为除数开始判断当前数是否能够被除1和本身的其他数整除
for j in range(2, int(math.sqrt(i)+1)):
# 如果能被2或者小于自己的数整除,这不是素数,改变flag为True
if i%j == 0:
flag = True
break
if flag == False:
result.append(i)
return result
result = sushu(0,101)
print(len(result))
print(result)
'''输入某年某月某日,判断这一天是这一年的第几天'''
#输入某年某月某日,判断这一天是这一年的第几天?
def outter(func):
def inner():
year = int(input("请输入一个年份:"))
# global year
if year % 100 != 0 and year % 4 == 0 or year % 400 == 0:
print("%d是闰年"%year)
dict1[2]=29
func()
else:
print("%d是平年"%year)
func()
return inner
dict1 ={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:30,9:31,10:31,11:30,12:31}
@outter
def f():
ymd2 = input("输入年-月-日[year-month-day]:")
ymd1 =ymd2.split('-')
day =0
for x in range(1,int(ymd1[1])):
day += dict1[x]
Day = day+int(ymd1[2])
print("这一天是这一年的第%d天"%Day)
f()
'''时间转换'''
import datetime
# 输入时间
input_time = input("请输入时间(%Y-%m-%d):") # input_time = "2020-7-3"
# 字符串转为时间
end_time = datetime.datetime.strptime(input_time, '%Y-%m-%d')
# 拼接上一年最后一天的时间
start_time = datetime.datetime.strptime(str(end_time.year-1) + "-12-31", '%Y-%m-%d')
# 时间相减 得到天数
(end_time-start_time).days
'''时间转换2'''
# 接收输入的信息,并拆分成年月日变量
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
# 预定义每个月对应年的第几天
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
# 第几天用sum变量表示,并初始化为months数组对应的天数
sum = months[month-1]
else:
print('data error')
# 添加day所代表的天数
sum += day
# 闰年标记
leap = 0
# 判断是否为闰年
if year % 400 == 0 or year % 4 == 0 and year % 100 != 0:
leap = 1
# 如果是闰年,总天数需要加一天
if leap == 1 and month > 2:
sum += 1
print('it is the %dth day.' % sum)
# 数据类型
# 序列数据类型 List(列表)
"""序列数据类型 List(列表)"""
# 创建 1.python列表可以存储任意类型的对象 2.按照顺序存储
my_list = [1.0, "python", True, None, print, list(range(0, 10, 3))]
print(type(my_list), end="类型\t")
print(len(my_list), end="长度\n")
# 访问
print(f"{my_list[4]}\t{my_list[-1]}")
del my_list
# 遍历
list1 = ["John", "Smaith", "Tom", "Lily", "Jim"]
for elem in list1:
print(elem, end="\t")
# 修改
## 修改值
list1[2] = "nicai"
## 追加
list1.append("last")
## 插入
list1.insert(1, "first")
# list1
# 删除
# del list1[1]
## 删除并取出
# str = list1.pop(3)
# str
## 指定值删除
# list.remove("nicai")
## 查找下标
# list1.index("first")
# 排序
## 临时排序
print(sorted(list1))
## 永久排序
# list1.sort()
# list1
## 列表倒序
list2 = sorted(list1)
list2.reverse()
list2
# 切片 1.语法: 列表[起始:结束:步长]
stus = ['孙悟空','猪八戒','沙和尚','唐僧','蜘蛛精','白骨精']
stus[0: 5: 2]
# 序列数据类型 Tuple(元组)
"""序列数据类型 Tuple(元组)"""
### 元组 1.类似list 2.属于不可变序列 ###
list3 = list(range(0, 10, 3))
# 元组不可变 但其中元素可以变
tuple1 = ("hello", "python", list3)
for elem in tuple1:
print(elem, end=" ")
tuple1[2][1] = 123
tuple1
# 序列数据类型 Set(集合)
"""序列数据类型 Set(集合)"""
### Set集合 无序不重复
## 创建空集合
set1 = set()
## list转化为set
set1 = set(list(range(0, 10, 3)))
print(set1)
a_set = {-1, -3, 2, 3, 5}
b_set = {2, 3, 5, 25, 36}
## 交集
print( a_set.union(b_set) )
print( a_set | b_set )
## 并集
print( a_set.intersection(b_set) )
print( a_set & b_set )
## 差集
print( a_set.difference(b_set) )
## 集合异或
print( a_set ^b_set )
# 序列数据类型 dictionary(字典)
"""序列数据类型 dictionary(字典) 1.key值唯一"""
# 定义
dic = { "k1": "v1"}
# dic = dict([(1, "baidu"), (2, "Goole"), (3, "toabao")])
print(dic[1])
print(dic)
print(dic.keys())
dic.values()
# 修改/新增元素
dic["k2"] = "v2"
# 删除元素
del dic["k2"]
dic.clear() # 清空字典所有条目
del dic # 删除字典
# 函数和类
# 函数参数和返回值的类型
"""函数参数和返回值的类型 200124"""
### 顺序实参
def info(heroName, petName):
print("英雄名字:{" + heroName + "}\t宠物名字:{" + petName + "}")
info("德鲁伊", "龙狼")
### 位置实参
info(petName="龙狼", heroName = "德鲁伊")
### 默认值
def info2(heroName, petName="烈焰神虎", attack="5680"):
print(f"英雄名字:{heroName}\t宠物名字:{petName}\t攻击力{attack}")
info2("苍瞳")
info2(heroName="苍瞳", attack="12345")
### 任意数量的参数
def fun1(*p):
print(p)
fun1(0, 1)
### 任意数量关键字参数
def fun2(**p):
for elem in p.items():
print( elem, end="\t" )
fun2(x=1, y=2, z=3)
### 通过 **来对一个字典进行解包操作
def fun3(name, info):
print(f"name={name} \t info={info}")
dic = { "name":"酒神", "info":"阴阳冕" }
fun3(**dic)
### 单值返回
def info2(heroName, petName="烈焰神虎", attack="5680"):
return f"英雄名字:{heroName}\t宠物名字:{petName}\t攻击力{attack}"
print( info2("苍瞳") )
### 多值返回
def arithmetic1(x, y):
add = x+y
subtract= x-y
multiply= x*y
if y != 0:
divide= x/y
else:
print("除数不能为零")
return add, subtract, multiply, divide
#eval()将字符串str当成有效的表达式来求值并返回计算结果
num1,num2=eval(input("请输入需要计算的两个数字:"'\n'))
# num1=int(num1)
# num2=int(num2)
a,s,m,d = arithmetic1(num1, num2)
print(f"{num1} + {num2} = {a}\t{num1} - {num2} = {s}\t{num1} * {num2} = {a}\t{num1} / {num2} = {d}")
### 模块
## 引入模块
# from data import cycle
## 引入函数 并起别名
# from data.cycle import sphere_surface_area as ssa
##引入模块 起别名
from data import cycle as cy
radius = 2
print(f"圆面积: {cy.area(radius)}\t圆周长:{cy.circumference(radius)}\t \
球体积:{cy.sphere_volume(radius)}\t球表面积:{cy.sphere_surface_area(radius)}")
# 常用库
# 类的练习
""" 9.类的练习 """
class Mammal:
#_init_是一个特殊的方法,类的实例化操作会自动为新创建的类实例调用_init_()方法
# name为实例属性
def __init__(self,name):
self.name = name
#类的方法至少有一个参数self且必须是第一个参数
def walk(self):
print(f'{self.name} walking')
def shout(self):
print(f'{self.name} shouting')
class Dog(Mammal):
print('===============Dog===============')
# 类属性
action = "摇尾巴"
def shout(self):
print(f'{self.name} 汪汪')
class Cat(Mammal):
print('===============Cat===============')
pass
mammal = Mammal('哺乳动物')
mammal.walk()
mammal.shout()
cat = Cat('喵喵')
cat.walk()
cat.shout()
dog = Dog('二哈')
dog.walk()
dog.shout()
Dog.action = "喝水"
print(dog.name + "在" + Dog.action)
"""类的练习2"""
class Car():
'''模拟汽车的类'''
def __init__(self, make, model, year):
# 初始化属性
self.make = make #制造商
self.model = model #型号
self.year = year #生产年份
self.odometer_reading = 0
def base_message(self):
# 汽车描述信息
cmessage = f"{self.make} {self.model} {self.year}"
return cmessage.title()
def read_odometer(self):
# 打印里程信息
print(f"This car has {self.odometer_reading} miles on it")
def update_odometer(self, miles):
# 修改里程信息 不能调小
if self.odometer_reading < miles:
self.odometer_reading = miles
else:
print("您不能调小里程数")
def increment_odometer(self, miles):
# 增加里程数
self.odometer_reading += miles
car = Car("audo", "a6", 2016)
print(car.base_message())
car.read_odometer()
## 直接修改属性
car.odometer_reading = 21
car.read_odometer()
## 方法修改
car.update_odometer(20)
car.read_odometer()
car.update_odometer(50)
car.read_odometer()
## 增加里程数
car.increment_odometer(10)
car.read_odometer()
class ElectricCar(Car):
"""电动车"""
def __init__(self, make, model, year, battery_size):
super().__init__(make, model, year)
self.battery_size = battery_size
def desctibe_battery(self):
# 属于电池容量的信息
print(f"This car has a {self.battery_size} -kwh battery")
def base_message(self):
return "ElectricCar:" + super().base_message()
ele_car = ElectricCar("tesla", "model s", 2017, 70)
print(ele_car.base_message())
ele_car.desctibe_battery()
# 测试
# 手工测试
# 手工测试 函数
from data.MyPythonFunTest import get_formatted_name as gfn
print("Enter 'q' at any time to quit." )
while True:
first = input("\nPlease give me a first name:")
if first in "q":
break
last = input("Please give me a last name:")
if last == "q":
break
formatted_name = gfn(first, last)
print("\tNeatly foematted name:" + formatted_name + ".")
# 代码测试工具unittest
"""代码测试工具 unittest 单元测试(函数)"""
"""
unittest 无法运行 :
https://blog.csdn.net/u012291393/article/details/78636502
https://www.liaoxuefeng.com/discuss/969955749132672/1203224296196800
"""
import unittest
from data.MyPythonFunTest import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""测试data.MyPythonFunTest.get_formatted_name"""
def test_first_last_name(self):
"""能够正确处理包含姓和名的情况"""
formatted_name = get_formatted_name("jim", "green")
# self.assertEqual(formatted_name, "jim green")
self.assertEqual(formatted_name, "Jim Green")
def test_first_last_middle_name(self):
"""能够正确处理包含姓. 名和中间名的情况"""
formatted_name = get_formatted_name("martin", "king", "luther")
self.assertEqual(formatted_name, "Martin Luther King")
# 在jupter不好使
# unittest.main()
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
"""代码测试工具 unittest 单元测试(类)"""
from data.MyPythonFunTest import Area
import unittest
class AreaTestCase(unittest.TestCase):
def setUp(self):
self.area = Area()
def tearDown(self):
self.area = None
def testArea(self):
self.assertEqual(self.area.getArea(),10000)
def testWidth(self):
self.area.setWidth(10)
self.assertEqual(self.area.getWidth(),10)
def testLength(self):
self.area.setLenth(10)
self.assertEqual(self.area.getLength(),10)
if __name__ == "__main__":
unittest.main(argv=['first-arg-is-ignored'], exit=False)
# 文件读写
# 文件读取
"""文件读取"""
"""
with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,
比如文件使用后自动关闭/线程中锁的自动获取和释放等
"""
filepath = r"data\hello.txt"
# 传统模式
# try:
# file = open(filename, 'r', encoding='utf-8')
# contents = file.read()
# print(contents)
# file.close()
# except FileNotFoundError:
# print("文件不存在")
# else:
# print("文件读取成功")
# 用 with 方式
# with open(filename, 'r', encoding='utf-8') as file:
# contents = file.read()
# print(contents.rstrip()) # rstrip() 删除文件末尾的空白
# 单行读取
# with open(filename, 'r', encoding='utf-8') as file:
# lines = file.readlines() # 读取全部内容 ,并以列表方式返回
# for line in lines:
# print(line, end="")
# 判断文件是否存在
import os
flag = os.path.exists(filepath)
if flag == True:
with open(filename, 'r', encoding='utf-8') as file:
contents = file.read()
print(contents.rstrip())
else:
print("文件不存在")
# 文件写入
"""文件写入"""
filename = r"data/hello.txt"
# "w"把原来的文件覆盖掉
# with open(filename, 'w', encoding='utf-8') as file:
# # write返回值为写入字符数
# contents = file.write("你好世界\nHello World")
# print(contents)
# "a" 追加
# with open(filename, 'a', encoding='utf-8') as file:
# # write返回值为写入字符数
# contents = file.write("\nHello Python")
# print(contents)
"""异常处理"""
# try:
# num1 = eval(input("输入被除数:"))
# num2 = eval(input("输入除数:"))
# answer = num1/num2
# except ZeroDivisionError:
# print("除数不能为零")
# else:
# print("计算结果:" + str(answer))
num1 = eval(input("输入被除数:"))
num2 = eval(input("输入除数:"))
if(num2 != 0):
print(num1/num2)
else:
print("除数不能为0")
pass
# json数据读写
"""json数据 的读取,存储"""
import json
import os
def json_store(filepath):
"""文件存在什么都不做 文件不存在保存"""
# 创建字典
dic = {
"name":"李雷",
"age":20,
"addr":"上海"
}
flag = os.path.exists(filepath)
if flag:
pass
else:
# python对象编码成json字符串 dump()编码并存储
with open(filepath, 'w', encoding='utf-8') as file:
json.dump(dic, file)
print("保存成功")
def json_read(filepath):
"""从文件读取"""
flag = os.path.exists(filepath)
if flag:
# 文件读取 json解码为python对象(load)
with open(filepath, 'r', encoding='utf-8') as file:
json_obj = json.load(file)
return json_obj
else:
pass
filepath = r"data\test.json"
json_store(filepath)
data = json_read(filepath=filepath)
print("欢迎" + data["name"] + "同学")
编辑 (opens new window)
上次更新: 2022/04/13, 21:51:31