基础知识
变量
-
变量
message = "Hello Paython world!"
- 变量名只能包含字母、数字和下划线
- 变量名不能包含空格,但可以用下划线来分隔其中的单词
- 不要将Python关键字和函数名用作变量名
- 变量名应简短又具有描述性
- 慎用小写字母L和大写字母O,因为很容易被看错成数字1和0
- 应尽量使用小写的Python变量名
字符串
-
字符串
name = "ada lovelace" print name.title() print name.upper() print name.lower() # Result: # Ada Lovelace # ADA LOVELACE # ada lovelace
-
字符串拼接
first_name = "ada" last_name = "lovelace" full_name = first_name + " " + last_name message = "Hello, " + full_name.title() + "!" print message # Hello, Ada Lovelace!
-
字符串移除开头和结尾的空字符串
favorite_language = 'python ' print favorite_language print favorite_language.rstrip() favorite_language = ' python' print favorite_language print favorite_language.strip() # 'python ' # 'python' # ' python' # 'python'
数字
-
加减乘除
print 2 + 3 # 5 print 3 - 2 # 1 print 2 * 2 # 4 print 3 / 2.0 # 1.5
-
乘方
print 3 ** 2 # 3 * 3 = 9 print 3 ** 3 # 3 * 3 * 3 = 27 print 10 ** 6 # 10 * 10 * 10 * 10 * 10 * 10 = 1000000
-
使用str()进行类型转化
age = 23 message = "Happy " + str(age) + "rd Birthday!" print message
注释
-
注释用#
# 注释 print "注释"
-
写什么注释
- 注释的主要目的是阐述代码要做什么,以及是如何做的。
Python之禅
-
Python之禅
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
列表
-
列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print bicycles # 第一个元素 print bicycles[0] print bicycles[0].title() # 使用-1访问最后一个元素 print bicycles[-1] print bicycles[-2] # ['trek', 'cannondale', 'redline', 'specialized'] # trek # Trek # specialized # redline
-
修改列表元素
# 修改列表元素 motorcycles = ['honda', 'yamaha', 'suzuki'] print motorcycles motorcycles[0] = 'ducati' print motorcycles # 添加元素 print "结尾加入awazoi" motorcycles.append('awazoi') print motorcycles # 插入列表开头 print "列表开头插入wawka" motorcycles.insert(0, 'wawka') print motorcycles # 删除元素 print "删除第一个元素" del motorcycles[0] print motorcycles # 删除最后一个元素并返回 print "删除并返回最后一个元素" popped_motorcycle = motorcycles.pop() print popped_motorcycle print motorcycles # 删除列表中任何位置的元素并返回 print "删除列表中第一个的元素,并打印出来" first_owned = motorcycles.pop(0) print first_owned print motorcycles # ['honda', 'yamaha', 'suzuki'] # ['ducati', 'yamaha', 'suzuki'] # 结尾加入awazoi # ['ducati', 'yamaha', 'suzuki', 'awazoi'] # 列表开头插入wawka # ['wawka', 'ducati', 'yamaha', 'suzuki', 'awazoi'] # 删除第一个元素 # ['ducati', 'yamaha', 'suzuki', 'awazoi'] # 删除并返回最后一个元素 # awazoi # ['ducati', 'yamaha', 'suzuki'] # 删除列表中第一个的元素,并打印出来 # ducati # ['yamaha', 'suzuki']
-
排序
# 列表排序 cars = ['bmw', 'audi', 'toyota', 'subaru'] print '排序前' print cars cars.sort() print '排序后' print cars print '反向排序' cars.sort(reverse=True) print cars print '临时排序' print sorted(cars) print sorted(cars, reverse=True) print '倒着打印' cars.reverse() print cars print '获取长度' print len(cars) # 排序前 # ['bmw', 'audi', 'toyota', 'subaru'] # 排序后 # ['audi', 'bmw', 'subaru', 'toyota'] # 反向排序 # ['toyota', 'subaru', 'bmw', 'audi'] # 临时排序 # ['audi', 'bmw', 'subaru', 'toyota'] # ['toyota', 'subaru', 'bmw', 'audi'] # 倒着打印 # ['audi', 'bmw', 'subaru', 'toyota'] # 获取长度 # 4
操作列表
-
遍历列表
magicians = ['alice', 'david', 'carolina'] print magicians print "遍历列表" for magician in magicians: print magician # ['alice', 'david', 'carolina'] # 遍历列表 # alice # david # carolina
-
数值列表
print "遍历1到4" for value in range(1, 4): print value print '数字列表' numbers = list(range(1, 15)) print numbers print '步长为2,偶数列表' even_numbers = list(range(2, 11, 2)) print even_numbers print '1~10的平方' squares = [] for value in range(1, 11): squares.append(value ** 2) print squares print '列表解析' squares = [value**2 for value in range(1, 11)] print squares # 遍历1到4 # 1 # 2 # 3 # 数字列表 # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # 步长为2,偶数列表 # [2, 4, 6, 8, 10] # 1~10的平方 # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] # 列表解析 # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
-
切片
print '指定获取列表中的元素' players = ['charles', 'martina', 'michael', 'florence', 'eli'] print players[0:3] print players[:4] print players[2:] print '遍历切片' for player in players[:3]: print player.title() # 复制列表 print '复制列表' my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] print '添加cannoli到my_foods' my_foods.append('cannoli') print 'my_foods为--' print my_foods print '\n' print 'friend_foods为--' print friend_foods # 这行不通 new_friend_foods = my_foods print 'new_friend_foods为' print new_friend_foods print 'my_foods为--' print my_foods print '添加ice cream到new_friend_foods' new_friend_foods.append('ice cream') print 'new_friend_foods为' print new_friend_foods print 'my_foods为--' print my_foods # 复制列表 # 添加cannoli到my_foods # my_foods为-- # ['pizza', 'falafel', 'carrot cake', 'cannoli'] # # # friend_foods为-- # ['pizza', 'falafel', 'carrot cake'] # new_friend_foods为 # ['pizza', 'falafel', 'carrot cake', 'cannoli'] # my_foods为-- # ['pizza', 'falafel', 'carrot cake', 'cannoli'] # 添加ice cream到new_friend_foods # new_friend_foods为 # ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream'] # my_foods为-- # ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
-
元组
# 不可变的列表被称为元组 print '元组内的元素不可改变,但可以重新定义元组' dimensions = (200, 50) print dimensions # 遍历 print '\n遍历元组' for dimension in dimensions: print dimension print '\n重新定义元组' dimensions = (400, 100) print dimensions # # 元组内的元素不可改变,但可以重新定义元组 # (200, 50) # # 遍历元组 # 200 # 50 # # 重新定义元组 # (400, 100)
if语句
-
条件
cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw': print car.upper() else: print car.title() age = 24 print '\nand全部满足条件' print age > 18 and age < 30 print age > 18 and age < 21 print '\nor连接多个条件' print age > 18 or age < 21 print age < 18 or age > 30 print '\nin包含' print 'audi' in cars print 'benz' in cars print '\nnot in 不包含' print 'audi' not in cars print 'benz' not in cars # Audi # BMW # Subaru # Toyota # # and全部满足条件 # True # False # # or连接多个条件 # True # False # # in包含 # True # False # # not in 不包含 # False # True
-
if语句
age = 24 if age > 30: print '大于30岁的成年人' elif age < 18: print '小于18岁的未成年人' else: print '大于18岁,小于30岁的青年' requested_toppings = [] if requested_toppings: print '\n列表内容为' print requested_toppings else: print '\n列表为空' available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print "\nAdding " + requested_topping + "." else: print "Sorry, we don't have " + requested_topping + "." # 大于18岁,小于30岁的青年 # # 列表为空 # # Adding mushrooms. # Sorry, we don't have french fries. # # Adding extra cheese.
字典
-
字典
print '字典' alien_0 = {'color': 'green', 'points': 5} print alien_0 print alien_0['color'] print alien_0['points'] print '\n添加键值对' alien_0['x_position'] = 0 alien_0['y_position'] = 25 print alien_0 print '\n删除键值对' del alien_0['points'] print alien_0 # 字典 # {'color': 'green', 'points': 5} # green # 5 # # 添加键值对 # {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25} # # 删除键值对 # {'color': 'green', 'x_position': 0, 'y_position': 25}
-
遍历字典
user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi' } for key, value in user_0.items(): print "\nKey: " + key print "Value: " + value # Key: username # Value: efermi # # Key: last # Value: fermi # # Key: first # Value: enrico # print '\n遍历所有的key' for key in user_0.keys(): print key.title() # 遍历所有的key # Username # Last # First # print '\n排序key' print sorted(user_0.keys()) print '\n所有的值' print user_0.values() # 排序key # ['first', 'last', 'username'] # # 所有的值 # ['efermi', 'fermi', 'enrico'] # favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } print '\n没有重复元素的集合' print set(favorite_languages.values()) # 没有重复元素的集合 # set(['python', 'c', 'ruby'])
用户输入和while循环
-
用户输入
message = input("请输入英文内容 >>>> ") print '\n打印输入的内容如下' print str(message)
-
while循环
current_number = 1 while current_number <= 5: print current_number current_number += 1 while True: number = input('\n输入4结束,输入6跳过:') if str(number) == '4': break elif str(number) == '6': continue else: print '输入的值为' + str(number)
函数
-
函数
def greet_user(language='Python'): """文档字符串的注释,描述函数是做什么的""" print "人生苦短,我用" + str(language) greet_user('Python') print '\n关键字实参' greet_user(language='Java') print "\n使用参数默认值" greet_user() # 人生苦短,我用Python # # 关键字实参 # 人生苦短,我用Java # # 使用参数默认值 # 人生苦短,我用Python def describe_pet(pet_name, animal_type='dog'): """显示宠物的信息""" print "\nI have a " + animal_type + "." print "My " + animal_type + "'s name is " + pet_name.title() + "." describe_pet('willie') describe_pet(pet_name='willie') describe_pet('harry', 'hamster') describe_pet(pet_name='harry', animal_type='hamster') describe_pet(animal_type='hamster', pet_name='harry') # # I have a dog. # My dog's name is Willie. # # I have a dog. # My dog's name is Willie. # # I have a hamster. # My hamster's name is Harry. # # I have a hamster. # My hamster's name is Harry. # # I have a hamster. # My hamster's name is Harry. print '\n带返回值的函数' def get_formatted_name(first_name, last_name): """返回姓名""" full_name = first_name + ' ' + last_name return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print musician print '\n返回字典' def build_person(first_name, last_name, age=''): person = {'first': first_name, 'last': last_name} if age: person['age'] = age return person print build_person('jimi', 'hendrix', 27) # # 带返回值的函数 # Jimi Hendrix # # 返回字典 # {'age': 27, 'last': 'hendrix', 'first': 'jimi'}
-
传递参数
def print_models(unprinted_designs, complete_models): unprinted_designs.pop() print unprinted_designs print complete_models list1 = [1, 2, 3, 4, 5] list2 = ['a', 'b', 'c', 'd'] print '原始参数' print list1 print list2 print '\n调用函数,禁止函数修改参数,传入参数副本' print_models(list1[:], list2) print '\n原始参数' print list1 print list2 # # 原始参数 # [1, 2, 3, 4, 5] # ['a', 'b', 'c', 'd'] # # 调用函数,禁止函数修改参数,传入参数副本 # [1, 2, 3, 4] # ['a', 'b', 'c', 'd'] # # 原始参数 # [1, 2, 3, 4, 5] # ['a', 'b', 'c', 'd'] print '\n调用函数,传入参数本身,修改参数内容' print_models(list1, list2) print '\n原始参数' print list1 print list2 # # 调用函数,传入参数本身,修改参数内容 # [1, 2, 3, 4] # ['a', 'b', 'c', 'd'] # # 原始参数 # [1, 2, 3, 4] # ['a', 'b', 'c', 'd'] print '\n任意个参数' def make_pizza(*toppings): print toppings make_pizza('mushrooms', 'green peppers') # # 任意个参数 # ('mushrooms', 'green peppers') print '\n任意个自定义的参数' def build_profile(first, last, **user_info): print user_info profile = {} profile['fist_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile print build_profile('albert', 'einstein', location='princeton', field='physics') # # 任意个自定义的参数 # {'field': 'physics', 'location': 'princeton'} # {'fist_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
-
模块化参数
# 导入 import module_name # 调用 module_name.function_name()
-
导入特定函数
from module_name import function_name from module_name import function_0, function_1, function_2
-
给函数指定别名
from module_name import function_name as fn
from pizza import make_pizza as mp mp(16, 'mushrooms)
-
给模块指定别名
import module_name as mn
import pizza as p p.make_pizza(16, 'mushrooms')
-
编写函数指南
-
给函数指定描述性名称,且只在其中使用小写字母和下划线
-
每个函数都应包含简要阐述其功能的注释,注释应紧跟在函数定义后面,并采用文档字符串格式
-
给形参指定默认值时,等号两边不要有空格
def function_name(parameter_0, parameter_1='default value')
-
类
-
小狗
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." print "使用类" my_dog = Dog('willie', 6) my_dog.sit()
-
汽车
class Car(object): """汽车""" 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 "汽车行驶公里数为" + str(self.odometer_reading) + " 。" def update_odometer(self, mileage): """ 将公里数设置为制定的值 禁止公里数往回调 """ if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print "你不能往回调公里数" def increment_odometer(self, miles): """增加公里数""" self.odometer_reading += miles print '汽车信息' my_used_car = Car('audi', 'A4L', 2018) my_used_car.read_odometer() print '\n汽车行驶了' my_used_car.update_odometer(23500) my_used_car.read_odometer() print '\n汽车截止行驶了' my_used_car.increment_odometer(100) my_used_car.read_odometer() # 汽车信息 # 汽车行驶公里数为0 。 # # 汽车行驶了 # 汽车行驶公里数为23500 。 # # 汽车截止行驶了 # 汽车行驶公里数为23600 。
-
继承
from car import Car class ElectricCar(Car): """电动汽车""" def __init__(self, make, model, year): """初始化父类的属性""" super(ElectricCar, self).__init__(make, model, year)
异常
-
异常
def count_words(filename): """计算文件内包含多少个词""" try: with open(filename) as f_obj: contents = f_obj.read() except Exception: print "没有找到" + filename + "文件" else: """就散包含多少个词""" words = contents.split() num_words = len(words) print filename + "文件包含有" + str(num_words) + "个词" filename = 'alice.txt' count_words(filename)
测试代码
-
测试
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): """测试""" def test_first_last_name(self): """能够正确返回首字母大写的名字""" formatted_name = get_formatted_name('janis', 'joplin') self.assertEqual(formatted_name, 'Janis Joplin') unittest.main()
-
断言
方法 用途 assertEqual(a, b) 核实 a == b assertNotEqual(a, b) 核实 a != b assertTrue(x) 核实x为True assertFalse(x) 核实x为False assertIn(item, list) 核实item在list中 assertNotIn(item, list) 核实item不在list中