码迷,mamicode.com
首页 > 编程语言 > 详细

python基础学习

时间:2020-10-19 23:06:06      阅读:42      评论:0      收藏:0      [点我收藏+]

标签:前缀   影响   语句   other   奇数   like   swa   实现   容量   

python

变量的命名和使用

· 变量名只能包含字母、数字和下划线。不能以数字打头。
· 变量名不能包含空格,但可使用下划线来分隔其中的单词。
· 不要将Python关键字和函数名用作变量名。
· 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0。

列表、元组、集合、字典的区别是什么?

列表:元素可变(任何数据类型),有序(可索引),append/insert/pop;
元组:元素不可变,但元素中的可变元素是可变的;有序(可索引);而且元组可以被散列,例如作为字典的键。
集合:无序(不可被索引)、互异
字典:无序,键值对(key:value),key唯一不可重复

# -*- coding: utf-8 -*-

一、变量

#变量使用、空格引用、字符大小写、字符首字母大写、应用数值str()
first_name = "zhang"
last_name = "shan"
full_name = first_name+" "+last_name

print(full_name.upper())

print(full_name.lower())

name = "hello, "+full_name.title()+"!"
print(name)

age = "24"
message = full_name.title()+" is "+str(age)+" years old ! "
print(message)

#制表符和换行符
languages = "languages\t:\nc\nc++\npython\nphp\nperl"
print(languages)

#剔除空格
string = ‘ python ‘
#右侧空格剔除
print(string.rstrip())
#左侧空格剔除
print(string.lstrip())
#左右剔除
print(string.strip())

#计算加、乘、除、幂
print(5+2)
print(5*2)
print(5.0/2)
print(2**3)

二、列表

#列表
print("列表")
name = ["zhangfei","liubei","guanyu"]
print(name)

print("修改列表元素")
name[0]="sunshangxiang"
print(name)

print("在列表中添加元素到末尾")
name.append("zhaoyun")
print(name)

print("列表中插入元素")
name.insert(1,"zhugeliang")
print(name)

print("列表中删除元素")
print("1、del删除后无法访问")
del name[1]
print(name)

print("2、pop()任意位置删除后可使用\npop()删除列表末尾=弹出栈顶元素\n()中可填0、1...可弹出任意位置元素\nname.pop()后将删除元素引用到popped_name")
popped_name = name.pop()
print(name)

print("查看popped_name")
print(popped_name)

print("3、remove()根据值删除元素后可使用\n注:只删除第一次出现的值,若出现多次,需循环\n如:删除刘备")
removed_name = ‘liubei‘
name.remove(removed_name)
print(name)

print("查看removed_name")
print(removed_name)

print("\n")

#组织列表
print("新列表")
word = [‘c‘,‘s‘,‘d‘,‘n‘,‘a‘]
print(word)

print("1、sort()排序,排序后无法恢复")
word.sort()
print(word)

print("sort(reverse=True),逆序")
word = [‘c‘,‘s‘,‘d‘,‘n‘,‘a‘]
print(word)
word.sort(reverse=True)
print(word)

print("sorted()排序后不影响原列表,可以使用sorted(reverse=True)逆序==》不做例。")


print("\n")
print("2、reverse()不排序,直接反转列表元素,永久性但可再次reverse()恢复")
print("原列表与reverse后的列表")
word = [‘c‘,‘s‘,‘d‘,‘n‘,‘a‘]
print(word)
word.reverse()
print(word)

print("\n")
print("len(列表名)确定列表长度,\n例:len(word)")
word = [‘c‘,‘s‘,‘d‘,‘n‘,‘a‘]
print(word)
length = "len(word):"+str(len(word))
print(length)

print("打印最后一个元素,例:print(word[-1])")
print(word[-1])


三、操作列表(for语句)

#操作列表
print("1、for遍历列表")
names = [‘lubu‘,‘dainwei‘,‘daiochan‘,‘si‘,‘wu‘]
for name in names:
print(name)

print("\n2、缩进循环,不缩进只执行一次,‘for语句后首行要缩进‘.")
for name in names:
print("hello "+name.title()+" !")
print("Thank you,everyone !")

print("\n函数range(),例:range(1,6)打印1-5.")
for value in range(1,6):
print(value)

print("\n使用range()创建数字列表")
numbers = list(range(1,6))
print(numbers)

print("\nrange()可指定步长")
numbers1 = list(range(1,11,2))
print(numbers1)

print("\n1~10的平方")
#为了使代码简洁,可直接number2.append(value**2)
numbers2 = []
for value in range(1,11):
numbers3 = value**2
numbers2.append(numbers3)
print(numbers2)

print("\n将上述数字列表简单统计计算\n最小值为:")
print(min(numbers2))
print("\n最大值为:")
print(max(numbers2))
print("\n总和:")
print(sum(numbers2))

print("\n列表解析")
numbers4 = [value**2 for value in range(1,11)]
print(numbers4)

print("\n使用列表中多个元素\n1、切片:切取列表中前三个数字,和最后三个")
print(numbers4[0:3])
print(numbers4[-3:])

print("\n遍历切片,遍历前三个数字")
for value in numbers4[:3]:
print(value)

print("\n复制列表,若想复制的表不一样,可分别在每个表中修改后引用")
print(names)
names1 = names[:]
print(names1)
print("names1 = names 不可实现上述情况,此为两表关联,两表值绝对一致")

print("\n定义元组,元组元素不可修改,但可变量赋值,重新定义整个元组:")
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
dimensions = (400,100)
for dimension in dimensions:
print(dimension)

print("\n代码规范:\nPEP 8建议每级缩进都使用四个空格\n很多Python程序员都建议每行不超过80>字符\n不要在程序文件中过多地使用空行")


四、操作字典(for语句、if语句)
# 字典
people = {‘color‘:‘green‘,‘points‘:5}
print(people[‘color‘])
print(people[‘points‘])

# 字典应用【场景:射杀绿色,获得5点】
people = {‘color‘:‘green‘,‘points‘:5}
new_points = people[‘points‘]
print("you just earned "+str(new_points)+" points!")

# 字典新增键值对
people = {‘color‘:‘black‘,‘points‘:‘6‘}
print(people)
people[‘name‘] = "laozhang"
people[‘sex‘] = "man"
print(people)

# 定义空字典,添加键值对
class1 = {}
class1[‘name1‘] = "zhngfei"
class1[‘name2‘] = "liubei"
print(class1)

# 修改字典中的值
peopel = {‘color‘:‘green‘,‘points‘:‘2‘}
print("The people is "+people[‘color‘]+".")
people[‘color‘] = ‘yellow‘
print("The people is now "+people[‘color‘]+".")

# 例子:定初始速度级别,跟踪一个能够以某级别速度移动的人的位置,记录移动后的位置
alien_0 = {‘x_position‘: 0,‘y_position‘: 10,‘speed‘:‘quick‘}
print("Original x_position:"+str(alien_0[‘x_position‘]))
# 向右移动人
# 根据people的当前速度决定将其移动多远
if alien_0[‘speed‘] == ‘slow‘:
x_increment = 1
elif alien_0[‘speed‘] == ‘quick‘:
x_increment = 2
else:
# 这个alien的speed很快
x_increment = 3
# 新位置=老位置加上增量
alien_0[‘x_position‘] = alien_0[‘x_position‘]+x_increment
print("New x_position:"+str(alien_0[‘x_position‘]))

# 删除键值对
people = {‘color‘:‘green‘,‘points‘:5}
print(people)
del people[‘points‘]
print(people)

# 由类似对象组成的字典
favorite_languages = {
‘zhangfei‘:‘python‘,
‘liubei‘:‘c‘,
‘guanyu‘:‘go‘,
}
print("liubei‘s favorite language is "+favorite_languages[‘guanyu‘].title()+".")

# 遍历字典
user = {
‘zhang‘:‘fei‘,
‘liu‘:‘bei‘,
‘guan‘:‘yu‘,
}
print("\n学生姓名:")
for xing,ming in user.items():
print("\nxing:"+xing.title())
print("ming:"+ming)
print(xing.title()+ming)

for name,language in favorite_languages.items():
print(name.title()+"‘s favorite language is "+ language.title()+".")

# 遍历字典中的所有键
favorite_languages = {
‘zhangfei‘:‘python‘,
‘liubei‘:‘c‘,
‘guanyu‘:‘go‘,
‘sunshangxiang‘:‘java‘
}
for name in favorite_languages.keys():
print(name.title())

# 字典列表组合使用(占用上一个字典内容)
friends = [‘liubei‘,‘sunshangxiang‘]

for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("hi,"+name.title()+",I see your favorite language is "+favorite_languages[name].title()+"!")


# 查看字典中是否存在该键
if ‘zhaoyun‘ not in favorite_languages.keys():
print("zhaoyun,啥都不喜欢!")

# 按顺序遍历字典
for name in sorted(favorite_languages.keys()):
print(name.title()+",hello!")

# 遍历字典中的所有值
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())

# 提取字典中的值,并去重
favorite_languages = {
‘huangzhong‘:‘python‘,
‘zhaoyun‘:‘c++‘,
‘lubu‘:‘java‘,
‘dianwei‘:‘python‘,
‘hanxin‘:‘C++‘,
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())

# 嵌套
# 字典列表
alien_0 = {‘color‘:‘green‘,‘point‘:4}
alien_1 = {‘color‘:‘yellow‘,‘point‘:6}
alien_2 = {‘color‘:‘red‘,‘point‘:7}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)

# 创建空列表
print("创建外星人列表")
aliens = []
# 创建6个黄色的外星人
for alien_number in range(6):
new_alien = {‘color‘:‘yellow‘,‘points‘:5,‘speed‘:‘slow‘}
aliens.append(new_alien)
# 显示前四个外星人
for alien in aliens[:4]:
print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens:"+str(len(aliens)))

# 创建空列表,并修改列表一部分字段
print("创建外星人列表1")
aliens_1 = []
# 创建10个绿色的外星人
for people_number in range(10):
new_people = {‘color‘:‘green‘,‘points‘:5,‘speed‘:‘slow‘}
aliens_1.append(new_people)
for people in aliens_1[0:3]:
if people[‘color‘] == ‘green‘:
people[‘color‘] = ‘red‘
people[‘speed‘] = ‘quick‘
people[‘points‘] = 10
# 显示前5个外星人
for people in aliens_1[:5]:
print(people)
print("...")

# 添加elif语句
for people in aliens_1[:10]:
if people[‘color‘] == ‘red‘:
people[‘color‘] = ‘black‘
people[‘speed‘] = ‘stop‘
people[‘points‘] = ‘100‘
elif people[‘color‘] == ‘green‘:
people[‘color‘] = ‘blue‘
people[‘speed‘] = ‘speedy‘
people[‘points‘] = ‘666‘
for people in aliens_1[:10]:
print(people)

# 在字典中存储列表
#(存储所点披萨的信息)
pizza = {
‘crust‘:‘thick‘,
‘toppings‘:[‘mushrooms‘,‘cheese‘],
}
print("概述所点的披萨")
print("you ordered a "+pizza[‘crust‘]+"-crust pizza "+"with the following toppings: ")
for topping in pizza[‘toppings‘]:
print("\t"+topping)

# 字典中一个键关联多个值,for循环遍历每个键的所有值
print("for循环遍历每个键的所有值")
favorite_languages = {
‘dage‘:[‘python‘,‘ruby‘],
‘zhangfei‘:[‘c‘,‘c++‘],
‘zhaoyun‘:[‘java‘],
‘huangzhong‘:[‘go‘,‘java‘],
}
for name,languages in favorite_languages.items():
print("\n"+name.title()+"‘s favorite languages are: ")
for language in languages:
print("\t"+language.title())

#
#for name,languages in favorite_languages.items():
# print(len(languages))
# num = len(languages)
# if num == ‘1‘:
# print("\n"+name.title()+"‘s favorite languages is "+languages.title())
# elif num != ‘1‘:
# print("\n"+name.title()+"‘s favorite languages are "+languages.title())

# 字典中存储字典

users = {
‘laozhang‘:{
‘first‘:‘zhang‘,
‘second‘:‘shan‘,
},
‘laowang‘:{
‘first‘:‘wang‘,
‘second‘:‘qiang‘,
},
}

for username,user_info in users.items():
print("\nusername: "+username)
full_name = user_info[‘first‘]+" "+user_info[‘second‘]
print("\t full name: "+full_name.title())


五、用户输入和while循环
# -*- coding:utf-8 -*-

# python 2.7 函数raw_input()== python 3 函数input():将输入解读为字符串。
# 用户输入和while循环

#函数input()--暂停程序,获取用户输入文本,将文本存储在变量中

message = str(input("Tell me something,and I will repeat it back to you:"))
print(message)

# 打印多行信息
prompt = "if you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\nHello, "+name+"!")

# 用int()来获取数值输入
# 判断身高是否满足要求
height = input("How tall are you, in inches?")
height = int(height)
if height >= 36:
print("\nYou‘re tall enough to ride!")
else:
print("\nYou‘ll be able to ride when you‘re a little ollder.")

# 求模运算符(判断数值奇偶)
number = input("Enter a number, and I‘ll tell you if it‘s even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number "+str(number)+" is even.")
else:
print("\nThe number "+str(number)+" is odd.")

# while循环简介
# while循环1~5
current_number = 1
while current_number <= 5:
print(current_number)
current_number+= 1

# 让用户选择何时退出(定义退岀值)
prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter ‘quit‘ to end the program."
message = ""
while message != ‘quit‘:
message = input(prompt)
if message != ‘quit‘:
print(message)

# 使用标志
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter ‘quit‘ to end the program."
active = True
while active:
message = input(prompt)
if message == ‘quit‘:
active = False
else:
print(message)

