Course: Q5 Prep

Task 2:

Create a program that reads a csv file in the following format:

 <product_name>;<price>;<quantity>

 There could be multiple records for the same product name.

Sample csv file contents:

coca cola;10.5;10

coca cola;10.5;a

coca cola;xx;5

water;4;5

water;10.5;-5

coca cola;-1.5;5

water;1.5;42

Based on the records in the csv file generated statistics for unique product name – total price and total quantity. Create new csv file to save those statistics in the format:

 <product_name>,<total_price>,<total quantity>

 Note: it is possible that price and/or quantity is not valid (e.g. negative numbers, letters, etc) - disregard the records that are invalid.

import csv

def ex():
    stats = 0;
    try:
        with open('products.csv') as csvfile:
            csv_reader = csv.reader(csvfile, delimiter=';')
            for row in csv_reader:
                name, price, quantity = row
                try:
                    price = float(price)
                    quantity = int(quantity)
                    if name not in stats:
                        stats[name] = dict(price=0, quantity=0)
                    stats[name]['total'] += price * quantity
                    stats[name]['quantity'] += quantity
                except ValueError:
                    print('Invalid price')

    except FileNotFoundError:
        print("File not found")

    except ValueError:
        print("Value error")

    with open('products.csv', 'w') as csv_file:
        csv_writer = csv.writer(csv_file)
        for key, value in stats.items():
            csv_writer.writerow([key, value['total'], value['quantity']])

csv library

Task 3:

Given file data.json:

{

"employees": [

{"name": "Alice", "salary": 3000},

{"name": "Bob", "salary": 2500}

]

}

 Read the file and print all employee names and calculate total salary.

 Add one more employee to the data and store the data into a new .json file.

def ex3():
    try:
        salary = 0
        with open('employees.json') as file:
            employees = json.load(file)
            for employee in data["employees"]:
                print(employee['name'])
                salary += employee['salary']
    except FileNotFoundError:
        print("File not found")

    with open('employees.csv', 'w') as csv_file:
        new_emp = {
            'name': 'John',
            'salary': 5000
        }
        data["employees"].append(new_emp)
        json.dumps(data, file)

Task 4: Given the following function create unit tests to cover all cases:

def magic(op1, op2, operation):

try:

if operation == '/’:

return op1 / op2

else:

return op1 + op2

except ZeroDivisionError:

return 0

except Exception:

raise

def magic(op1, op2, operation):
    try:
        if operation == '/’:
            return op1 / op2
        else:
            return op1 + op2
    except ZeroDivisionError:
        return 0
    except Exception:
        raise

from unittest import TestCase, main

class TestMagic(TestCase):
    def test_magic(self):
        self.assertEqual(magic(2, 2, '/'), 1)

    def test_magic_div_zero(self):
        self.assertEqual(magic(0, 0, '/'), 0)

    def test_magic_add(self):
        self.assertEqual(magic("xx", "tt", '+'), "xxtt")

    def test_magic_others(self):
        with self.assertRaises(ZeroDivisionError):
            magic("xx", 42, '+')