#要使用下面这种语法,首先指定一个描述性的列表名,如squares;然后,指定一个左方括号,并定义一个表达式,用 于生成你要存储到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来,编写一个for循环,用于给 表达式提供值,再加上右方括号 squares = [value**2 for value in range(1,11)]
# if-else age = 17 if age > 18: print '未成年' else: print '已成年'
# if-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.")
# 使用多个elif age = 12 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5 print("Your admission cost is $" + str(price) + ".")
# 检查特殊元素 fruits = ['tomato','apple','banana','orange'] for fruit in fruits: if fruit == 'apple': print 'sorry ,we are out of '+ fruit + 'now' else: print 'buy'+ fruit
# 确定列表不是空的 fruits = [] if fruits : for fruit in fruits: print 'buy'+ fruit else: print 'buy nothing'
# 使用多个列表 avilable_fruit = ['apple ','banana','orange'] buy_fruit= ['tomato','apple'] for buy in buy_fruit: if buy in avilable_fruit: print ('buy '+buy) else: print ('sorry ,we are out of '+ buy + 'now')
#遍历所有键值对 stu={'name':'zhangsan','age':'18','class':'test'} for key,value in stu.items(): print('\nkey: '+key) print('value: '+value)
# 遍历所有键 stu={'name':'zhangsan','age':18,'class':'test'} for key in stu.keys(): print('\nkey: '+key)
# 遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for key in stu.keys():替换为for key in stu:, 输出将不变。
# 方法keys()并非只能用于遍历,实际上,它返回一个列表,其中包含字典中的所有键 if 'class' not in stu.keys(): print(stu['name']+'已经毕业')
# 按顺序遍历字典中所有键 stu={'name':'zhangsan','age':18,'class':'test'} for key in sorted(stu.keys()): print('\nkey: '+key)
# 遍历字典中的所有值 intersts={'张珊':'sing','李思':'dance','王武':'sing','赵流':'write'} for value in intersts.values(): print('\nvalue: '+value)
# 通过对包含重复元素的列表调用set(),可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合 intersts={'张珊':'sing','李思':'dance','王武':'sing','赵流':'write'} for value in set(intersts.values()): print('\nvalue: '+value)
# 字典列表 stu_1 = {'name':'zhangsan','age':'18','grade':'72'} stu_2 = {'name':'lisi','age':'20','grade':'90'} stu_3 = {'name':'wangwu','age':'17','grade':'80'} stu_list = [stu_1,stu_2,stu_3] for stu in stu_list: print (stu)
aliens = [] # 创建30个绿色的外星人 for alien_number in range(30): new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} aliens.append(new_alien) # 显示前五个外星人 for alien in aliens[:5]: print(alien) print("...")
# 显示创建了多少个外星人 print("Total number of aliens: " + str(len(aliens)))
# 将前三个外星人修改为黄色的、速度为中等且值10个点 for alien in range[:3]: if alien['color'] == 'green': alien['color']= 'red' alien['points'] = 10 alien['speed']='medium' print alien
# 在字典中存储列表 goods ={'zhangsan':['sing','dance'],'lisi':['look book','have foods'],'wangwu':['write','sports']} for name,good in goods.items(): print (name + "'s goods are:") for g in good: print (g)
# 在字典中存储字典 grades = {'zhangsan':{'english':'80','math':'90','chinese':'72'},'lisi':{'english':'82','math':'70','chinese':'92'}} for name,grade in grades.items(): print (name + "'s grades are :") for sub,score in grade.items(): print (sub + ":" + score)
# 删除列表中包含的某元素(全删,并不是只删除第一个) test= ['dog','cat','pig','dog','mouse','dog'] while 'dog' in test: test.remove('dog') print (test)
# 使用用户输入来填充字典 response = {} flag = True while flag: name = input('what is your name ?') res = input('what is intersting ?') response[name] = res ismore = input('do you want to others ,yes or no ? ') if ismore == 'no': flag = False print (response)
11 函数
11.1 函数应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 所有补考的学员考完后移动到通过人员列表中 def haveexam(all,passstus): while all: current = all.pop() print (current + 'is having the exam !') passstus.append(current)
def passstu(psslist): for stu in psslist: print (stu + 'has pass the exam !')
# 传递任意数量实参 # *fruits,创建一个名为fruits的空元组,,并将收到的所有值都封装到这个元组中,将实参封装到一个元组中,即便 函数只收到一个值也如此 def shopping(*fruits): for fruit in fruits: print ('add ' + fruit + 'to order list')
shopping('apple','orange','banana')
# 结合使用位置实参和任意数量实参 def shopping(counts ,*fruits): print ('I have '+counts + ' yuan .I can buy : ') for fruit in fruits: print (fruit)
shopping('10','apple','orange','banana')
1 2 3 4 5 6 7 8 9 10 11
# 使用任意数量的关键字参数 def get_user_info(firname,lastname,**otherinfo): user_info = {} user_info['firstnam']= firname user_info['lastname']= lastname for key,value in otherinfo.items(): user_info[key]= value return user_info
① 导入整个模块
创建test.py文件,import test
② 导入特定的函数
from module_name import function_name
from module_name import function_0, function_1, function_2
③ 使用as给函数指定别名
from module_name import function_name as fn
④ 使用 as 给模块指定别名
import module_name as mn
⑤ 导入模块中的所有函数
from module_name import *
12 类
12.1 使用类和实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Dog(): def __init__(self,name,age): self.name = name self.age = age
def sit(self): print (self.name + 'is sitting')
def roll_over(self): print (self.name + 'is rolling ,and its age is '+ str(self.age))
dog = Dog('jack',18) dog.sit() dog.roll_over()
# 在Python 2.7中创建类时,需要做细微的修改——在括号内包含单词object class ClassName(object):
from collections import OrderedDict favarite_fruit = OrderedDict() favarite_fruit['xiaodong']='apple' favarite_fruit['xiaoxi']='pear' favarite_fruit['xiaonan']='banana' favarite_fruit['xiaobei']='orange' for name,fruit in favarite_fruit.items(): print(name + "'s favarite fruit is " + fruit)
13 文件
13.1 读取整个文件
1 2 3 4 5 6 7 8 9 10
# open()要以任何方式使用文件都得先打开文件,哪怕仅仅是打印其内容 # 关键字with在不再需要访问文件后将其关闭 # 在文件路径中使用反斜杠(\)而不是斜杠(/) with open ('D:/pythontest/pi_digits.txt') as file: # 读取文件全部内容 contents = file.read() # read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。 print (contents) # 要删除多出来的空行,可在print语句中使用rstrip(): print (contents.rstrip())
13.2 逐行读取
1 2 3 4
filepath= 'D:/pythontest/pi_digits.txt' with open(filepath) as file: for line in file: print (line.rstrip())
13.3 创建一个包含文件各行内容的列表
1 2 3 4 5 6 7
filepath= 'D:/pythontest/pi_digits.txt' with open(filepath) as file: # 从文件中读取每一行,并将其存储在一个列表中 lines = file.readlines()
for line in lines: print (line)
13.4 使用文件内容
1 2 3 4 5 6 7 8 9
filepath= 'D:/pythontest/pi_digits.txt' with open(filepath) as file: # 从文件中读取每一行,并将其存储在一个列表中 lines = file.readlines() pi= '' for line in lines: pi += line.strip() print (pi) print(len(pi))
13.5 包含一百万位的大型文件
1 2 3 4 5 6 7 8 9 10 11
filepath= 'D:/pythontest/pi_digits.txt' with open(filepath) as file: # 从文件中读取每一行,并将其存储在一个列表中 lines = file.readlines() pi= '' for line in lines: pi += line.strip()
# 保留10位 print (pi[:10]+'...')
13.6 写入空文件
1 2 3 4 5
filepath= 'D:/pythontest/write.txt' # 已写入方式打开文件 with open(filepath,'w') as file: # 这种方式写入文件会直接覆盖掉文件原有内容,并不是追加写 file.write('test')
13.7 写入多行
1 2 3 4 5 6 7
filepath= 'D:/pythontest/write.txt' # 已写入方式打开文件 filepath= 'D:/pythontest/write.txt' with open(filepath,'w') as file: # 这种方式写入文件会直接覆盖掉文件原有内容,并不是追加写 file.write('line one \n') file.write('line two \n')
13.8 追加写
1 2 3 4 5
filepath= 'D:/pythontest/write.txt' with open(filepath,'a') as file: # 这种方式写入文件会直接覆盖掉文件原有内容,并不是追加写 file.write('line three \n') file.write('line four\n')
14 异常
14.1 处理 ZeroDivisionError 异常
1 2 3 4
try: print(5/0) except ZeroDivisionError: print ('you can not devide by zero')
14.2 使用异常避免崩溃
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# try-except-else工作原理:只有可能引发异常的代码才需要放在try语句中,仅在try代码块成功执行时才需要运行的 代码应放在else代码块中。except代码块指示try代码块运行出现了异常该怎么办。 print('give me two number and i will tell you the division result to you') print("press 'q' to quit")
while True: fir_num = input('the first number') if fir_num == 'q': break sec_num = input('the second number') if sec_num == 'q': break try: result = int(fir_num)/int(sec_num) except Exception as e: print(e) else: print (result)
14.3 处理 FileNotFoundErro
1 2 3 4 5 6 7 8
filepath = 'D:/pythontest/test.txt' try: with open(filepath) as file: contents = file.read() except FileNotFoundError: print(filepath+' not exsit') else: print(contents)
14.4 分析文本
1 2 3 4 5 6 7 8 9 10 11
filepath = 'D:/pythontest/write.txt' try: with open(filepath) as file: contents = file.read() except Exception as e: print('something error,the detail into is : '+e) else: words = contents.split(' ') words_len = len(words) print (words) print('total num is :'+ str(words_len))
14.5 使用多个文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def count_book(filepath): try: with open(filepath) as file: contents = file.read() except Exception as e: print( e) else: words = contents words_len = len(words) print (words) print( 'total num is :' + str(words_len))
books = ['D:/pythontest/write.txt' ,'D:/pythontest/1.txt' ,'D:/pythontest/2.txt','D:/pythontest/3.txt'] for book in books: count_book(book)
# json.dump(),将数字列表存储到json文件中 import json nums = [1,2,3,4,5] file = 'D:/pythontest/3.txt' with open(file,'w') as file_obj: json.dump(nums,file_obj)
# json.load(),将列表读取到内存 import json filepath = 'D:/pythontest/3.txt' with open(filepath) as file_obj: nums = json.load(file_obj) print (nums)
# 保存和读取用户生成的数据 import json username = input('tell me your name and i will remember it :') filepath = 'D:/pythontest/username.txt' with open(filepath,'w') as file_obj: json.dump(username,file_obj) print('i have remember your name,'+username)
import json filepath = 'D:/pythontest/username.txt' try: with open(filepath) as file_obj: username = json.load(file_obj) print('welcome bace '+ username) except FileNotFoundError: with open(filepath,'w') as file_obj: username = input('tell me your name and i will remember it :') json.dump(username,file_obj) print('i have remember your name,'+username)