# 使用break退出循环(以while True打头的循环(见?)将不断运行,直到遇到break语句)
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\nEnter ‘quit‘ when you are finished."
while True:
city = input(prompt)
if city == ‘quit‘:
break
else:
print("I‘d love to go to "+city.title()+"!")

# 在循环中使用continue(要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句)
# 1~10打印奇数
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)

# 避免无限循环
# (确认程序至少有一个这样的地方能让循环条件为False或让break语句得以执行。)

 

# 使用while循环来处理列表和字典
# 一、在列表之间移动元素

# 首先创建一个待验证的用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = [‘zhangfei‘,‘guanyu‘,‘liubei‘]
confirmed_users = []
# 验证每个用户,知道没有未验证用户为止
# 将每一个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: "+current_user.title())
confirmed_users.append(current_user)
# 显示已验证的用户
print("\nThe following users have been confirmed: ")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

# 使用用户输入来填充字典

responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
# 提示输入被调查者名字和回答
name = input("\nwhat is your name?")
response = input("which mountain would you like to climb someday?")
# 将答卷存储在字典中
responses[name] = response
# 看看是否还有人要参与调查
repeat = input("would you like to let another person respond?(yes/no)")
if repeat == ‘no‘:
polling_active = False
# 调查结束,显示结果
print("\n--- poll results ---")
for name,response in responses.items():
print(name+" would like to climb "+response+".")

六、函数+模块

# -*- coding: utf-8 -*-

# 函数

# 定义函数
# (关键字def来告诉Python你要定义一个函数;函数定义,向Python指出了函数名,还可能在括号内指出函数为完成其任务需要什么样的信息---在这里,函数名为greet_user(),它不需要任何信息就能完成其工作,因此括号是空的)

# 紧跟在def greet_user():后面的所有缩进行构成了函数体。"""文本"""---文档字符串的注释

def greet_user():
"""显示简单的问候语"""
print("hello!")
greet_user()

# 向函数传递信息

def greet_user(username):
"""显示简单的问候语"""
print("hello~"+username.title()+"!")
greet_user(‘zhangfei‘)

# 实参和形参
# 函数greet_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息;在代码greet_user(‘jesse‘)中,值‘jesse‘是一个实参--实参是调用函数时传递给函数的信息。

# 位置实参
# (你调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。)

def describe_pet(animal_type,animal_name):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"‘s name is "+animal_name.title()+".")
describe_pet(‘dog‘,‘coco‘)
# 多次调用函数
describe_pet(‘rabbit‘,‘dudu‘)

# 关键字实参(实参中将名称和值关联起来)
def describe_pet(animal_type,animal_name):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"‘s name is "+animal_name.title()+".")
describe_pet(animal_type=‘dog‘,animal_name=‘coco‘)
describe_pet(animal_type=‘rabbit‘,animal_name=‘dudu‘)

# 默认值
def describe_pet(animal_name,animal_type=‘dog‘):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"‘s name is "+animal_name.title()+".")
describe_pet(animal_name=‘liao‘)
# 若给animal_type提供了实参,将忽略形参的默认值
describe_pet(‘lisa‘,‘rabbit‘)

# 等效的函数调用
def describe_pet(animal_name,animal_type=‘dog‘):
"""显示宠物信息"""
print("\nI have a "+animal_type+".")
print("My "+animal_type+"‘s name is "+animal_name.title()+".")
describe_pet(‘liao‘)
describe_pet(animal_name=‘liao‘)
describe_pet(‘coco‘,‘rabbit‘)
describe_pet(animal_name=‘coco‘,animal_type=‘rabbit‘)
describe_pet(animal_type=‘rabbit‘,animal_name=‘coco‘)

# 避免实参错误
# traceback指出了问题出在什么地方,确保函数调用和函数定义匹配。

# 返回值--return语句
# 返回简单值(接受名和姓并返回整洁的姓名)
def get_formatted_name(first_name,last_name):
"""返回整洁的姓名"""
full_name = first_name+‘ ‘+last_name
return full_name.title()
musician = get_formatted_name(‘zhang‘,‘shan‘)
print("\n"+musician)

# 让实参变成可选的
# 名字有中间名:如张三丰
def get_formatted_name(first_name,middle_name,last_name):
"""返回整洁的姓名"""
full_name = first_name+‘ ‘+middle_name+‘ ‘+last_name
return full_name.title()
musician = get_formatted_name(‘zhang‘,‘san‘,‘feng‘)
print(musician)

# 若并非所有人都有中间名--中间名可选(指定默认值--空字符串)
def get_formatted_name(first_name,last_name,middle_name=‘‘):
"""返回整洁的姓名"""
if middle_name:
full_name = first_name+‘ ‘+middle_name+‘ ‘+last_name
else:
full_name = first_name+‘ ‘+last_name
return full_name.title()
musician = get_formatted_name(‘zhao‘,‘yun‘)
print(musician)
musician = get_formatted_name(‘zhao‘,‘zi‘,‘long‘)
print(musician)

# 返回字典
def build_person(first_name,last_name):
"""返回字典,其中包含有关一个人的信息"""
person = {‘first‘:first_name,‘last‘:last_name}
return person
musician = build_person(‘huang‘,‘zhong‘)
print(musician)

def build_person(first_name,last_name,age=‘‘):
"""返回一个字典,其中包含有关一个人的信息"""
person = {‘first‘:first_name,‘last‘:last_name}
if age:
person[‘age‘] = age
return person
musician = build_person(‘zhang‘,‘fei‘,age=38)
print(musician)

# 结合使用函数和while循环
def get_formatted_name(first_name,last_name):
"""返回整洁的姓名"""
full_name = first_name+‘ ‘+last_name
return full_name.title()
# 这是一个无限循环!
while True:
print("\nplease tell me your name:")
print("(enter ‘q‘ at any time to quit)")
f_name = input("first_name:")
l_name = input("last_name:")
if f_name == ‘q‘ and l_name == ‘q‘:
break
else:
formatted_name = get_formatted_name(f_name,l_name)
print("\nhello, "+formatted_name+"!")

# 传递列表
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "hello, "+name.title()+"!"
print(msg)
usernames = [‘zhangfei‘,‘liubei‘,‘guanyu‘]
greet_users(usernames)

# 在函数中修改列表
# 首先创建一个列表,其中包含一些要打印的设计
unprinted = [‘huawei‘,‘oppo‘,‘xiaomi‘]
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted:
current = unprinted.pop()
# 模拟根据设计制作打印模型的过程
print("printing model: "+current)
completed_models.append(current)
# 显示打印好的所有模型
print("\nthe following models have been printed:")
for completed_model in completed_models:
print(completed_model)

# 函数引用---第一个负责打印设计的,一个负责概述打印哪些设计
def print_models(unprinted,completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
"""
while unprinted:
current = unprinted.pop()
# 模拟根据设计制作3D打印模型的过程
print("printing model: "+current)
completed_models.append(current)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
print("\nthe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted = [‘dog‘,‘rabbit‘,‘cat‘]
completed_models = []
print_models(unprinted,completed_models)
show_completed_models(completed_models)

# 禁止函数修改列表
# 可用切片表示法--将列表的副本传递给函数,如:function_name(list_name[:])
# print_models(unprinted[:],completed_models)

# 传递任意数量的实参
# (形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中)
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza(‘pepperoni‘)
make_pizza(‘mushrooms‘,‘green peppers‘,‘extra cheese‘)

# 加入循环
def make_pizza(size,*toppings):
"""打印顾客点的所有配料"""
print("\nmakeing a "+str(size)+
"-inch pizza with the following topping:")
for topping in toppings:
print("- "+topping)
make_pizza(‘66‘,‘pepperoni‘)
make_pizza(‘99‘,‘mushrooms‘,‘green peppers‘,‘extra cheese‘)

# 使用任意数量的关键字实参
# (形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有>名称—值对都封装到这个字典中)
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile[‘first_name‘] = first
profile[‘last_name‘] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile(‘zhang‘,‘shan‘,
location=‘china‘,
field=‘physics‘)
print(user_profile)

# 将函数存储在模块中
# 导入整个模块

# cat pizza.py
#def make_pizza(size,*toppings):
# """概述要制作的披萨"""
# print("\nmakeing a "+str(size)+
# "-inch pizza with the following toppings:")
# for topping in toppings:
# print("- "+topping)

# 在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza()两次:

# cat making_pizzas.py
import pizza
pizza.make_pizza(16,‘pepperoni‘)
pizza.make_pizza(21,‘mushrooms‘,‘green peppers‘,‘extra cheese‘)

# import语句可以导入模块中的任何一个函数(模块中有多个函数)
# 例如:module_name.function_name()


# 导入特定的函数
# 导入方法的语法:from module_name importfunction_name
# 逗号分隔函数名,可根据需要从模块中导入任意数量的函数:from module_name importfunction_0,function_1,function_2

from pizza import make_pizza
make_pizza(33,‘haha‘)
make_pizza(44,‘hehe‘,‘hoho‘,‘huhu‘)

# 使用as给函数指定别名-语法:from module_name importfunction_name as fn
# 下面给函数make_pizza()指定了别名mp()。这是在import语句中使用make_pizza asmp实现的,关键字as将函数重命名为你提供的别名
from pizza import make_pizza as mp
mp(55,‘laozhang‘)
mp(66,‘laowang‘,‘laoli‘,‘laohuang‘)

# 使用as给模块指定别名-语法:importmodule_name as mn
import pizza as p
p.make_pizza(77,‘coco‘)
p.make_pizza(88,‘lili‘,‘bobo‘,‘popo‘)

# 导入模块中的所有函数-语法:from pizza import *
# 使用星号(*)运算符可让python导入模块中的所有函数:
from pizza import *
make_pizza(110,‘wowo‘)
make_pizza(220,‘qoqo‘,‘eoeo‘,‘roro‘)

七、类

# -*- coding: utf-8 -*-
# 类
# 创建和使用类
# 创建Dog类(约定,在Python中,首字母大写的名称指的是类)
# 1.方法_int_() :类中的函数称为方法,开头和末尾各有两个下划线,这是一种约定.
# 在这个方法的定义中,形参self必不可少,还必须位于其他形参的前面---原因:每个与类相关联的方法调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。

# 以self为前缀的变量都可供类中的所有方法使用,我们还可以通过类的任何实例来访问这些变量;
# self.name = name获取存储在形参name中的值,并将其存储到变量name中,通过实例访问的变量称为属>性;

class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self,name,age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title()+" is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title()+" rolled over!")
my_dog = Dog(‘willie‘,6)
print("my dog‘s name is "+my_dog.name.title()+".")
print("my dog is "+str(my_dog.age)+" years old.")
# Python使用实参‘willie‘和6调用Dog类中的方法__init__()。方法__init__()创建一个表示特定小狗的示例

# 在Python 2.7中创建类时,需要做细微的修改——在括号内包含单词object:
#class classname(object):
# --snip--

# 1.访问属性2.调用方法
# 要访问实例的属性,可使用句点表示法,如下代码来访问my_dog的属性name的值:
my_dog.name
class Dog():
"""一次模拟小狗的简单尝试"""
def __init__(self,name,age):
"""初始化属性name和age"""
self.name = name
self.age = age
def sit(self):
"""模拟小狗被命令时蹲下"""
print(self.name.title()+" is now sitting.")
def roll_over(self):
"""模拟小狗被命令时打滚"""
print(self.name.title()+" rolled over!")
my_dog = Dog(‘willie‘,6)
my_dog.sit()
my_dog.roll_over()

# 使用类和实例--car类
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+‘ ‘+self.make+‘ ‘+self.model
return long_name.title()
my_new_car = Car(‘audi‘,‘a4‘,‘2020‘)
print(my_new_car.get_descriptive_name())

# 给属性指定默认值,添加一个名为odometer_reading的属性,其初始值总是为0;名为read_odometer()的方法,用于读取汽车的里程表
class Car():
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+‘ ‘+self.make+‘ ‘+self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("this car has "+str(self.odometer_reading)+" miles on it.")
my_new_car = Car(‘audi‘,‘a4‘,2020)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

# 修改属性的值
my_new_car = Car(‘audi‘,‘a4‘,2020)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# 通过方法修改属性的值
class Car():
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+‘ ‘+self.make+‘ ‘+self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("this car has "+str(self.odometer_reading)+" miles on it.")
def update_odometer(self,mileage):
"""将里程表读数设置为指定的值"""
self.odometer_reading = mileage
my_new_car = Car(‘audi‘,‘a4‘,2021)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(66)
my_new_car.read_odometer()

# 对方法update_odometer()进行扩展,添加逻辑

class Car():
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year)+‘ ‘+self.make+‘ ‘+self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("this car has "+str(self.odometer_reading)+" miles on it.")
def update_odometer(self,mileage):
"""
将里程表读数设置为指定的值
禁止将里程表读数往回调
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("you can‘t roll back an odometer!")
#my_new_car = Car(‘audi‘,‘a4‘,2021)
#print(my_new_car.get_descriptive_name())
#my_new_car.update_odometer(-1)
#my_new_car.read_odometer()

# 通过方法对属性的值进行递增
def increment_odometer(self,miles):
"""讲里程表读数曾加指定的量"""
self.odometer_reading+= miles
my_used_car = Car(‘subaru‘,‘outback‘,2022)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(5000)
my_used_car.read_odometer()
my_used_car.increment_odometer(-6000)
my_used_car.read_odometer()


# 继承(子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法)

class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year)+‘ ‘+self.make+‘ ‘+self.model
return long_name.title()
def read_odometer(self):
print("this car has "+str(self.odometer_reading)+" miles on it.")
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("you can‘t roll back an odometer!")
def increment_odometer(self,miles):
self.odometer_reading+= miles
class ElectricCar(Car):
"""电动汽车独特之处"""
def __init__(self,make,model,year):
"""初始化父类的属性"""
Car.__init__(self,make,model,year)
my_tesla = ElectricCar(‘tesla‘,‘model s‘,2022)
print(my_tesla.get_descriptive_name())

