I719 Fundamentals of Python/lecture2

From ICO wiki
Revision as of 11:18, 10 February 2017 by Eroman (talk | contribs) (Created page with "= Lecture 2 = == Importing from files == * imported files get executed * python needs a file name '''init'''.py in the directory ofr the file to import it * '''init'''.py ge...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Lecture 2

Importing from files

  • imported files get executed
  • python needs a file name init.py in the directory ofr the file to import it
  • init.py get executed when something within the directory is imported
  • to not execute on import, put code within a if statement like:
if __name__ == "__main__":
  • For development and debugging, it is very useful to import thing into an interactive python shell

Unittests

import unittest

HELLO_WORLD = 'hello world'

class HelloTests(unittest.TestCase):
    def test_string_correct(self):
        self.assertEqual(HELLO_WORLD, 'hello world')

def main():
    print(HELLO_WORLD)

if __name__ == "__main__":
    main()

Running Unittest

python3 -m unittest helloprinter.py

Task 1

Make FizzBuzz testable Make a function that return Fizz if divisible by 3, buzz if divisible by 5, FizzBuzz if divisible by both 3 and 5, and the returns the number if niether is met. And then write tests for these cases

Solution

import unittest

def fizz_buzz(i):
    if i % 15 == 0:
        return 'FizzBuzz'
    elif i % 3 == 0:
        return 'Fizz'
    elif i % 5 == 0:
        return 'Buzz'
    else:
        return i

if __name__ == "__main__":
    for i in range(1, 101):
        print(fizz_buzz(i))

class FizzBuzzTestCase(unittest.TestCase):
    def test_fizz(self):
        result = fizz_buzz(3)
        self.assertEqual(result, 'Fizz')

    def test_buzz(self):
        result = fizz_buzz(5)
        self.assertEqual(result, 'Buzz')

    def test_fizzbuzz(self):
        result = fizz_buzz(15)
        self.assertEqual(result, 'FizzBuzz')

    def test_niether(self):
        result = fizz_buzz(1)
        self.assertEqual(result, 1)

Dictionary

```python >>> a = [1, 2, 3] >>> a[1] 2 >>> a[0] 1 >>> hello = "hello" >>> hello[1] 'e' >>> [(1, 'h'), (2, 'e')][(1, 'h'), (2, 'e')] >>> a = [(1, 'h'), (2, 'e')] >>> example_dict = {'python': 1991} >>> example_dict {'python': 1991} >>> example_dict['python'] 1991 >>> example_dict['p'] Traceback (most recent call last): File "<input>", line 1, in <module> example_dict['p'] KeyError: 'p' >>> example_dict.get('python') 1991 >>> example_dict.get('pythons') >>> example_dict.get('pythons', 1990) 1990 >>> example_dict['javascript'] = 1995 >>> example_dict {'javascript': 1995, 'python': 1991} >>>

``