1、变量类型
a = 1
print ( a)
a = 3
print ( a)
string1 = "我是王振豪"
string2 = "我是王振豪2"
print ( string1+ string2)
print ( string1[ 0 ] )
print ( string1[ - 1 ] )
print ( string1[ 0 : 4 ] )
a = 1.5
d = None
e = True
2、注释
①
②'''
asd
''' ( 多行注释)
③ctrl+ / : 注释
3、输入
user_age = input ( "请输入您的年龄:" )
int ( )
float ( )
str ( )
user_age1 = int ( input ( "请输入您的分数:" ) )
user_age_after_10_year = user_age1 + 10
print ( "您十年后会是" + str ( user_age_after_10_year) + "岁" )
user_weight = float ( input ( "请输入您的体重:" ) )
user_height = float ( input ( "请输入您的身高:" ) )
user_BMI = user_weight/ ( user_height) ** 2
print ( "您的BMI值为:" + str ( user_BMI) )
4、函数
def get_sum ( sum1, sum2) :
result = sum1 + sum2
return result
a = 1
b = 3
c = get_sum( a, b)
print ( c)
def calculate_BMI ( weight, height) :
BMI = weight/ height** 2
if BMI <= 18.5 :
print ( "您的BMI分类为:偏瘦" )
elif BMI <= 25 :
print ( "您的BMI分类为:正常" )
elif BMI <= 30 :
print ( "您的BMI分类为:偏胖" )
else :
print ( "您的BMI分类为:肥胖" )
return BMI
BMI = calculate_BMI( 100 , 180 )
print ( "BMI为:" + str ( BMI) )
type ( "hello" )
type ( 6 )
type ( 6.0 )
type ( true)
type ( None )
5、条件语句
mood_index = int ( input ( "对象今天的心情指数是:" ) )
if mood_index >= 60 :
print ( "恭喜,今晚应该可以打游戏" )
print ( "666" )
else :
print ( "为了自个小命,还是别打了" )
user_weight = float ( input ( "请输入您的体重:" ) )
user_height = float ( input ( "请输入您的身高:" ) )
user_BMI = user_weight/ ( user_height) ** 2
print ( "您的BMI值为:" + str ( user_BMI) )
if user_BMI <= 18.5 :
print ( "偏瘦" )
elif 18.5 < user_BMI <= 25 :
print ( "正常" )
elif 25 < user_BMI <= 30 :
print ( "偏胖" )
else :
print ( "肥胖" )
6、逻辑运算
7、列表、字典、元组
list1 = [ ]
shopping_list = [ "键盘" , "键帽" ]
print ( shopping_list)
shopping_list. append( "显示器" )
print ( shopping_list)
shopping_list. remove( "键盘" )
print ( shopping_list)
print ( len ( shopping_list) )
print ( shopping_list[ 0 ] )
num_list = [ 1 , 13 , - 7 , 2 , 96 ]
print ( max ( num_list) )
print ( min ( num_list) )
print ( sorted ( num_list) )
contacts = { "小明" : "213123" , "小花" : "dsadsads" }
contacts[ "小明" ]
contacts[ "美女A" ] = "238834732"
"小明" in contacts
del contacts[ "小明" ]
len ( contacts)
contacts. keys( )
contacts. values( )
contacts. items( )
contacts1 = { ( "张伟" , 23 ) : "3221312313" , ( "张伟" , 34 ) : "378743" , ( "张伟" , 56 ) : "34324324" }
zhangwei23_phone = contacts1[ ( "张伟" , 23 ) ]
slang_dict = { "觉醒年代" : "wzh" , "YYDS" : "wzh2" }
slang_dict[ "破防" ] = "wzh3"
query = input ( "请输入您想要查询的流行语:" )
if query in slang_dict:
print ( "您查询的" + query+ "含义如下" )
print ( slang_dict[ query] )
else :
print ( "您查询的流行语暂未收录。" )
print ( "当前本词典收录词条数为:" + str ( len ( slang_dict) ) + "条。" )
8、循环语句
for 变量名 in 可迭代对象:
temperature_dict = { "111" : 36.4 , "112" : 36.6 , "113" : 36.2 }
for temperature_tuple in temperature_dict. items( ) :
staff_id = temperature_tuple[ 0 ]
temperature = temperature_tuple[ 1 ]
if temperature >= 38 :
print ( staff_id)
total = 0
for i in range ( 1 , 101 ) :
total = total + i
print ( total)
while 条件A:
行动B
sum = 0
ant = 0
p = input ( "请输入数字(完成所有数字输入后,请输入q终止程序):" )
while p!= "q" :
num = float ( p)
sum += num
ant+= 1
p = input ( "请输入数字(完成所有数字输入后,请输入q终止程序):" )
if ant == 0 :
result = 0
else :
result = sum / ant
print ( "您输入的数字平均值为" + str ( result) )
9、字符串格式化
wzh_dict = { "小明" : 3.231 , "小王" : 7.31 , "小李" : 4.23 }
for name, sno in wzh_dict. items( ) :
print ( "{0}你好,您当前的绩点为{1:.2f}" . format ( name, sno) )
print ( "{name1}你好,您当前的绩点为{sno1:.2f}" . format ( name1= name, sno1= sno) )
wzh_dict = { "小明" : 3.231 , "小王" : 7.31 , "小李" : 4.23 }
for name, sno in wzh_dict. items( ) :
print ( f" { name} 你好,您当前的绩点为 { sno: .2f } " )
10、引入模块
①import 模块名
②from 模块名 import 函数名
③from 模块名 import * (引入所有函数)
按住ctrl点击函数名可以查看函数具体如何实现
引入第三方模块(需要先下载再使用)
安装库:在终端输入:pip install 库名
11、面向对象
class NameOfClass :
class CuteCat :
def __init__ ( self, cat_name, cat_age, cat_color) :
self. name = cat_name
self. age = cat_age
self. color = cat_color
def speak ( self) :
print ( "喵" * self. age)
def think ( self, content) :
print ( f"小猫 { self. name} 在思考 { content} ..." )
cat1 = CuteCat( "Jojo" , 1 , "橙色" )
cat1. think( "现在去抓沙发还是去撕纸箱" )
案例:定义一个学生类
要求:
1 、属性包括学生姓名、学号,以及语数英三科的成绩
2 、能够设置学生某科目的成绩
3 、能够打印出该学生的所有科目的成绩
法一:
class Student :
def __init__ ( self, s_name, s_sno, s_yw, s_sx, s_yy) :
self. name = s_name
self. sno = s_sno
self. yw = s_yw
self. sx = s_sx
self. yy = s_yy
def set_grade_yw ( self, yw) :
self. yw = yw
def set_grade_sx ( self, sx) :
self. sx = sx
def set_grade_yy ( self, yy) :
self. yy = yy
def shuchu ( self) :
print ( f" { self. name} 的成绩为:语文 { self. yw} 、数学 { self. sx} 、英语 { self. yy} " )
stu = Student( "小王" , "123" , 56 , 66 , 87 )
stu. set_grade_yw( 100 )
stu. shuchu( )
法二:
class Student :
def __init__ ( self, name, sno) :
self. name = name
self. sno = sno
self. grades = { "语文" : 0 , "数学" : 0 , "英语" : 0 }
def set_grade ( self, course, grade) :
if course in self. grades:
self. grades[ course] = grade
def shuchu ( self) :
print ( f"学生 { self. name} 的成绩为:" )
for course in self. grades:
print ( f" { course} : { self. grades[ course] } 分" )
stu1 = Student( "小明" , "3211" )
stu2 = Student( "小王" , "23232" )
stu1. set_grade( "语文" , 45 )
stu1. shuchu( )
stu2. set_grade( "数学" , 100 )
stu2. shuchu( )
类的继承:class 子类(父类):
练习:人力系统
员工分为两类: 全职员工FullTimeEmployee、兼职员工PartTimeEmployee
全职和兼职都有“姓名 name”、"工号 id" 属性
都具备“打印信息 print_info”( 打印姓名、工号) 方法。
全职有“月薪 monthly_salary”属性
兼职有“日薪 daily_salary”属性、“每月工作天数 work_days”的属性
全职和兼职都有“计算月薪 calculate_monthly_pay”的方法,但具体计算过程不一样
class Employee :
def __init__ ( self, name, id ) :
self. name = name
self. id = id
def print_info ( self) :
print ( f"姓名: { self. name} ,工号: { self. id } " )
class FullTimeEmployee ( Employee) :
def __init__ ( self, name, id , monthly_salary) :
super ( ) . __init__( name, id )
self. monthly_salary = monthly_salary
def calculate_monthly_pay ( self) :
print ( f"月薪为: { self. monthly_salary} " )
class PartTimeEmployee ( Employee) :
def __init__ ( self, name, id , daily_salary, work_days) :
super ( ) . __init__( name, id )
self. daily_salary = daily_salary
self. work_days = work_days
def calculate_monthly_pay ( self) :
print ( f"月薪为: { self. daily_salary* self. work_days} " )
fe1 = PartTimeEmployee( "小王" , 23 , 200 , 25 )
fe1. print_info( )
fe1. calculate_monthly_pay( )
12、文件操作
一、文件读取
f = open ( "文件路径" , "r" , encoding= "utf-8" )
print ( f. read( ) )
print ( f. readline( ) )
使用:
line = f. readline( )
while line != " " :
print ( line)
line = f. readline( )
readlines( ) : 读全部文件内容,并把每行作为列表元素返回,一般配合for 循环使用
二、文件关闭
①f. close( )
②with open ( "文件路径" ) as f:
print ( f. read( ) )
三、例子
①f = open ( "./data" , "r" , encoding= "utf-8" )
content = f. read( )
print ( content)
f. close( )
②with open ( "./data" , "r" , encoding= "utf-8" ) as f:
lines = f. readlines( )
for line in lines:
print ( line)
四、写文件
f. write( "Hello!\n" )
f. write( "Yoooo" )
五、案例
with open ( "./poem.txt" , "w" , encoding= "utf-8" ) as f:
f. write( "我欲乘风归去\n" )
f. write( "又恐琼楼玉宇\n" )
f. write( "高处不胜寒。" )
with open ( "./poem.txt" , "a" , encoding= "utf-8" ) as f:
f. write( "起舞弄清影\n" )
f. write( "何似在人间。" )
13、异常处理
异常类型:IndexError( 索引错误) ZeroDivisionError( 除零错误) FileNotFoundError( 找不到文件错误) TypeError( 类型错误) 等等
捕捉异常:
try :
user_weight = float ( input ( "请输入您的体重:" ) )
user_height = float ( input ( "请输入您的身高:" ) )
user_BMI = user_weight/ user_height** 2
except ValueError:
print ( "输入不为合理数字,请重新运行程序,并输入正确的数字。" )
except ZeroDivisionError:
print ( "身高不能为零,请重新运行程序,并输入正确的数字。" )
except :
print ( "发生了未知错误,请重新运行程序。" )
else :
print ( "您的BMI值为:" + str ( user_BMI) )
finally :
print ( "程序结束运行。" )
14、测试
①assert 代码== 预期结果(若错误,则终止,不会进行后续测试)
②unittest库
例子:
my_calculator. py
def my_adder ( x, y) :
return x+ y
test_my_calculator. py
import unittest
from my_calculator import my_adder
class TestMyAdder ( unittest. TestCase) :
def test_positive_with_positive ( self) :
self. assertEqual( my_adder( 5 , 3 ) , 8 )
def test_negative_with_positive ( self) :
self. assertEqual( my_adder( - 5 , 3 ) , - 2 )
最后在终端运行:python - m unittest( 会自动搜索以test_开头的方法执行)
输出结果:. . ( 代表两个方法测试都通过了) ,若为:F. (代表第一个测试不通过)
③unittest. TestCase类的常见测试方法
assertEqual( A, B) 类似于assert A== B
assertTrue( A) 类似于assert A is True
assertIn( A, B) 类似于assert A in B
assertNotEqual( A, B) 类似于assert A!= B
assertFalse( A) 类似于assert A is False
assertNotIn( A, B) 类似于assert A not in B
setUp( ) : 当多个测试用例中用到同一个对象时,可以定义一个setUp方法,将该对象写进去,其他方法都可以用该对象(self. 对象名)
例子:
class ShoppingList :
"""初始化购物清单,shopping_list是字典类型,包含商品名和对应价格
例子:{“牙刷”:5,“沐浴露”:15,“电池”:7}"""
def __init__ ( self, shopping_list) :
self. shopping_list = shopping_list
def get_item_count ( self) :
return len ( self. shopping_list)
def get_total_price ( self) :
total_price = 0
for price in self. shopping_list. values( ) :
total_price+= price
return total_price
import unittest
from shopping_list import ShoppingList
class TestShoppingList ( unittest. TestCase) :
def setUp ( self) :
self. shopping_list = ShoppingList( { "纸巾" : 8 , "帽子" : 30 , "拖鞋" : 15 } )
def test_get_item_count ( self) :
self. assertEqual( self. shopping_list. get_item_count( ) , 3 )
def test_get_total_price ( self) :
self. assertEqual( self. shopping_list. get_total_price( ) , 53 )
15、高阶函数
例子:
def calculate_square ( num) :
return num* num
def calculate_cube ( num) :
return num* num* num
def calculate_plus_10 ( num) :
return num+ 10
calculate_and_print( num, calculator) :
result = calculator( num)
print ( "..." )
calculate_and_print( 3 , calculate_square)
calculate_and_print( 7 , calculate_plus_10)
例如:lambda num1, num2: num1+ num2等价于
def calculate_sum ( num1, num2) :
return num1+ num2