Python快速入门和使用
本篇主要介绍了Python的主要语法使用,能让你短时间内快速掌握Python的使用,轻松上手,也可做为日后参考的基础。
Python安装和编辑器安装请参考:Python入门-CSDN博客
Python常用语法和实例
#Control+/可以实现单行注释
"""
三个单/双引号可以实现多行注释
三个单/双引号也可以实现跨行输入
"""
print("跨行输入:")
print("""
白日依山尽
黄河入海流
欲穷千里目
更上一层楼
""")
print("\ninput使用和字符串拼接:")
# input为自带输入方法,使用强制转换可以将输入的内容变成强制转换类型
user_age=int(input("请输入你的年龄:"))
# 变量一般使用下划线命名法,字母小写,单词之间用下划线隔开
user_oldage=user_age+10;
"""
python字符串拼接方法:
方法一:str1="hello" str2="world" result=str1+str2
方法二:str_list = ["Hello", "World"] result = " ".join(str_list)
方法三:result = "%s %s" % (str1, str2)
方法四:格式化字符串,result= f"{str1} {str2}"
方法五:format {0}表示第一个占位符
:.2f表示保留2为小数
"""
print(f"你十年后的年龄是:{user_oldage}")
print("你现在年龄是{0},十年后的年龄是{1}".format(user_age, user_oldage))
width=120.5382
print(f"width:{width:.2f}")
print("\nif:")
xiaoming_age=12
# if语句
if xiaoming_age>user_age:
print("小明比你大")
elif xiaoming_age==user_age:
print("小明和你一样大")
else :
print("小明比你小")
print("\n逻辑运算(not,and,or):")
"""
and 与
or 或
not 非
优先级:not>and>or
"""
if user_age>18 and xiaoming_age>18:
print("你和小明都成年了")
elif user_age>18 or xiaoming_age>18:
print("你或小明成年了")
elif user_age > 18 and not xiaoming_age > 10:
print("你成年了,且小明还没长大")
else:
print("你和小明都未成年")
print("\n列表:")
# 列表,不定长
num_list=[1,-5,12,7]
print(min(num_list))
print(max(num_list))
print(sorted((num_list)))
num_list.append(8)
num_list.remove(12);
print(num_list);
print("\n字典:")
# 字典,以键值对形式存在
dictionary={"小明":12,"小雪":10,"小强":11}
print(dictionary)
print("\n"+str(dictionary["小雪"]))
del(dictionary["小雪"])
print(dictionary)
length=len(dictionary)
#打印字典所有键
print(dictionary.keys())
#打印字典所有键值对
print(dictionary.values())
#打印字典所有键
print(dictionary.items())
print("\nfor循环:")
# for循环 break退出循环,循环必须缩进
for num in num_list:
if(num>5):
print(num)
print("\nrange:")
"""
整数数列 range
第一个参数:初始值
第二个参数:结束值(不包含)
第三个参数:步长
"""
num_range=range(1,9,2)
for r in num_range:
print(r)
print("\nwhile循环:")
i=0
while i<len(num_list):
print(str(num_list[i]))
i=i+1
print("\n函数:")
"""
函数命名使用驼峰法:首字母大写
"""
def Sum_Num(a,b):
sum=a+b
return sum
print(f"计算合为{Sum_Num(12,35)}")
print("\n导入模块:")
import statistics
#median计算中位数
print(statistics.median(num_list))
print("\n类:")
"""
__init__:类的构造方法
"""
class Cat:
def __init__(self,name,age):
self.catname=name
self.catage=age
self.colors=["white","black","yellow"]
def ExistCatColor(self,color):
if(self.colors.count(color)>0):
print(f"有{color}的猫")
else:
print(f"没有{color}的猫")
cat1=Cat("Tom",3)
print(f"小猫{cat1.catname}已经{cat1.catage}岁了")
cat1.ExistCatColor("black")
cat1.ExistCatColor("red")
print("\n继承:")
"""
谁是谁的子类,就把父类写在()里面
子类实例化父类,会调用父类构造方法
"""
class Animal:
def __init__(self, name, age):
self.age = age
self.name = name
print(f"{self.name} can move")
def Deal(self):
print(f"{self.name} will deal")
class Human(Animal):
def __init__(self, name, age, tool):
super().__init__(name, age)
self.tool = tool
def UseTool(self):
print(f"human can use {self.tool}")
class Dog(Animal):
def __init__(self, name, age, food):
super().__init__(name, age)
self.food = food
def LikeFood(self):
print(f"Dog like {self.food}")
human1 = Human("Tom", 12, "锤子")
human1.UseTool()
dog1 = Dog("旺财", 2, "骨头")
dog1.LikeFood()
print("\n文件操作:")
"""
open 参数1:文件名
参数2:读写操作 r:读 w:写 a:附加 r+:读写
参数3:编码格式
"""
f=open("../data/test.txt","r",encoding="utf-8")
# 读取文件4个字节
print(f.read(3))
# 读取文件一行数据
print(f.readline())
# 读取文件所有内容,再次read读取为空
print(f.read())
# 关闭文件,释放资源
f.close()
#with 打开文件会自动释放资源,不需要手动close
with open("../data/test.txt","r+",encoding="utf-8") as file:
lines=file.readlines()
for line in lines:
print(line)
file.write("\n举头望明月,")
file.write("\n低头思故乡。")
lines = file.readlines()
for line in lines:
print(line)
print("\n异常处理:")
try:
user_weight = float(input("请输入您的体重(单位:kg):"))
user_height = float(input("请输入您的身高(单位:m):"))
user_BMI =user_weight /user_height ** 2
print(f"{user_BMI:.2f}")
except ValueError:
print("输入不为合理数字,请重新运行程序,并输入正确的数字。")
except ZeroDivisionError:
print("身高不能为零,请重新运行程序,并输入正确的数字。")
except:
print("发生了未知错误,请重新运行程序。")
Python测试
需要测试的函数方法
class Calculate:
def __init__(self,offset):
self.offset=offset
def Sum_Num(a,b):
sum=a+b
return sum
测试代码
"""
unittest为python测试库
assert会引起中断,后面程序不会执行
在中断输入python -m unittest,会搜索所有继承unittest的类,
并运行其以test_开头的所有方法,展示测试结果,需要有一个__init__.py文件(文件可空白)
assertEqual(A,B) assert A==B
assertTrue(A) assert A is True
assertIn(A,B) assert A in B
"""
import unittest
from program import sumnum
class TestSumNum(unittest.TestCase):
# setUp创建一个实例,后面的方法可以用这个实例调用
def setUp(self):
self.calculate=sumnum.Calculate(2)
def test_offset(self):
self.assertTrue(self.calculate.offset==2)
def test_positive_with_positive(self):
# assert Sum_Num(6,9)==15 assert会引起中断,后面程序不会执行
self.assertEqual(sumnum.Calculate.Sum_Num(6,9),14)
def test_negative_with_positive(self):
self.assertEqual(sumnum.Calculate.Sum_Num(-3, 9), 6)
if __name__ == '__main__':
unittest.main()
参考: