python基础知识 (来源:学习《pthon从入门到实践》一书所做笔记)
1变量和简单数据类型
name="ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name
print(full_name)
制表符(前面有空格):\t,换行符\n
print("\tpython")
favorite_language=' python '
favorite_language=favorite_language.strip()
print(favorite_language)
age=23
message="Happy "+str(age)+"rd birthday"
print(message)
2学习列表
2.1列表是什么
bicycles=['trek','cannodake','readline','specialized']
print(bicycles)
2.2访问列表元素
bicycles=['trek','cannodake','readline','specialized']
print(bicycles[0])
2.3访问最后一个元素用-1,倒数第二个用-2…
print(bicycles[-1].title())
2.4使用列表中的各个值
message="My first bicycle was a "+bicycles[0].title()+"."
print(message)
2.5修改列表元素
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0]='ducati'
print(motorcycles)
2.5.1在列表末尾添加元素
motorcycles.append('ducati')
print(motorcycles)
2.5.2在列表中插入元素
motorcycles=['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
2.5.3从列表中删除元素,如果知道删除元素的位置使用del语句
del motorcycles[0]
print(motorcycles)
2.5.3.1使用pop删除元素
motorcycles=['honda','yamaha','suzuki']
print(motorcycles)
popped_motorcycle=motorcycles.pop(0)
print(motorcycles)
print(popped_motorcycle)
2.5.3.2根据值删除元素remove()
motorcycles.remove('yamaha')
print(motorcycles)
2.6.1使用sort()对列表进行永久性排序
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
2.6.1向sort()传递参数reverse=True相反顺序排列元素
cars.sort(reverse=True)
print(cars)
2.6.2使用函数sorted()对列表进行临时排序
cars=['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
2.7倒着打印列表reverse(),确定列表的长度len()
cars=['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
print(len(cars))
3 操作列表
3.1遍历整个列表for循环
magicains=['dsdjiw','daeic','carolina']
for magicain in magicains:
print(magicain.title()+",taht was a great trick!")
print("I can't wait to see your next trick,"+magicain.title()+".\n")
print("Thank you,everyone.That was a great magic show!")
3.2创建数字列表使用range()函数
for value in range(1,3):
print(value)
3.2.1使用range()创建数字列表
numbers=list(range(1,6))
print(numbers)
even_numbers=list(range(2,11,2))
print(even_numbers)
squares=[]
for value in range(1,11):
square=value**2
squares.append(square)
print(squares)
digits=[1,2,3,4,5,6,7,8]
print(max(digits))
print(min(digits))
print(sum(digits))
3.3列表解析
squares=[value**2 for value in range(1,11)]
print(squares)
players=['charles','martina','michal','wsjwi','dwdd','dddwd2']
print(players[0:3])
players=['charles','martina','michal','wsjwi','dwdd','dddwd2']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title ())
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print("my favorite foods are:")
print(my_foods)
friend_foods.append('ice cream')
print("\nmy favorite foods are:")
print(friend_foods)
3.4元组 不可变的列表
demensions=(200,5,6)
print(demensions[0])
print(demensions[1])
print(demensions[2])
dimensions=(200,2,2)
for dimension in dimensions:
print(dimension)
dimensions=(200,4)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions=(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
4 if语句
4.1基本用法
requested_topping='mushrooms'
if requested_topping!='annjid':
print("hold the annjid")
age_0=22
age_1=89
if age_0>20 and age_1<=19:
print("haa")
else:
print("heihei")
banned_users=['andrew','carolina','david']
user='marie'
if user not in banned_users:
print(user.title()+",you can post a respons if you wish")
4.2if-elif-else结构:需要检查超过两个的情形
age=12
if age<4:
print("your admission cost is $0.")
elif age<18:
print("your admission cost is $5.")
else:
print("your admission cost is $10.")
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print ("\nFinished making your pizza!")
4.3使用if语句处理列表
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding"+requested_topping+".")
print("\nFinisted making your pizza!")
else:
print ("are you sure you want a plain pizza?")
5 字典{}
5.1基本用法
alien_0={'color':'green','points':5}
print(alien_0['color'])
alien_0={'x_position':0,'y_posion':25,'speed':'medium'}
print("Original x_position:" + str(alien_0['x_position']))
if alien_0['speed']=='slow':
x_increment=1
elif alien_0['speed']=='medium':
x_increment=2
else:
x_increment=3
alien_0['x_position']=alien_0['x_position']+x_increment
print("New x_position:" + str(alien_0['x_position']))
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".")
5.2遍历所有键-值对应
user_0={
'username':'jhdshi',
'first':'suhb',
'last':'fermi',
}
for key,value in user_0.items():
print("\nKey:" + key)
print("\nValue:" + value)
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name,language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
5.3遍历字典中的所有键 方法keys()
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
5.3.1按顺序遍历字典中的所有键、函数sorted()
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ",thank you for taking the poll.")
5.3.2遍历字典中的所有值用value()方法,剔除重复项可使用集合set
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
5.4嵌套,将一系列字典储存在列表中
alien_0={'color':'green','point':5}
alien_1={'color':'yellow','point':10}
alien_2={'color':'red','point':15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
aliens=[]
for alien_number in range(30):
new_alien={'color':'green','point':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color']=='green':
alien['color']='yellow'
alien['speed']='medium'
alien['point']=10
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
5.5在字典中储存列表
favorite_languages={
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
5.6在字典中储存字典
users = {
'ifjri':{
'first':'fef',
'last':'fefef',
'location':'ojd',
},
'dedf':{
'first':'fsqf',
'last':'fefess',
'location':'ojsd',
},
}
for username,user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
6 用户输入和while循环
6.1函数input的工作原理
message=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 message you see."
prompt +="\nWhat is your fir st name?"
name=input(prompt)
print("\nHello," + name + "!")
使用int()来获取数值输入
height = input("How tall are you,in inches?")
height = int(height)
if height >= 36:
print("\nYou are tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
#求模运算符%返回余数
6.2while循环
prompt="\nTell me something,and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
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)
unconfirmed_users = ['alice','brian','candance']
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())
7函数
7.1用关键字def定义函数
def describe_pet(animal_type,pet_name):
"""显示宠物信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet('hamaster','harry')
7.2使用任意数量的关键字实参
def bulid_profile(first,last,**user_info): **让python创建一个名为user_info的空字典用于储存用户简介
"""创建一个字典其中包括我们知道的有关用户的一切"""
profile = {}
profile['fist_name'] = first
profile['last_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = bulid_profile(‘abbert’,‘einstein’, location =‘princeton’, field=‘physics’) print(user_profile)
7.3将函数储存在模块中,导入整个模块
def make_pizza(size,*toppings):
"""概述要制作的披萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
7.4使用as给函数或模块指定别名
from module_name import function_name as fn
import module_name as mn
7.5使用*运算符可以让python导入模块中的所有函数
from pizza import*
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
8 类
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('sasz',6)
print("My ndog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + "years old.")
8.1继承将获得另一个类的所有属性和方法
from hhh import ElectricCar
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.batery.get_range()
read()读取文件全部内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
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))
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
filename = 'programming.txt'
with open(filename,'a') as file_object:
file_object.write("I also love finding in datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
9异常处理
9.1处理ZeroDivisionError异常使用try-exceotion代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
print("Give me two numbers, and I'l 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
answer = int(first_number)/int(second_number)
print(answer)
9.2else代码块try-except代码块
print("Give me two numbers,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: ")
try:
answer = int(first_number)/(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry ,the file " + filename + " does not exist."
print(msg)
9.3分析文本
9.3.1储存数据使用json.dump()和json.load()
import json
numbers = [2,3,5,7,11,13]
filename = 'number.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
?
9.3.2使用json.load()将这个列表存储到内存中
import json
filename = 'number.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
import json
username = input("What is your name?")
filename ='username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We'll remenber you when you come back, " + username + "!")
import json
filename ='username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcom back," + username + "!")
10测试代码
def get_formatted_name(first,last,middle=''):
"""生成整洁的名字"""
if middle:
full_name = first + ' ' + middle + ' ' + last
else:
full_name = first + ' ' + last
return full_name.title()
10.1单元测试和测试用例,可通过的测试
一个要测试的类
class AnonymousSurvey():
"""收集匿名调查问卷的答案"""
def __init__(self,question):
"""存储一个问题,并为存储答案做准备"""
self.question = question
self.responses = []
def show_question(self):
"""显示调查问卷"""
print(self.question)
def store_response(self, new_response):
"""储存单份调查答卷"""
self.responses.append(new_response)
def show_results(self):
"""显示收集到的所有答卷"""
print("Survey results:")
for response in self.responses:
print('-' + response)
11笔记说明
一边看书,一边跟着书上的例子跟着边学边敲,便于以后忘记时翻阅。
?
|