# Module 3 - Python Programming Fundamentals
:::info
Learning objectives
* Classify conditions and branching by identifying structured scenarios with outputs.
* Work with objects and classes.
* Explain objects and classes by identifying data types and creating a class.
* Use exception handling in Python.
* Explain what functions do.
* Build a function using inputs and outputs.
* Explain how for loops and while loops work.
* Work with condition statements in Python, including operators and branching.
* Create and use loop statements in Python.
:::
> Conditions and Branching
This video introduces **conditions**, and we can use operators like **`and`** and **`or`** to make conditions more complex.
> Hands-on Lab: Conditions and Branching
- [Conditions and Branching](https://github.com/jacksonchen1998/IBM-PY0101EN-Python-Basics-for-Data-Science/blob/main/Module_3/conditions_in_python.ipynb)
> Practice Quiz: Conditions and Branching
1. What is the outcome of the following? `1=2`
:::spoiler Answer
`SyntaxError:can't assign to literal`
:::
2. What is the output of the following code segment?
```python
i=6
i<5
```
:::spoiler Answer
`False`
:::
3. True or False. What is the output of the below code snippet? `‘a’==‘A’`
:::spoiler Answer
`False`
:::
4. Which of the following best describes the purpose of ‘elif’ statement in a conditional structure?
:::spoiler Answer
It defines the condition in case the preceding conditions in the if statement are not fulfilled.
:::
> Loops
This video introduces the **`for` loop** and **`while` loop**.
Different `for` loop variations can be used in different scenarios, such as:
- `for a in list` – Iterates directly over elements.
- `for i in range(len(list))` – Iterates using an index.
- `for i, item in enumerate(list)` – Iterates with both index and value.
> Practice Quiz: Loops
1. What will be the result of the following?
```python
for x in range(0, 3):
print(x)
```
:::spoiler Answer
```
0
1
2
```
:::
2. What is the output of the following:
```python
for x in ['A','B','C']:
print(x+'A')
```
:::spoiler Answer
```
AA
BA
CA
```
:::
3. What is the output of the following:
```python
for i,x in enumerate(['A','B','C']):
print(i,x)
```
:::spoiler
```
0 A
1 B
2 C
```
:::
> Functions
The video explains Python functions, covering built-in functions like `len()`, `sum()`, `sorted()`, and `.sort()`.
It shows how to define custom functions using `def`, return values, and handle multiple parameters. Functions can include loops, accept variadic arguments (`*args`), and may return `None` if no return statement is provided.
Variable scope is discussed, distinguishing between global and local variables. The video ends with an invitation to explore more advanced function concepts.
> Hands-on Lab: Functions
- [Functions](https://github.com/jacksonchen1998/IBM-PY0101EN-Python-Basics-for-Data-Science/blob/main/Module_3/exception_handling.ipynb)
> Practice Quiz: Functions
1. What does the following function return: `len(['A','B',1])` ?
:::spoiler Answer
`3`
:::
2. What does the following function return: `len([sum([0,0,1])])` ?
:::spoiler Answer
`1`
:::
3. What is the value of list L after the following code segment is run?
```python
L=[1,3,2]
sorted(L)
```
:::spoiler Answer
`[1,3,2]`
:::
4. What result does the following code produce?
```python
def print_function(A):
for a in A:
print(a + '1')
print_function(['a', 'b', 'c'])
```
:::spoiler Answer
```python
a1
b1
c1
```
:::
5. What is the output of the following lines of code?
```python
def Print(A):
for a in A:
print(a+'1')
Print(['a','b','c'])
```
:::spoiler Answer
```python
a1
b1
c1
```
:::
> Exception Handling
This video shows:
- **Exception Handling** helps manage errors without crashing the program.
- **try…except**: Attempts code in `try`; handles errors in `except`.
- **Specific exceptions** (e.g., `IOError`) are better than generic ones.
- **else** runs if no errors occur (e.g., confirm success).
- **finally** always runs (e.g., close files).
- Helps write more reliable and debuggable programs.
**Errors** are typically caused by the environment, hardware, or operating system.
**Exceptions** are usually a result of problematic code execution within the program.
> Hands-On Lab: Exception Handling
- [Exception Handling](https://github.com/jacksonchen1998/IBM-PY0101EN-Python-Basics-for-Data-Science/blob/main/Module_3/exception_handling.ipynb)
> Practice Quiz: Exception Handling
1. Why do we use exception handlers?
:::spoiler Answer
To catch errors within a program.
:::
2. What is the purpose of a try…except statement?
:::spoiler Answer
Catch and handle exceptions when an error occurs
:::
3. Consider the following code: If the user enters the value of `b` as 0, what is expected as the output?
```py
a = 1
try:
b = int(input("Please enter a number to divide a"))
a = a/b
print("Success a=",a)
except:
print("There was an error")
```
:::spoiler Answer
There was an error
:::
> Objects and Classes
This video introduces the concept of **classes and objects** in Python:
- **Circle** and **Rectangle** classes are used to create objects like `RedCircle` and `BlueCircle`.
- Objects have **attributes** (e.g., `radius`, `color`, `height`, `width`) and **methods** (e.g., `drawRectangle`).
- Use the **`dir()`** function to view an object’s attributes and methods.
- Attributes with underscores are internal; focus on regular ones.
- Objects are **instances of classes**, and Python offers many features for working with them.
> Hands-On Lab: Objects and Classes
- [Classes and Objects](https://github.com/jacksonchen1998/IBM-PY0101EN-Python-Basics-for-Data-Science/blob/main/Module_3/classes_and_objects_in_python.ipynb)
> Practice Quiz: Objects and Classes
1. Which of the following statements will create an object `C1` for the class that uses radius as 4 and color as ‘yellow’?
```py
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return self.radius
```
:::spoiler Answer
```py
C1 = Circle(4, ‘yellow’)
```
:::
2. Consider the execution of the following lines of code.
```py
CircleObject = Circle()
CircleObject.radius = 10
```
What are the values of the radius and color attributes for the `CircleObject` after their execution?
```py
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return self.radius
```
:::spoiler Answer
10, 'blue'
:::
3. What is the color attribute of the object V1?
```py
class Vehicle:
color = "white"
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
self.seating_capacity = None
def assign_seating_capacity(self, seating_capacity):
self.seating_capacity = seating_capacity
V1 = Vehicle(150, 25)
```
:::spoiler Answer
'white'
:::
4. Which of the following options would create an appropriate object that points to a red, 5-seater vehicle with a maximum speed of 200kmph and a mileage of 20kmpl?
```py
class Vehicle:
color = "white"
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
self.seating_capacity = None
def assign_seating_capacity(self, seating_capacity):
self.seating_capacity = seating_capacity
V1 = Vehicle(150, 25)
```
:::spoiler Answer
```py
Car = Vehicle(200,20)
Car.color = ‘red’
Car.assign_seating_capacity(5)
```
:::
5. What is the value printed upon execution of the code shown below?
```py
class Graph():
def __init__(self, id):
self.id = id
self.id = 80
val = Graph(200)
print(val.id)
```
:::spoiler Answer
80
:::
> Practice Lab: Text Analysis
- [Text Analysis](https://github.com/jacksonchen1998/IBM-PY0101EN-Python-Basics-for-Data-Science/blob/main/Module_3/text_analysis.ipynb)