# python2.7中的继承
#class Car(object):
# def __init__(self,make,model,year):
# --snip--
#class ElectricCar(Car):
# def __init__(self,make,model,year):
# super(ElectricCar,self).__init__(make,model,year)
# --snip--

# 给子类定义属性和方法

#class Car():
# --snip--
class ElectricCar(Car):
"""repersent aspects of a car,sepcific to electric vehicles."""
def __init__(self,make,model,year):
"""
电动汽车的独特之处
初始化父类的属性,再初始化电动汽车特有的属性
"""
Car.__init__(self,make,model,year)
self.battery_size = 70
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("this car has a "+str(self.battery_size)+"-kwh battery.")
my_tesla = ElectricCar(‘tesla‘,‘model s‘,2020)
print(my_tesla.get_descriptive_name())
print(my_tesla.describe_battery())

# 重写父类的方法(重写fill_gas_tank()的方法:调用该方法则忽略打印下述代码)

class ElectricCar(Car):
def fill_gas_tank():
"""电动汽车没有油箱"""
print("this car doesn‘t need a gas tank!")

# 将实例用作属性(可以将大类中同属性的小类提取出来作为大类中的一个属性)

#class Car():
# --snip--
class Battery():
"""一次模拟电动汽车电瓶的简单尝试"""
def __init__(self,battery_size=80):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("this car has a "+str(self.battery_size)+"-kwh battery.")
def get_range(self):
"""打印一条消息,指出电瓶的续航里程"""
if self.battery_size == 80:
range = 240
elif self.battery_size == 85:
range = 270
message = "this car can go approximately "+str(range)
message+= " miles on a full charge."
print(message)
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""
初始化父类的属性,再初始化电动汽车特有的属性
"""
Car.__init__(self,make,model,year)
self.battery = Battery(85)
# 若没有指定尺寸85,则默认值为80
my_tesla = ElectricCar(‘tesla‘,‘model‘,2023)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

# 导入类
# 导入单个类

# cat car.py
# (模块级文档字符串)
#"""一个可用于表示汽车的类"""
#class Car():
# """一次模拟汽车的简单尝试"""
# def __init__(self,make,model,year):
# """初始化描述汽车的属性"""
# self.make = make
# self.model = model
# self.year = year
# self.odometer_reading = 0
# def get_descriptive_name(self):
# """返回整洁的描述性名称"""
# long_name = str(self.year)+‘ ‘+self.make+‘ ‘+self.model
# return long_name.title()
# def read_odometer(self):
# """打印一条消息,指出汽车的里程"""
# print("this car has "+str(self.odometer_reading)+" miles on it.")
# def update_odometer(self,mileage):
# """
# 讲里程表读数设置为指定的值
# 拒绝将里程表往回拨
# """
# if mileage >= self.odometer_reading:
# self.odometer_reading = mileage
# else:
# print("you can‘t roll back an odometer!")
# def increment_odometer(self,miles):
# """讲里程表读数增加指定的量"""
# self.odometer_reading+= miles
# ***************************************
# cat my_car.py
#from car import Car
#my_new_car = Car(‘benchi‘,‘c320‘,2023)
#print(my_new_car.get_descriptive_name())
#my_new_car.odometer_reading = 23
#my_new_car.read_odometer()


# 在一个模块中存储多个类
# cat car.py

#"""一组用于表示燃油汽车和电动汽车的类"""
#class Car():
# --snip--
#class Battrey():
# --snip--
#class ElectricCar(Car):
# --snip--
# ************************
# cat my_electric_car.py
#from car import ElectricCar
#my_tesla = ElectricCar(‘tesla‘,‘model s‘,2030)
#print(my_tesla.get_descriptive_name())
#my_tesla.battery.describe_battery()
#my_tesla.battery.get_range()

# 从一个模块中导入多个类
# my_cars.py

#from car import Car,ElectricCar
#my_beetle = Car(‘volkswagen‘,‘beetle‘,2040)
#print(my_beetle.get_descriptive_name())
#my_tesla = ElectricCar(‘tesla‘,‘roadster‘,2050)
#print(my_tesla.get_get_descriptive_name())

# 导入整个模块
# my_cars.py

#import car
#my_dazhong = car.Car(‘jieda‘,‘dazhong‘,2010)
#print(my_dazhong.get_descriptive_name())
#my_tesla = car.ElectricCar(‘tesla‘,‘model s‘,2040)
#print(my_tesla.get_descriptive_name())

# 导入模块中的所有类(不推荐)
#frommodule_name import *

# 在一个模块中导入另一个模块

#cat car.py
#"""一个可用于表示汽车的类"""
#class Car():
# --snip--

#cat electric_car.py
#"""一组可用于表示电动汽车的类"""
#from car import Car
#class Battery():
# --snip--
#class ElectricCar(Car):
# --snip--

# 首先从模块collections中导入了OrderedDict类
# 创建了OrderedDict类的一个实例,并将其存储到favorite_languages中
# 调用OrderedDict()来创建一个空的有序字典,并将其存储在favorite_languages中。
# 接下来,我们以每次一对的方式添加名字—语言对
# 之后我们遍历favorite_languages

from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages[‘jen‘] = ‘python‘
favorite_languages[‘sarah‘] = ‘c‘
favorite_languages[‘edward‘] = ‘ruby‘
favorite_languages[‘phil‘] = ‘python‘
for name,language in favorite_languages.items():
print(name.title()+"‘s favorite language is "+ language.title()+".")


八、文件和异常

# -*- coding: utf-8 -*-
# 文件和异常

# 从文件中读取数据
# 读取整个文件
#cat pi_digits.txt
#3.1415926535
# 8979323846
# 2643383279

#cat file_reader.py
# 调用open()和close()来打开和关闭文件,使用方法read()读取这个文件的全部内容存储在contents中
with open(‘pi_digits.txt‘) as file_object:
contents = file_object.read()
print(contents)
# 结果多出一个空行(因为read()到达文件末尾时返回一个空字符串),删除空行-可使用rstrip()
print(contents.rstrip())

# 文件路径

# linux中"/"
#with open(‘text_files/filename.txt‘) as file_object:
# windows中"\"
#with open(‘text_files\filename.txt‘) as file_object:

# 绝对路径一般可能较长,可存储变量中
# linux中
#file_path = ‘/home/ehmatthes/other_files/text_files/filename.txt‘
#with open(file_path) as file_object:
# windows中
#file_path = ‘C:\User\ehmatthes\other_files\text_files\filename.txt‘
#with open(file_path) as file_object:

# 逐行读取
#cat file_reader.py
filename = ‘/pi_digits.txt‘
with open(filename) as file_object:
for line in file_object:
print(line)

# 创建一个包含文件各行内容的列表
filename = ‘pi_digits.txt‘
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())

# 使用文件的内容
#cat pi_string.py
filename = ‘pi_digits.txt‘
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ‘‘
for line in lines:
pi_string+= line.rstrip()
print(pi_string)
print(len(pi_string))

# 去除每行左边的空格--strip()
print("-----")
filename = ‘pi_digits.txt‘
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ‘‘
for line in lines:
pi_string+= line.strip()
print(pi_string)
print(len(pi_string))

# 打印到某一位,如打印到小数点后第十位
print(pi_string[:12]+"...")
print(len(pi_string))

# 搜索其中符合自己想要的字符串
birthday = input("enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
print("your birthday appears in the first million digits of pi!")
else:
print("your birthday does not appear in the first million digits of pi.")

# 写入文件
# (调用open()时提供了两个实参,指定读取模式(‘r‘)、写入模式(‘w‘)、附加模式(‘a‘)或让你能够读取和写入文件的模式(‘r+‘))
filename = ‘liujinye.txt‘
with open(filename,‘w‘) as file_object:
file_object.write("I love liujinye.\n")
# 写入多行
file_object.write("You‘re my baby !\n")

# 附加到文件(给文件添加内容)
with open(filename,‘a‘) as file_object:
file_object.write("I also love finding meaning in large datasets.\n")

# 异常
# (编写了处理异常的代码,程序将运行;未处理将停止并显示traceback报告)异常是try-except代码处理的

# 处理ZeroDivisionError异常
# cat division.py
#print(5/0)

# 使用try-except代码块

try:
print(5/0)
except ZeroDivisionError:
print("you can‘t divide by zero !")

# 使用异常避免崩溃
print("Give me two nmubers, and I‘ll divide them.")
print("Enter ‘q‘ to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == ‘q‘:
break
second_number = input("Second number:")
if second_number == ‘q‘:
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("you can‘t divide by 0 !")
except ValueError:
print("you can‘t input empty !")
else:
print(answer)

# 处理FileNotFoundError异常

filename = ‘empty.txt‘
try:
with open(filename) as f_obj:
contents = f_obj.read()
except IOError:
msg = "sorry, the file "+filename+" does not exist."
print(msg)

# 分析文本

 

python基础学习

标签:前缀   影响   语句   other   奇数   like   swa   实现   容量   

原文地址:https://www.cnblogs.com/zhangshan-log/p/13843010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!