Skip to content

Commit 357caf7

Browse files
authored
Add files via upload
0 parents  commit 357caf7

File tree

19 files changed

+1048
-0
lines changed

19 files changed

+1048
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Lab Instructions: Abstract Classes and Methods
2+
3+
In this assignment, you will be creating an abstract class for a bank that will be used to create a regular class for a specific bank.
4+
This class will contain the implementation of the abstract method from the abstract class.
5+
6+
<br>
7+
8+
> ### **Tips: Before you Begin**
9+
> #### **To view your code and instructions side-by-side**, select the following in your VSCode toolbar:
10+
> - View -> Editor Layout -> Two Columns
11+
> - To view this file in Preview mode, right click on this README.md file and `Open Preview`
12+
> - Select your code file in the code tree, which will open it up in a new VSCode tab.
13+
> - Drag your assessment code files over to the second column.
14+
> - Great work! You can now see instructions and code at the same time.
15+
> - Questions about using VSCode? Please see our support resources [here](https://www.coursera.org/learn/programming-in-python/supplement/2IEyt/visual-studio-code-on-coursera)
16+
> #### **To run your Python code**
17+
> - Select your Python file in the Visual Studio Code file tree
18+
> - You can right click the file and select "Run Python File in Terminal"
19+
> or run the file using the smaller
20+
play button in the upper right-hand corner
21+
> of VSCode.
22+
(Select "Run Python File in Terminal" in the provided button dropdown)
23+
> - Alternatively, you can follow lab instructions which use python3 commands to run your code in terminal.
24+
>
25+
<br>
26+
27+
## Exercise Instructions
28+
29+
### Instructions
30+
31+
1. Create a class called `Bank` and pass `ABC` to it.
32+
33+
2. Inside the class you have to define two methods:
34+
- 2.1: Define a function called `basicinfo()` and add a print statement inside it saying
35+
`"This is a generic bank"` and returning the string `"Generic bank: 0"`.
36+
37+
- 2.2: Define a second function called `withdraw` and keep it empty by adding a pass keyword under it.
38+
Make this function abstract by adding `'@abstractmethod'` right above it. <br><br>
39+
40+
3. Create another class called `Swiss` and pass the class `Bank` inside it.
41+
This means you are inheriting from `class Bank`.
42+
- 3.1: Create a constructor for this class that initializes a class variable `bal` to `1000` <br><br>
43+
44+
4. Override both functions from the Bank class: `basicinfo()` and `withdraw()`.
45+
- 4.1: Define a function called `basicinfo()` and add a print statement inside it stating `“This is the Swiss Bank”`
46+
and returning a string with `"Swiss Bank: "` followed by the current bank balance.
47+
For example, if `self.bal = 80`, then it would return `"Swiss Bank: 80"`
48+
49+
- 4.2 Define a second function, called `withdraw` and pass one parameter to it (other than `self):` amount.
50+
Amount represents the amount that will be withdrawn.
51+
52+
- 4.2.1: Update the class variable bal by deducting the value of amount from it.
53+
- 4.2.2: Print the value of amount giving output such as: “Withdrawn amount: 30"
54+
- 4.2.3: Print the new balance giving an output such as: “New balance: 970”
55+
- 4.2.4: Return the new balance
56+
- Note: Make sure to verify that there is enough money to withdraw!
57+
If amount is greater than balance, then do not deduct any money from the
58+
class variable `bal`. Instead, print a statement saying `"Insufficient funds"`, and return the original account balance instead.
59+
60+
<br>
61+
62+
63+
## Final Step: Let's submit your code!
64+
Nice work! To complete this assessment:
65+
- Save your file through File -> Save
66+
- Select "Submit Assignment" in your Lab toolbar.
67+
68+
Your code will be autograded and return feedback shortly on the "Grades" tab.
69+
You can also see your score in your Programming Assignment "My Submission" tab.
70+
<br> <br>

Abstract Classes and Methods/bank.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Import ABC and abstractmethod from the module abc (which stands for abstract base classes)
2+
from abc import ABC, abstractmethod
3+
4+
# Class Bank
5+
class Bank(ABC):
6+
""" An abstract bank class
7+
8+
[IMPLEMENT ME]
9+
1. This class must derive from class ABC
10+
2. Write a basicinfo() function that prints out "This is a generic bank" and
11+
returns the string "Generic bank: 0"
12+
3. Define a second function called withdraw and keep it empty by
13+
adding the `pass` keyword under it. Make this function abstract by
14+
adding an '@abstractmethod' tag right above the function declaration.
15+
"""
16+
@abstractmethod
17+
def withdraw(self, amount):
18+
pass
19+
20+
def basicinfo(self):
21+
print("This is a generic bank")
22+
return "Generic bank: 0"
23+
24+
# Class Swiss
25+
class Swiss(Bank):
26+
""" A specific type of bank than derives from class Bank
27+
28+
[IMPLEMENT ME]
29+
1. This class must derive from class Bank
30+
2. Create a constructor for this class that initializes a class
31+
variable `bal` to 1000
32+
3. Implement the basicinfo() function so that it prints "This is the
33+
Swiss Bank" and returns a string with "Swiss Bank: " (don't forget
34+
the space after the colon) followed by the current bank balance.
35+
36+
For example, if self.bal = 80, then it would return "Swiss Bank: 80"
37+
38+
4. Implement withdraw so that it takes one argument (in addition to
39+
self) that is an integer which represents the amount to be withdrawn
40+
from the bank. Deduct the withdrawn amount from the bank bal, print
41+
the withdrawn amount ("Withdrawn amount: {amount}"), print the new
42+
balance ("New Balance: {self.bal}"), and return the new balance.
43+
44+
Note: Make sure to verify that there is enough money to withdraw!
45+
If amount is greater than balance, then do not deduct any
46+
money from the class variable `bal`. Instead, print a
47+
statement saying `"Insufficient funds"`, and return the
48+
original account balance instead.
49+
"""
50+
def __init__(self):
51+
self.bal = 1000
52+
53+
def basicinfo(self):
54+
print("This is the Swiss Bank")
55+
return f"Swiss Bank: {self.bal}"
56+
57+
def withdraw(self, amount):
58+
if amount > self.bal:
59+
print("Insufficient funds")
60+
return self.bal
61+
else:
62+
self.bal -= amount
63+
print(f"Withdrawn amount: {amount}")
64+
print(f"New balance: {self.bal}")
65+
return self.bal
66+
67+
# Driver Code
68+
def main():
69+
assert issubclass(Bank, ABC), "Bank must derive from class ABC"
70+
s = Swiss()
71+
print(s.basicinfo())
72+
s.withdraw(30)
73+
s.withdraw(1000)
74+
75+
if __name__ == "__main__":
76+
main()
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Lab Instructions: Functions, loops and data structures
2+
3+
In this lab you will be presented with a menu ordering system which will allow users to
4+
input three choices for a select menu. You are tasked with completing the menu system so
5+
that it returns and calculates the final bill for the user.
6+
<br><br>
7+
8+
> ### **Tips: Before you Begin**
9+
> #### **To view your code and instructions side-by-side**, select the following in your VSCode toolbar:
10+
> - View -> Editor Layout -> Two Columns
11+
> - To view this file in Preview mode, right click on this README.md file and `Open Preview`
12+
> - Select your code file in the code tree, which will open it up in a new VSCode tab.
13+
> - Drag your assessment code files over to the second column.
14+
> - Great work! You can now see instructions and code at the same time.
15+
> - Questions about using VSCode? Please see our support resources [here](https://www.coursera.org/learn/programming-in-python/supplement/2IEyt/visual-studio-code-on-coursera).
16+
> #### **To run your Python code**
17+
> - Select your Python file in the Visual Studio Code file tree
18+
> - You can right click the file and select "Run Python File in Terminal"
19+
> or run the file using the smaller
20+
play button in the upper right-hand corner
21+
> of VSCode.
22+
(Select "Run Python File in Terminal" in the provided button dropdown)
23+
> - Alternatively, you can follow lab instructions which use python3 commands to run your code in terminal.
24+
>
25+
26+
<br>
27+
28+
## There are three main objectives of this activity:
29+
1. Create new functions to solve specific problems.
30+
2. Gain experience of using for loops to iterate over different data collections.
31+
3. Create and use data structures to store, retrieve and loop over data.
32+
33+
<br>
34+
35+
## Exercise Instructions
36+
37+
1. Open the script ordering_system.py present inside the project folder.
38+
39+
2. Run the script and, when requested, enter in the three products of your choice based on the menu - 1 = espresso, 2 = coffee etc.
40+
41+
3. To run the script, open terminal and execute the following command.
42+
43+
```
44+
python3 ordering_system.py
45+
```
46+
47+
4. Extend the script to have a new function called `calculate_subtotal`.
48+
It should accept one argument which is the order list and return the sum
49+
of the prices of the items in the order list.
50+
51+
5. Implement `calculate_tax()` which calculates the tax of the subtotal.
52+
The tax percentage is 15% of overall bill.
53+
54+
6. Implement `summarize_order()` which returns a list of the names of the items
55+
that the customer ordered and the total amount (including tax) that they have to pay.
56+
The orders should show the name and price.
57+
58+
<br>
59+
60+
## Final Step: Let's submit your code!
61+
Nice work! To complete this assessment:
62+
- Save your file through File -> Save
63+
- Select "Submit Assignment" in your Lab toolbar.
64+
65+
Your code will be autograded and return feedback shortly on the "Grades" tab.
66+
You can also see your score in your Programming Assignment "My Submission" tab.
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
menu = {
2+
1: {"name": 'espresso',
3+
"price": 1.99},
4+
2: {"name": 'coffee',
5+
"price": 2.50},
6+
3: {"name": 'cake',
7+
"price": 2.79},
8+
4: {"name": 'soup',
9+
"price": 4.50},
10+
5: {"name": 'sandwich',
11+
"price": 4.99}
12+
}
13+
14+
def calculate_subtotal(order):
15+
""" Calculates the subtotal of an order
16+
17+
[IMPLEMENTED]
18+
1. Add up the prices of all the items in the order and return the sum
19+
20+
Args:
21+
order: list of dicts that contain an item name and price
22+
23+
Returns:
24+
float = The sum of the prices of the items in the order
25+
"""
26+
print('Calculating bill subtotal...')
27+
### WRITE SOLUTION HERE
28+
subtotal = 0 # initialize a variable to store the sum
29+
for item in order: # loop over the list of dictionaries
30+
subtotal += item["price"] # add the price of each item to the sum
31+
return subtotal # return the sum
32+
33+
def calculate_tax(subtotal):
34+
""" Calculates the tax of an order
35+
36+
[IMPLEMENTED]
37+
1. Multiply the subtotal by 15% and return the product rounded to two decimals.
38+
39+
Args:
40+
subtotal: the price to get the tax of
41+
42+
Returns:
43+
float - The tax required of a given subtotal, which is 15% rounded to two decimals.
44+
"""
45+
print('Calculating tax from subtotal...')
46+
### WRITE SOLUTION HERE
47+
tax = subtotal * 0.15 # multiply the subtotal by 0.15
48+
tax = round(tax, 2) # round the result to two decimal places
49+
return tax # return the tax
50+
51+
def summarize_order(order):
52+
""" Summarizes the order
53+
54+
[IMPLEMENTED]
55+
1. Calculate the total (subtotal + tax) and store it in a variable named total (rounded to two decimals)
56+
2. Store only the names of all the items in the order in a list called names
57+
3. Return names and total.
58+
59+
Args:
60+
order: list of dicts that contain an item name and price
61+
62+
Returns:
63+
tuple of names and total. The return statement should look like
64+
65+
return names, total
66+
"""
67+
print('Summarizing order...')
68+
### WRITE SOLUTION HERE
69+
subtotal = calculate_subtotal(order) # call calculate_subtotal function
70+
tax = calculate_tax(subtotal) # call calculate_tax function
71+
total = round(subtotal + tax, 2) # calculate total by adding subtotal and tax and rounding to two decimals
72+
names = [] # initialize an empty list to store names
73+
for item in order: # loop over the list of dictionaries
74+
names.append(item["name"]) # append the name of each item to the list
75+
return names, total # return a tuple of names and total

Import and Scope/README.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Lab Instructions: Import and Scope
2+
3+
So far, you've learned the different ways in which you can use import statements to import other Python files, modules and packages.
4+
You have also seen the different ways in which you can import specific functions using different formats of import.
5+
In this assignment you'll learn and practice how to use import to bring external code within the direct scope of the project.
6+
7+
<br>
8+
9+
> ### **Tips: Before you Begin**
10+
> #### **To view your code and instructions side-by-side**, select the following in your VSCode toolbar:
11+
> - View -> Editor Layout -> Two Columns
12+
> - To view this file in Preview mode, right click on this README.md file and `Open Preview`
13+
> - Select your code file in the code tree, which will open it up in a new VSCode tab.
14+
> - Drag your assessment code files over to the second column.
15+
> - Great work! You can now see instructions and code at the same time.
16+
> - Questions about using VSCode? Please see our support resources [here](https://www.coursera.org/learn/programming-in-python/supplement/2IEyt/visual-studio-code-on-coursera).
17+
> #### **To run your Python code**
18+
> - Select your Python file in the Visual Studio Code file tree
19+
> - You can right click the file and select "Run Python File in Terminal"
20+
> or run the file using the smaller
21+
play button in the upper right-hand corner
22+
> of VSCode.
23+
(Select "Run Python File in Terminal" in the provided button dropdown)
24+
> - Alternatively, you can follow lab instructions which use python3 commands to run your code in terminal.
25+
>
26+
27+
<br>
28+
29+
## Exercise Objectives:
30+
- Use the import statement to import a built-in package in Python.
31+
- Use the import statement to call a function present in another Python file.
32+
<br><br>
33+
34+
## Instructions
35+
36+
1. Open the file jsongenerator.py present inside project folder.
37+
38+
2. Import a built-in package called `json`
39+
40+
3. Import the following from a file called employee.py:
41+
- A function called `details`
42+
- Variables called `employee_name`, `age` and `title`
43+
<br><br>
44+
45+
4. Implement the `create_dict()` function that returns a dictionary given employee information.
46+
Create and return a dictionary with three key-value pairs where:
47+
- Keys are string variables: `"first_name"` `“age”` and `“title”`
48+
and their respective values are `employee_name`, `age` and `title` variables that we have imported from the employee module.
49+
- Be sure to cast the values to the expected types.
50+
<br><br>
51+
52+
5. Use a function called `dumps()` from the json module using dot notation and pass the `employee_dict` dictionary that we have created to it.
53+
Return its value to a variable named `json_object`.
54+
55+
The format of the same should look like:
56+
```
57+
variable = json.dumps(dict)
58+
```
59+
60+
6. Complete the `write_json_to_file()` function
61+
- Use a built-in function called `open()` and pass the `output_file` argument and `“w”` to it.
62+
Return the value of this function to a variable named newfile.
63+
- Call a function called `write()` over this variable newfile. Pass the `json_object` variable you created in Step 5 inside it.
64+
- Close this file by calling a built-in function `close()` directly on newfile. You don’t need to pass any arguments here.
65+
<br><br>
66+
67+
68+
7. Save the files
69+
70+
8. Open the terminal to execute the files
71+
72+
9. Run the code using the command (within project directory)
73+
```
74+
python3 jsongenerator.py
75+
```
76+
77+
<br>
78+
79+
80+
## Final Step: Let's submit your code!
81+
Nice work! To complete this assessment:
82+
- Save your file through File -> Save
83+
- Select "Submit Assignment" in your Lab toolbar.
84+
85+
Your code will be autograded and return feedback shortly on the "Grades" tab.
86+
You can also see your score in your Programming Assignment "My Submission" tab.
87+
<br> <br>

Import and Scope/employee.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
employee_name = "Mario"
2+
age = "55"
3+
title = "owner"
4+
5+
def details():
6+
print("Employee name is: ", employee_name)
7+
print("Employee age is: ", age)
8+
print("Employee title is: ", title)

0 commit comments

Comments
 (0)