10-11:喜欢的数字:
import json
filename = 'number.json'
number = input("What is your favourite number?")
with open(filename,'w') as f_obj:
json.dump(number,f_obj)
with open(filename) as f_obj:
number = json.load(f_obj)
print("I know your favorite number is "+number)
What is your favourite number?6
I know your favorite number is 6
10-12记住喜欢的数字:
import json
filename = 'number.json'
try:
with open(filename) as f_obj:
usernumber = json.load(f_obj)
except FileNotFoundError:
usernumber = input("What is your favourite number?")
with open(filename,'w') as f_obj:
json.dump(usernumber,f_obj)
print("Now we store your favorite number "+usernumber)
else:
print("I know your favorite number is "+usernumber)
What is your favourite number?8
Now we store your favorite number 8
I know your favorite number is 8
11-1 城市和国家:
import unittest
from city_functions import get_city_country
class City_Country_Case(unittest.TestCase):
def test_city_country(self):
formatted_name = get_city_country('beijing','chinese')
self.assertEqual(formatted_name,'Beijing Chinese')
unittest.main()
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
11-3 雇员:
import unittest
from employee import Employee
class TestEmployee(unittest.TestCase):
def setUp(self):
self.myself = Employee('Steph','Curry')
def test_give_default_raise(self):
self.assertEqual(self.myself.salary + 5000,self.myself.give_raise())
def test_give_custom_raise(self):
self.assertNotEqual(self.myself.salary + 1000,self.myself.give_raise())
unittest.main()
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK