[关闭]
@ExcitedSpider 2018-01-30T02:01:05.000000Z 字数 2688 阅读 1222

Learning Python(2)

File

  1. with open('pai.txt') as file_object:
  2. contents=file_object.read()
  3. print(content.strip())
  1. with open('pai.txt') as file_object:
  2. for line in file_object:
  3. print(line.rstrip())
  1. with open('pai.txt','w') as file_object:
  2. file_object.writelines("I like pie!")

Exception

  1. first_num=input("First number:")
  2. second_num=input("Second number:")
  3. try:
  4. result=float(first_num)/float(second_num)
  5. except Exception: #ZeroDivisionError
  6. print("you can't divide by zero")
  7. else:
  8. print("Result is "+str(result))

Save data

  1. import json
  2. numbers=[2,3,4,5,6,7]
  3. numbers2=[]
  4. filename='numbers.json'
  5. with open(filename,'r+') as json_obj:
  6. json.dump(numbers,json_obj)
  7. with open(filename) as json_obj:
  8. numbers2=json.load(json_obj)
  9. print(numbers2)

Test

  1. #getname.py
  2. def get_formatted_name(first,last):
  3. """Generate a neatly formatted full name"""
  4. full_name = first+' '+last
  5. return str(full_name).title()
  1. #test.py
  2. import unittest
  3. from getname get_formatted_name
  4. class NameTestCase(unittest.TestCase):
  5. """测试"""
  6. def test_first_last_name(self):
  7. """能够正确的处理janis jpplin嘛?"""
  8. formatted_name=get_formatted_name('janis','joplin')
  9. self.assertEqual(formatted_name,'Janis Joplin')
  10. unittest.main()
method usage
assertEqual(a,b) a==b?
assertNotEqual(a,b) a!=b?
assertTrue(x) x==True?
assertFalse(x) x==False?
assertIn(item,list) if item in list?
assertNotIn(item,list) if item not in list?
  1. #survey.py
  2. class AnoumousSurvey():
  3. """匿名问卷调查"""
  4. def __init__(self,question):
  5. self.question=question
  6. self.responses=[]
  7. def show_quesiton(self):
  8. """show quesiton"""
  9. print(self.question)
  10. def store_response(self,new_response):
  11. self.responses.append(new_response)
  12. def show_results(self):
  13. print("Survey results:")
  14. for response in self.responses:
  15. print('- '+response)
  1. #test.py
  2. from survey import AnoumousSurvey
  3. import unittest
  4. class TestAS(unittest.TestCase):
  5. """test for AnoumousSurvey"""
  6. def test_store_single_response(self):
  7. """测试单个答案是否能被存储"""
  8. question="What language did you like most?"
  9. my_survey=AnoumousSurvey(question)
  10. my_survey.store_response('English')
  11. self.assertIn('English',my_survey.responses)
  12. unittest.main()

Closure

  1. def gen_counter(name):
  2. count=[0]
  3. def counter():
  4. count[0] += 1
  5. print('Hello '+name+','+str(count[0])+' access!')
  6. return counter
  7. c=gen_counter('master')
  8. c()
  9. c()
  10. c()
  11. #output:
  12. Hello master,1 access!
  13. Hello master,2 access!
  14. Hello master,3 access!
  15. #variation 'count' will only be access by counter(), so it's very safe
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注