# 检查是否相等 car = 'Bwt' car == 'bwt'# 考虑大小写 car.lower() == 'bwt'#不考虑大小写
# 检查是否不相等 car = 'Bwt' if(car != 'Audio'): print 'error'
# 比较数字 > < >= <= == # 多个条件检查 # and :与关系 # or:或关系
# 检查特定值是否包含在列表中,可以用in实现 bytime = ('year','month','day') bytimes = ['yy','mm','dd'] 'years' in bytime 'years' in bytimes
# 检查特定值是否不包含在列表中,not in bytime = ('year','month','day') 'years' not in bytime
7.2 if 语句格式
# 最简单的if if conditional_test: do something
# 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 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 inset(intersts.values()): print('\nvalue: '+value)
8.8 嵌套
将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
# 字典列表 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)
# 使用用户输入来填充字典 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 函数应用
# 所有补考的学员考完后移动到通过人员列表中 defhaveexam(all,passstus): while all: current = all.pop() print (current + 'is having the exam !') passstus.append(current)
defpassstu(psslist): for stu in psslist: print (stu + 'has pass the exam !')
# 传递任意数量实参 # *fruits,创建一个名为fruits的空元组,,并将收到的所有值都封装到这个元组中,将实参封装到一个元组中,即便 函数只收到一个值也如此 defshopping(*fruits): for fruit in fruits: print ('add ' + fruit + 'to order list')
shopping('apple','orange','banana')
# 结合使用位置实参和任意数量实参 defshopping(counts ,*fruits): print ('I have '+counts + ' yuan .I can buy : ') for fruit in fruits: print (fruit)
shopping('10','apple','orange','banana')
# 使用任意数量的关键字参数 defget_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 使用类和实例
classDog(): def__init__(self,name,age): self.name = name self.age = age
defsit(self): print (self.name + 'is sitting')
defroll_over(self): print (self.name + 'is rolling ,and its age is '+ str(self.age))
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)
try: print(5/0) except ZeroDivisionError: print ('you can not devide by zero')
14.2 使用异常避免崩溃
# 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 ase: print(e) else: print (result)
14.3 处理 FileNotFoundErro
filepath = 'D:/pythontest/test.txt' try: with open(filepath) asfile: contents = file.read() except FileNotFoundError: print(filepath+' not exsit') else: print(contents)
14.4 分析文本
filepath = 'D:/pythontest/write.txt' try: with open(filepath) asfile: contents = file.read() except Exception as e: print('something error,the detail intois : '+e) else: words = contents.split(' ') words_len = len(words) print (words) print('total num is :'+ str(words_len))
14.5 使用多个文件
def count_book(filepath): try: withopen(filepath) asfile: 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)
# 保存和读取用户生成的数据 importjson username = input('tell me your name and i will remember it :') filepath = 'D:/pythontest/username.txt' withopen(filepath,'w') as file_obj: json.dump(username,file_obj) print('i have remember your name,'+username)
importjson filepath = 'D:/pythontest/username.txt' try: withopen(filepath) as file_obj: username = json.load(file_obj) print('welcome bace '+ username) except FileNotFoundError: withopen(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)