列表
# 列表取出数据首字母大写(title函数)
# bicycles = ['trek','cannondale','redline','specialized']
# print(bicycles[0].title())
# 列表尾部添加元素(append函数)
# bicycles = ['trek','cannondale','redline','specialized']
# bicycles.append('suzuki')
# print(bicycles)
#列表任意位置添加元素(insert函数)
# bicycles = ['trek','cannondale','redline','specialized']
# bicycles.insert(0,'mazida')
# print(bicycles)
# 删除列表中任意位置元素(del函数,前提是知道索引)
# bicycles = ['trek','cannondale','redline','specialized']
# del bicycles[0]
# print(bicycles)
# pop方式删除列表数据(删除最后一位,类似于栈弹出操作,后进先出,根据传递的下标可以弹出指定位置数据,如果删除并不再使用,用del,删除后还需要的话,用pop)
# motorcycles = ['honda','yamaha','suzuki']
# print(motorcycles)
# poped_motorcycle = motorcycles.pop(0)
# print(motorcycles)
# print(poped_motorcycle)
# 根据值来删除元素(只能删除一次,只删除该值第一次出现的时候,若删除列表中所有的指定值,需要循环来实现)
# motorcycles = ['honda','yamaha','suzuki','honda']
# print(motorcycles)
# motorcycles.remove('honda')
# print(motorcycles)
#sort方法使用后列表修改且不可恢复(反向传递传递reverse=true)
# cars = ['bmw','audi','toyata','subura']
# cars.sort()
# print(cars)
# cars.sort(reverse=True)
# print(cars)
# sorted保留列表元素原来的顺序,同时以特定的方式呈现他们。
# cars = ['bmw','audi','toyata','subura']
# print(cars)
# print('after sorted\n')
# print(sorted(cars))
# print(cars)
# reverse反转列表中的排列顺序,reverse不按字母顺序反转,而是按照列表的顺序反转
#len()确定列表长度
# cars = ['bmw','audi','toyata','subura']
# print(cars)
# cars.reverse()
# print(cars)
# print(len(cars))
#操作列表,缩进展示代码之间的逻辑关系
#for循环遍历列表
# cars = ['bmw','audi','toyata','subura']
# print(cars)
# for car in cars:
# print(car)
# print(car.title()+",is so amazing")
# 避免缩进错误
# 1.不要忘记缩进
# 2.忘记缩进额外代码行
# 3.不必要的缩进
# 4.循环后不必要的缩进
# 5.不要遗漏循环后的冒号
# 创建数值列表
# 1.range()函数
# for value in range(1,5):
# print(value)
# 2.利用range创建数字列表
# numbers = list(range(1,6))
# print(numbers)
# 按照指定步长添加,(2,11,3)表明从2开始,范围是2-11,步长为3
# even_numbers = list(range(2,11,3))
# print(even_numbers)
# 3.创建平方数列表
# squares =[]
# for value in range(1,11):
# square = value**2
# squares.append(square)
# print(squares)
# 4.对数字列表执行简单的统计计算
# min取最小
# max取最大值
# sum对列表数字求和
# digits = [1,2,3,4,5,6,7,8,9,0]
# print(min(digits))
# print(max(digits))
# print(sum(digits))
# 列表解析
# squares = [value**2 for value in range(1,11)]
# print(squares)
# 切片(创建切片需要指定第一个元素和最后一个元素的索引)
# players = ['michael','harden','james','green','durant','duke']
# # print(players[0:3])
# # print(players[1:3])
# # # 倒数后三个元素输出
# # print(players[-3:])
# # 前三个元素输出
# print(players[:3])
# 复制列表
# my_foods = ['pizza','fateal','cake']
# friend_foods = my_foods[:]
# print("My favorite foods are:")
# print(my_foods)
# print("My friens' favorite foods are:")
# print(friend_foods)
#赋值(同一个列表)
# newfriend_foods = my_foods
# newfriend_foods.append('ice cream')
# print(my_foods)
元组(不可变的列表)
# 元组看起来犹如列表,但使用圆括号而不是方括号来标识
#遍历元组
# dimensions = (200,50,300,100)
# print(dimensions[0])
# print(dimensions[1])
# for dimension in dimensions:
# print(dimension)
#修改元组变量:重新定义元组
# dimensions = (200,50,300,100)
# for dimension in dimensions:
# print(dimension)
# dimensions = (400,100)
# for dimension in dimensions:
# print(dimension)
# python编码格式
# 1.缩进:建议每行四个空格
# 2.行长:建议不超过80个字符
# 3.空行:将程序的不同部分分开,区分功能
if语句遍历列表
# cars =['audi','bmw','subaru','toyota']
# for car in cars:
# if car == 'bmw':
# print(car.upper())
# else:
# print(car.title())
# = 赋值语句
# == 检查是否相等,检查是否相等时区分大小写
#若只是判断值是否相等,可以先进行小写转换操作lower()方法,再进行值的比较
# car = "Audi"
# if car == 'audi':
# print('true')
# else:
# print('false')
# != 检查是否不相等,检查两个值不相等的代码效率可能更高
# request_mapping = 'mushroom'
# if request_mapping != 'mushroo':
# print('true')
# else:
# print('false')
#数字之间的比较
# num = 10
# if num !=20:
# print('error')
# else:
# print('success')
# 检查多个条件
# 1.使用and检查多个条件 该检查项中每个表达式均为true,整个表达式才为true,若有一个不为真,则为false
# age_0 =22
# age_1 =18
# if age_0 >= 21 and age_1>=21:
# print(True)
# else:
# print(False)
# 2.使用or检查,该项中一个为真,则整个表达式为true,若有一个不为真,则为True
# age_0 =22
# age_1 =18
# if age_0 >= 21 or age_1>=21:
# print(True)
# else:
# print(False)
# 3.检查特定值是否包含在列表中,可以使用关键字in,另一种可以使用遍历搜索比较值
# cars =['audi','bmw','subaru','toyota']
# str = 'bmw'
# str1 = 'mesdi'
# if str in cars:
# print(True)
# else:
# print(False)
# if str1 not in cars:
# print(True)
# 4. if 最简单的if语句
# if something:
# dosomething
#
# 5.if-else语句
# 条件测试通过执行一个,未通过执行另一个操作
# if something:
# dosomething
# else:
# doanotherthing
# 6.if-else-else结构 判断超过两个的情形,多个elseif情形
# age = 88
# if age < 4:
# print('mianfei')
# elif age <18:
# print('banjia')
# elif age > 65:
# print('mianfei')
# else:
# print('quanjia')
# 7.省略不必要的else,防止无效的恶意攻击
# age = 88
# if age < 4:
# print('mianfei')
# elif age <18:
# print('banjia')
# elif age > 65:
# print('mianfei')
# 8.如果只想执行一个代码块,使用if-elif-else结构,运行多个建议使用一些列独立的if语句
# players = ['michael','harden','james','green','durant','duke']
# str1 ='harden'
# str2='james'
# str3= 'green'
# if str1 in players:
# print('sueccess1')
# elif str2 in players:
# print('sueccess2')
# elif str3 in players:
# print('sueccess3')
# 9.if语句判断列表是否为空
# cars = []
# if cars:
# for car in cars:
# print(car)
# else:
# print('cars is null')
# 10.判断多个列表元素是否重叠
# available_cars = ['bmw','audi','subaru','toyota']
# need_cars = ['audi','skoda']
# for need_car in need_cars:
# if need_car in available_cars:
# print('the car is in:'+need_car.title())
# else:
# print('you need buy the car:'+need_car.title())
# print('go back')
字典
# 字典形式类似于json格式,key-value存储。与键相关的值可以是数字、字符串、列表乃至字典(可以将任何python对象作为字典中的值)
#访问字典中的值的方式:字典名['键名']
# 添加键值对,字典名['键']=值
# 修改字典中的值:字典名['键']=新值
# bmw ={'color':'red','price':'500000','seat':'5'}
# print(bmw['price'])
# bmw['width']=2
# bmw['height']=2
# bmw['color']='green'
# print(bmw)
#删除键值对(删除将永远消失,如果需要访问则需要重新添加)
# bmw ={'color':'red','price':'500000','seat':'5'}
# del bmw['seat']
# print(bmw)
# 字典较长或列表过长,可以采取按行存属性
# language = {
# 'best_language':'python',
# 'popular_language':'java',
# 'power_lanuage':'c',
# 'outstanding_lanuage': 'javascript'
# }
# print('best language is:'+language['best_language'].title())
# 遍历字典(python不关心键值对的存储顺序,只关注键和值之间的关联关系)
# 遍历时key、value关键字可以自定义,项的数量要一致
# language = {
# 'best_language':'python',
# 'popular_language':'java',
# 'power_lanuage':'c',
# 'outstanding_lanuage': 'javascript',
# 'favorite_language':'python'
# }
# for key,value in language.items():
# print('Key:'+key)
# print('Value:'+value)
# 遍历所有的项与值
# for name,yuyan in language.items():
# print('Name:'+name)
# print('Value:'+yuyan)
# 遍历所有的键
# for name in language.keys():
# print(name.title())
# 遍历所有的值
# for lan in language.values():
# print(lan.title())
# 集合set,集合类似于列表,但每个元素都是独一无二的
# for lan in set(language.values()):
# print(lan.title())
# 字典列表
# car_0 ={'color':'green','name':'bmw'}
# car_1 ={'color':'yellow','name':'scoda'}
# car_3 ={'color':'red','name':'wma'}
# cars =[car_0,car_1,car_3]
# for car in cars:
# print(car)
# 在字典中存储列表
# 遍历列表中的列表
# develop_languages ={
# 'know':['python','ruby'],
# 'skilled':['python','java','javaScript'],
# 'professional':['javaScript','java'],
# 'unknow':['ruby']
# }
# for name,language in develop_languages.items():
# print('\n'+name.title()+' favorite language is:')
# for lan in language:
# print('\t'+' language is:' + lan.title())
# 字典中嵌套字典
users={
'marin':{
'name':'cheng',
'age':'18',
'sex':'male'
},
'tonny':{
'name':'tonny',
'age':'28',
'sex':'male'
},
'jack':{
'name':'jack',
'age':'38',
'sex':'female'
}
}
for username,userinfo in users.items():
print('Username:'+username)
print(userinfo['name']+" 's age is:"+userinfo['age']+" and sex is:"+userinfo['sex'])
用户输入和while循环
# input函数(让程序暂停,等待用户输入一些文本,获取用户输入后,python将其存储在一个变量中,以供程序使用)
# message =input("tell me what's your favorite fruit:")
# print(message)
# 如果提示超过一行,建议将提示存储在一个变量中,再将该变量传递给函数input()
# prompt="if you like the wind,please look the sky after you get hurt:"
# message = input(prompt)
# print(message)
# 使用int来获取数值输入
# age = input("please input your age:")
# message = int(age)
# if message > 18:
# print('you are an adult')
# else:
# print('you are a child')
# print(message)
# 求模运算(求模运算将两个数相除并返回余数,可以用来判断奇偶性)
# print(4 % 3)
# print(5 % 3)
# num = input("please input the number:")
# message = int(num)
# if message % 2 ==0:
# print("the number you input is even")
# else:
# print("the number is odd")
# while循环(直到运行到指定的条件不满足为止)
# current_num = 1
# total = 0
# while current_num <= 5:
# current_num += 1
# total += current_num
# print(total)
# 自定义退出语句
# lip = '\n i will retuen the message that you input:'
# lip += '\n please input the exit to kill the process'
# message = ''
# while message !='exit':
# message = input(lip)
# if message !='exit':
# print(message)
# 自定义标志变量,判断程序的状态,控制程序进程
# lip = '\n i will retuen the message that you input:'
# lip += '\n please input the exit to kill the process'
# message = ''
# active = True
# while active:
# message = input(lip)
# if message =='exit':
# active = False
# else:
# print(message)
# break结束语句,退出循环
# prompt = "\n please enter the name of a city you have visited:"
# prompt += '\n(enter exit to kill the process)'
# while True:
# city = input(prompt)
# if city == 'exit':
# break
# else:
# print('i have gone to:' + city)
# continue再循环中的使用(返回循环开头,根据条件测试结果决定是否继续执行循环)
#避免编写无限循环,测试每条while语句
# current_num =0
# total =0
# while current_num < 10:
# current_num +=1
# if current_num % 2 ==0:
# continue
# print(current_num)
# total += current_num
# print(total)
# while循环处理列表和字典
# super_stars = ['james','kobe','harden','curry']
# mvp_starts = []
# while super_stars:
# current_starts = super_stars.pop()
# print('Have got mvp:'+current_starts.title())
# mvp_starts.append(current_starts)
# print("all MVP stars are:")
# for mvp in mvp_starts:
# print(mvp)
# 删除包含特定值的列表元素(之前说明remove只删除该值第一次出现的值,通过while循环和for循环可以删除所有)
# super_stars = ['james','kobe','harden','curry','micheal','westbrook','james','duke','james']
# str = 'james'
# print(super_stars)
# while str in super_stars:
# super_stars.remove(str)
# print(super_stars)
# 用户输入填充字典数据(字典key具有唯一性)
# fruits ={}
# active = True
# while active:
# name = input("\n please input your name:")
# fruit = input("\n please input your favorite fruit:")
# fruits[name] = fruit
# anotherFruit = input("Do you still love the another fruit:(yes/no)")
# if anotherFruit == 'no':
# active = False
# # break(没必要的语句,当active=false时,循环自动结束)
#
# for name,fruit in fruits.items():
# print(name + " like the fruit "+fruit)
函数
# 函数定义(def + 函数名+() 括号内是为了输入可能需要传递的一些参数)
# def hello():
# print('hello world')
# hello()
# 实参与形参,在下面的例子中,username是形参,可以随意命名(建议通俗易懂),marin是实参,需要传递的参数
# def greet(username):
# print('hello '+username)
# greet('marin')
# 传递实参的方式:位置实参、关键字实参
# 位置实参传递方式(要求形参的位置与实参的位置一一对应),函数的多次调用是一种高效率的方法
# def fans(name,star):
# print(name+"'s favorite star is:"+star)
# fans('marin','duke')
# fans('tonny','harden')
# 关键字实参方式:名称-值对,关键字传参不会混淆参数值,还能更加清楚指出各个值的用处
# def fans(name,star):
# print(name+"'s favorite star is:"+star)
# fans(name='marin',star='duke')
# fans(name='tonny',star='harden')
# 给定默认值(形参指定默认值后,对应调用中可以省略相应的实参,也可以重新指定实参的值)
# 使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参。
# def fans(name,star,age="29"):
# print(name+"'s favorite star is:"+star+" and his age is:"+age)
# fans(name="marin",star="duke")
# fans(name="tonny",star="harden",age="36")
# # 等效的函数调用
# def dog(sex,name="tonny",age="18"):
# print(name+"'s age is:"+age+" and his sex is:"+sex)
# dog("female")
# dog('male','jack','19')
# dog(sex="male",name="curry",age="28")
# 函数返回值(在函数中,可使用return语句将值返回到调用函数的代码行)
# def dog(sex,name="tonny",age="18"):
# return name+"'s age is:"+age+" and his sex is:"+sex
# print(dog('male'))
# print(dog('male','james'))
# 返回字典
# def person(name,age,sex):
# person = {'name':name,'age':age,'sex':sex}
# return person
# person1 = person('tonny','29','male')
# print(person1['name'])
# while循环与函数联合使用
# def greet_person(first_name,last_name):
# full_name = first_name +' ' +last_name
# return full_name
# while True:
# print("\n please enter you name")
# print("\n you can exit at any time by input(exit)")
# firstName = input("please input your first name:")
# if firstName =='exit':
# break
# lastName = input('please input your last name:')
# if lastName == 'exit':
# break
# fullname = greet_person(firstName,lastName)
# print("hello "+fullname)
# 列表参数
# users =['harden','duke','james','curry']
# def printHonor(names):
# for name in names:
# print("you are the super star:"+name)
# printHonor(users)
# 在函数中修改列表
# def paintingModel():
# unprinted_designs = ['iphone case','robot pendant','dodecahedron']
# completed_models = []
# while unprinted_designs:
# current_design = unprinted_designs.pop()
# print("painting model:"+current_design)
# completed_models.append(current_design)
# print("all Models have been printed!")
# for completed_model in completed_models:
# print("the model has been Painted:"+completed_model)
# paintingModel()
# 函数功能解耦
# 函数设计:最好一个函数只做一件事情,确保函数功能高度统一
# 如果不想让函数修改列表,可以传递列表副本,这样可以保证列表完整性,但是同时会影响函数效率,副本的创建会消耗时间和内存
# def paintingModel(unprinted_designs,completed_models):
# while unprinted_designs:
# current_design = unprinted_designs.pop()
# print("painting model:"+current_design)
# completed_models.append(current_design)
#
# def show_completed(completed_models):
# print("\n The following models have been printed:")
# for completed_model in completed_models:
# print("the model has been Painted:" + completed_model)
#
# unprinted_designs = ['iphone case','robot pendant','dodecahedron']
# completed_models = []
# paintingModel(unprinted_designs, completed_models)
# show_completed(completed_models)
# print(unprinted_designs)
# 副本函数传入
# paintingModel(unprinted_designs[:], completed_models)
# show_completed(completed_models)
# print(unprinted_designs)
# 接收任意数量实参(*toppings中的星号让python创建了一个空元组,并将接收到的所有值封装到元组中)
# def makeCake(*toppings):
# for topping in toppings:
# print("make cake needs:"+topping)
# makeCake('sugar','water','oil','cream')
# 结合使用位置实参和任意数量实参
# def makeCake(size,*toppings):
# print("make a "+size+" inch cake needs the following things:")
# for topping in toppings:
# print(topping)
# makeCake('16','sugar','water','oil','cream')
# 使用任意数量的关键字实参(返回的字典中包含所有的信息)
# def person(firstname,lastname,**userInfo):
# personInfo={}
# personInfo['firstName'] = firstname
# personInfo['lastName'] = lastname
# for key,value in userInfo.items():
# personInfo[key] =value
# return personInfo
# person1 = person("liang","cheng",age='18',location='anhui')
# print(person1)
# 函数存储于模块之中
# 要让函数是可导入的,要先创建模块。模块扩展名为.py的文件,包含要导入到程序中的代码,利用import方式导入
# person.py
# def createPerson(firstname,lastname,**userInfo):
# personInfo={}
# personInfo['firstName'] = firstname
# personInfo['lastName'] = lastname
# for key,value in userInfo.items():
# personInfo[key] =value
# return personInfo
# person1 = person("liang","cheng",age='18',location='anhui')
# print(person1)
# 导入特定的函数
# from person import createPerson
# 给导入函数指定别名
# from person import createPerson as cp
# cp("liang","cheng",age='18',location='anhui')
# 导入person模块中的所有函数
# (尽量不要使用这种方式,有可能会出现所引入文件中的函数名与当前文件中的函数名重复,进而导致错误)
# from person import *
## 函数编写几点建议:
## 1.给函数指定描述性名称,且在其中使用小写字母和下划线
## 2.描述性名称可以帮助别人明白代码实现的功能 #
## 3.模块命名最好也遵循上述约定 #
## 4.每个函数简要添加阐述功能的注释
## 5.def person(firstName,lastName,age='19')传入形参给定默认值时,等号两边不要留空格
## 6.建议代码长度单行不超过79个字符
## 7.所有的import语句应放在文件开头
## 8.一个程序包含多个函数,隔两行将相邻的函数分开,便于阅读
类
# 类的创建和使用
# Python中,首字母大写的名称指的是类
# __init__方法是一个特殊方法,每当根据person类创建新实例时,python会运行它
# 每个与类相关相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法
# 变量name和age都有前缀self,以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些对象
# self.name = name获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例。
# 可以通过实例访问的变量称为属性
# 通过句点表示法来访问属性(person.name)
# 调用方法,实例名称.方法名(person.name)
# class Person():
# def __init__(self,name,age):
# self.name = name
# self.age = age
# def read(self):
# print(self.name.title()+" is now reading")
# def write(self):
# print(self.name.title()+" is now writing")
# person1 = Person('marin','18')
# print(person1.name)
# 类的使用和修改
# 修改属性的值
# 1.直接修改:car.killmoter =1000
# 2.通过方法修改:在函数内创建一个方法,通过传入指定参数,利用函数调用来修改其值(updateKilo)
# class Car():
# def __init__(self,maker,model,year):
# self.maker = maker
# self.model = model
# self.year =year
# self.killmoter = 0
#
# def getCarInfo(self):
# info = "the car's maker is "+self.maker+" and his model is: "+self.model +" product year is: "+self.year
# print(info)
#
# def readKilo(self):
# print("the car has run "+str(self.killmoter))
#
# def updateKilo(self,mile):
# if mile > self.killmoter:
# self.killmoter = mile
# print("the kilometer has been modified successfully")
# else:
# print("you can not roll back")
#
# car = Car("Adui","Q5","2019")
# print(car.getCarInfo())
# print(car.readKilo())
# car.killmoter =1000
# print(car.readKilo())
# print(car.updateKilo(3))
# print(car.readKilo())
# 继承
# 一个类继承另一个类时,它将自动获取另一个类的所有属性和方法,原类称为父类,继承类称为子类
# 创建子类时,父类必须包含在当前文件夹中,且位于子类前面
# 定义子类时,必须在括号内指定父类的名称,方法__init__接手创建Car所需的信息
# super()是一个特殊函数,关联父类与子类
# 如果子类有自己的属性和方法,可以在继承之后添加
# 重写父类方法:
# 若父类方法不符合子类模拟的实物的行为,都可对其进行重写,子类重写父类方法时,要与重写的父类方法同名
# 当类越来越庞大,属性和方法越来越多时,可以考虑将类的一部分作为一个独立的类提取出来,将大类换成一个个小类
"""一个汽车简单类"""
# class Car():
# def __init__(self,maker,model,year):
# """初始化描述汽车的属性"""
# self.maker = maker
# self.model = model
# self.year =year
# self.killmoter = 0
#
# def getCarInfo(self):
# """返回对汽车属性的描述"""
# info = "the car's maker is "+self.maker+" and his model is: "+self.model +" product year is: "+self.year
# print(info)
#
# def tankInfo(self):
# print("the car has oil tank")
#
# class ElectricCar(Car):
# """电动汽车类"""
# def __init__(self,maker,model,year):
# super().__init__(maker,model,year)
# self.battery = 70
# def batteryInfo(self):
# print("this car has a "+str(self.battery)+" kw*h")
# def tankInfo(self):
# print("the electric car don't hava tank")
#
# class Battery():
# """电池类"""
# def __init__(self,batterySize=70):
# self.batterySize = batterySize
# def BatteryInfo(self):
# print("This car has a "+str(self.batterySize)+"Kwh battery!")
#
# class Electric(Car):
# """电动汽车类-引入Battery类"""
# def __init__(self,maker,model,year):
# super().__init__(maker,model,year)
# self.battery = Battery(80)
#
# tesla = ElectricCar("tsl","T3","2018")
# print(tesla.getCarInfo())
# print(tesla.batteryInfo())
# print(tesla.tankInfo())
#
# myTesla = Electric('tesla',"T4","2019")
# print(myTesla.battery.BatteryInfo())
# 导入类到子文件中与函数的导入方式类似
# from car import Car (前一个是car是文件名,后一个Car是类名)
# 一个模块中可以导入多个类
# from car import Car,ElectricCar
# 导入整个模块
# import car
# car.Car('tesla',"T4","2019")
# 导入模块中所有的类(不建议此类导入方式)
# for car import *
# 类的编码风格
# 1.类名采用驼峰命名方式(类似于CarInfo)
# 2.对于每个类,应该跟随一个文档字符串,简要描述类的功能,及相关一些使用要求
# 3.类中用一个空行来分隔功能函数,模块中可以用两个
# 4.导入模块时,先导入标准库中的模块,中间隔行,再导入自定义模块,便于区分(最好在标准库和自定义库文件头前面加上解释)
本文章部分案例参考《Python编程-从入门到实践》Eric Matthes著,书写的很好,这里安利一波。如有侵权,联系删除。希望给大家一点启发。如有不足,恳请批评指正。