開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 5(Making Choices)、Exercises 9、10、11の解答を求めてみる。
コード
Python 3
#!/usr/bin/env python3 from unittest import TestCase, main from test.support import captured_stdout class MyTestCase(TestCase): def setUp(self): pass def tearDown(self): pass def test9(self): ph = 2 with captured_stdout() as stdout: for ph in [2, 3, 7]: if ph < 3.0: print(f'{ph} is VERY acidic! Be careful.') elif ph < 7.0: print(f'{ph} is acidic.') s = '''2 is VERY acidic! Be careful. 3 is acidic. ''' self.assertEqual(stdout.getvalue(), s) def test10a(self): ph = 6.4 with captured_stdout() as stdout: if ph < 7.0: print("It's acidic!") elif ph < 4.0: print("It's a strong acid!") self.assertEqual(stdout.getvalue(), "It's acidic!\n") def test10b(self): ph = 3.6 with captured_stdout() as stdout: if ph < 7.0: print("It's acidic!") elif ph < 4.0: print("It's a strong acid!") self.assertEqual(stdout.getvalue(), "It's acidic!\n") def test10c(self): ph = 3.6 with captured_stdout() as stdout: if ph < 7.0: print("It's acidic!") if ph < 4.0: print("It's a strong acid!") s = '''It's acidic! It's a strong acid! ''' self.assertEqual(stdout.getvalue(), s) def test11(self): with captured_stdout() as stdout: for age in [44, 45]: is_young = age < 45 for bmi in [21, 22]: is_heavy = bmi >= 22.0 if is_young: if is_heavy: risk = 'medium' else: risk = 'low' else: if is_heavy: risk = 'high' else: risk = 'medium' print(risk) output = '''low medium medium high ''' self.assertEqual(stdout.getvalue(), output) if __name__ == '__main__': main()
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./sample9.py -v test10a (__main__.MyTestCase) ... ok test10b (__main__.MyTestCase) ... ok test10c (__main__.MyTestCase) ... ok test11 (__main__.MyTestCase) ... ok test9 (__main__.MyTestCase) ... ok ---------------------------------------------------------------------- Ran 5 tests in 0.001s OK $
0 コメント:
コメントを投稿