《Python程式設計》第十一章部分課後練習題

Zetrue_Li發表於2018-04-11

#11-1 城市和國家:

程式碼:

#11-1 城市和國家

def city_country(city, country):
	return city.title() + ', ' + country.title()
	
import unittest

class TestCites(unittest.TestCase):

	def test_city_country(self):
		pair = city_country('santiago', 'chile')
		self.assertEqual(pair, 'Santiago, Chile')
		
unittest.main()

輸出:pass


#11-2 人口數量:

Part-1:

#11-2 人口數量

def city_country(city, country, population):
	return city.title() + ', ' + country.title() + ' - ' + 'population ' + population
	
import unittest

class TestCites(unittest.TestCase):

	def test_city_country(self):
		pair = city_country('santiago', 'chile')
		self.assertEqual(pair, 'Santiago, Chile')
		
unittest.main()

Part-2:

#11-2 人口數量

def city_country(city, country, population = -1):
	if(population==-1):
		return city.title() + ', ' + country.title()
	else:
		return city.title() + ', ' + country.title() + ' - ' + 'population ' + population
	
import unittest

class TestCites(unittest.TestCase):

	def test_city_country(self):
		pair = city_country('santiago', 'chile')
		self.assertEqual(pair, 'Santiago, Chile')
		
unittest.main()

Part-3:

#11-2 人口數量

def city_country(city, country, population = -1):
	if(population==-1):
		return city.title() + ', ' + country.title()
	else:
		return city.title() + ', ' + country.title() + ' - ' + 'population ' + str(population)
	
import unittest

class TestCites(unittest.TestCase):
	
	def test_city_country(self):
		pair = city_country('santiago', 'chile')
		self.assertEqual(pair, 'Santiago, Chile')
		
	def test_city_country_population(self):
		pair = city_country('santiago', 'chile', 5000000)
		self.assertEqual(pair, 'Santiago, Chile - population 5000000')
		
unittest.main()

輸出:pass


#11-3 僱員:

程式碼:

#11-3 僱員

import unittest

class Employee():
	"""Create A class named Employee who has the properties of name and salary"""
	
	def __init__(self, last_name, first_name, annual_salary):
		self.last_name = last_name
		self.first_name = first_name
		self.annual_salary = annual_salary
		
	def give_raise(self, rais = 50000):
		self.annual_salary += rais
		
class TestEmpolees(unittest.TestCase):
	
	def setUp(self):
		self.employee = Employee('James', 'Harden', 1000000)
	
	def test_give_default_raise(self):
		self.employee.give_raise()
		self.assertEqual(self.employee.annual_salary, 1050000)
	
	def test_give_custom_raise(self):
		self.employee.give_raise(10000)
		self.assertEqual(self.employee.annual_salary, 1010000)

unittest.main()

輸出:

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

相關文章