20170922

来源:互联网 发布:免费翻墙软件for mac 编辑:程序博客网 时间:2024/06/04 00:25
#20170922#number = 0#while number < 10:#   number += 1#   if number % 2 ==0:#       continue#   print(number-1)#unconfirm_users = ['alice','brian','candace']#confirm_users = []#while unconfirm_users:#   current_user = unconfirm_users.pop()#   print('verifying user:'+current_user.title())#   confirm_users.append(current_user)#for confirm_user in confirm_users:#   print(confirm_user.title())#删除包含特定值的所有列表元素#pets = ['dog','cat','dog','gofish','cat','rabbit','cat']#print(pets)#while 'cat' in pets:#   pets.remove('cat')#~ print(pets)#~ responses = {}#~ polling_active = True#~ while polling_active:    #~ name = input('\nWhat is your name?')    #~ response = input('which moutain 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 + '.')#~ 定义函数#~ def greet_user(username):    #~ """显示简单的问候语"""    #~ print('hello!'+username.title())#~ greet_user("liumeng")#~ 位置实参:基于实参顺序对应到函数中#~ 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('hamster','harry') #~ describe_pet(pet_name = "harry")#~ describe_pet()#~ def get_formatted_name(frist_name,last_name,middle_name=''):    #~ if middle_name:        #~ full_name = frist_name+" "+middle_name+" "+last_name    #~ else:        #~ full_name = frist_name+" "+last_name    #~ return full_name.title()#~ musician = get_formatted_name('jimi','hendrix')#~ print(musician)#~ musician = get_formatted_name('jimi','hendrix',"lee")#~ 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('jimi','hendrix',age = 27)#~ print(musician)#~ while True:    #~ print('\nPlease tell me your name:')    #~ print("(enter 'q' any time to quit)")    #~ f_name = input("First name :")    #~ if f_name =='q':        #~ break    #~ l_name = input("Last name :")    #~ if l_name =='q':        #~ break    #~ 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 = ['hahaha','try','margot']#~ greet_users(usernames)#~ unprinted_designs = ['iphone case','rabot pendant','dodecahedron']#~ completed_models = []#~ while unprinted_designs:    #~ current_design = unprinted_designs.pop()    #~ print("printing model:"+current_design)    #~ completed_models.append(current_design)#~ for completed_model in completed_models:    #~ print(completed_model)#~ def print_models(unprinted_designs,completed_models):    #~ while unprinted_designs:        #~ current_design = unprinted_designs.pop()        #~ print("printing model:"+current_design)        #~ completed_models.append(current_design)#~ def show_completed_models(completed_models):    #~ for completed_model in completed_models:        #~ print(completed_model)#~ print_models(unprinted_designs[:],completed_models)#~ show_completed_models(completed_models)#~ print('dddddddddddddddddddd')#~ show_completed_models(unprinted_designs)#~ def make_pizza(size,*toppings):    #~ print(toppings)    #~ print("\nMaking a "+str(size)+" pizza with the following toppings:")    #~ for topping in toppings:        #~ print("- " + topping)#~ print('1')#~ make_pizza(16,'1','2','3')#~ print(1)#~ 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('albert','einstein',                              #~ location = 'princeton',                              #~ field = 'physics'    #~ )#~ print(user_profile)#~ from pizza import make_pizza as mp#~ make_pizza(16, 'pepperoni')#~ mp(16, 'pepperoni')#~ class Dog():    #~ def __init__(self, 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.name.title())#~ my_dog.sit()#~ class Car():    #~ def __init__(self,make,model,year):        #~ self.make = make        #~ self.model = model        #~ self.year = year        #~ self.odometer_reading = 0    #~ def get_descroptie_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#~ my_new_car = Car('audi','a4',2016) #~ print(my_new_car.get_descroptie_name())#~ print(my_new_car.read_odometer())#~ my_used_car = Car('subaru','outback',2013)#~ print(my_used_car.get_descroptie_name())#~ my_used_car.update_odometer(23500)#~ my_used_car.read_odometer()#~ my_used_car.increment_odometer(100)#~ my_used_car.read_odometer()#~ class ElectricCar(Car):    #~ def __init__(self,make,mode,year):        #~ super().__init__(make,mode,year)        #~ self.battery = Battery()#~ class Battery():    #~ def __init__(self, battery_size=70):        #~ self.battery_size = battery_size    #~ def decribe_battery(self):        #~ print("this car has a "+str(self.battery_size)+"-kWh battery.")    #~ def get_range(self):        #~ if self.battery_size == 70:            #~ range = 240        #~ elif self.battery_size == 80:            #~ range = 270        #~ message = "This car can go approximately " + str(range)        #~ message += " miles on a full charge."        #~ print(message)#~ my_tesla = ElectricCar('tesla','model s',2016)#~ print(my_tesla.get_descroptie_name())#~ my_tesla.battery.decribe_battery()#~ my_tesla.battery.get_range()#~ from car import Car#~ my_new_car = Car('audi','a4',2016)#~ print(my_new_car.get_descriptive_name())#~ my_new_car.odometer_reading = 23#~ my_new_car.read_odometer()#~ from car import ElectricCar#~ my_tesla = ElectricCar('tesla','model s',2016)#~ print(my_tesla.get_descriptive_name())#关键字with在不再需要访问文件后将其关闭,#with open('pi_digits.txt') as file_object:#   contents = file_object.read()#   print(contents)#逐行读取#~ filename = 'pi_digits.txt'#~ with open(filename) as file_object:    #~ for line in file_object:        #~ print(line.rstrip())#创建一个包含文件各行内容的列表    #~ lines = file_object.readlines()#~ for line in lines:    #~ print(line.rstrip())    #~ pi_string = ''    #~ for line in lines:        #~ pi_string += line.rstrip()    #~ print(pi_string)    #~ print(len(pi_string))#~ filename = 'pi_digits.txt'#~ with open(filename,'a') as file_object:    #~ file_object.write("I love programing.\n")    #~ file_object.write("I love programing.")#~ print(5/0)#~ try:    #~ answer = 5/0#~ except ZeroDivisionError:    #~ print("You can't divide by 0!")#~ 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)#~ title = "Alice in Wonderland"#~ lists = title.split()#~ print(lists)#~ filename = 'pi_digits.txt'#~ with open(filename,'r') as f:    #~ number = len(f.read())    #~ print(number)#~ 存储数据#~ 很多程序要求用户输入某种信息,如让永不存储游戏首选选项#~ 函数json.dump()和json.load(),要存储的书籍以及可用户存储数据的文件对象#~ import json#~ numbers = [2,3,5,7,11,13]#~ filename = 'numbers.json'#~ with open(filename,'w') as f_obj:    #~ json.dump(numbers,f_obj)#~ filename = 'numbers.json'#~ with open(filename) as f_obj:    #~ numbers = json.load(f_obj)#~ print(numbers)#~ 保存和读取用户生成的数据#~ username = input("what is your name?")#~ filename = "username.json"#~ with open(filename,'w') as f_obj:    #~ json.dump(username,f_obj)    #~ print("we'll remember you when you come back,"+username+"!")#~ filename= "username.json"#~ with open(filename) as f_obj:    #~ username = json.load(f_obj)    #~ print("welcome back, "+username+"!")#~ class AnonymousSurvey():    #~ def __init__(self,question):        #~ self.question = question        #~ self.responses = []    #~ def show_question(self):        #~ print(question)    #~ def store_response(self,new_response):        #~ self.responses.append(new_response)    #~ def show_result(self):        #~ print("Survey results:")        #~ for response in self.responses:            #~ print('- '+response)#~ question = 'what languge did you first learn to speak?'#~ my_survey = AnonymousSurvey(question)#~ my_survey.show_question()#~ print("Enter 'q' at any thim to quit.\n")#~ while True:    #~ response = input("language:")    #~ if response == 'q':        #~ break    #~ my_survey.store_response(response)#~ print('\nThank you to everyone who participated in the survey!')#~ my_survey.show_result()#~ from io import StringIO#~ f = StringIO()#~ a = f.write("hello")#~ print(a)#~ f.write(' ')#~ f.write('world!')#~ print(f.getvalue())#~ from io import StringIO#~ f = StringIO('Hello!\nHi\nGoodbye!')#~ while True:    #~ s = f.readline()    #~ if s=='':        #~ break    #~ print(s.strip())#~ from io import BytesIO#~ f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')#~ print(f.read())#~ import os#~ print(os.name())#~ print(os.uname())#~ import os#~ print(os.environ)#~ 查看当前目录的绝对路径#~ import os#~ print(os.path.abspath('.'))#~ 在某个目录下创建一个新目录,首先吧新目录的完整路径表示出来#~ print(os.path.join(os.path.abspath('.'),'testdir'))#~ 然后创建一个目录#~ print(os.mkdir("os.path.join(os.path.abspath('.'),'testdir')"))#~ from collections import Iterable#~ print(isinstance([],Iterable))#~ print(isinstance({},Iterable))#~ print(isinstance('abc',Iterable))#~ print(isinstance(100,Iterable))
原创粉丝点击