Important Coding Functions Summary
Important Coding Functions Summary
2. Input Function:
- The input() function assigns user input to a variable.
Example:
some_value = input("Enter some value: ")
3. Printing Values:
- The print() function outputs the value of a variable to the console.
Example:
print(x)
4. Deleting Variables:
- Use del() to delete a variable.
Example:
del(x)
5. Mathematical Operations:
- Basic operations: addition (+), subtraction (-), multiplication (*), division (/).
Example:
z = x + 2 * y - 12
6. Augmented Assignments:
- Shortcuts for applying operations to variables:
Example:
x += 5 # Same as x = x + 5
x *= 5 # Same as x = x * 5
8. String Operations:
- Concatenation: Join strings using +.
Example: greeting = "Hello, " + "World!"
- Multiply strings: Repeat strings using *.
Example: dash_line = "-" * 5 # Output: "-----"
9. String Slicing:
- Access parts of a string using index notation.
Example:
example_string = "Example!"
first_char = example_string[0] # Output: 'E'
last_char = example_string[-1] # Output: '!'
Week3-DataStructures
1. List Functions and Methods:
- Lists in Python are ordered, mutable sequences of elements. They can contain elements of
different data types.
Accessing Elements:
- list_name[0]: Accesses the first element of the list.
Example:
first_element = list_name[0] # first_element = 1
Slicing:
- list_name[start:end]: Returns a new list containing elements from the start index to end-1.
Example:
sublist = list_name[1:3] # sublist = [2, 3]
Modifying Elements:
- list_name[2] = 10: Modifies the element at index 2.
Example:
list_name[2] = 10 # list_name becomes [1, 2, 10, 4]
Concatenation:
- list1 + list2: Concatenates two lists.
Example:
combined_list = [1, 2] + [3, 4] # combined_list = [1, 2, 3, 4]
Repetition:
- list1 * 3: Repeats the list elements three times.
Example:
repeated_list = [1, 2] * 3 # repeated_list = [1, 2, 1, 2, 1, 2]
List Methods:
- x.append(element): Adds the element to the end of the list.
Example:
list_name.append(5) # list_name = [1, 2, 10, 4, 5]
- Tuples are ordered, immutable sequences of elements. They cannot be modified after
creation.
Accessing Elements:
- tuple_name[0]: Accesses the first element of the tuple.
Example:
first_element = tuple_name[0] # first_element = 1
Slicing:
- tuple_name[start:end]: Returns a new tuple containing elements from start index to end-1.
Example:
sub_tuple = tuple_name[1:3] # sub_tuple = (2, 3)
Concatenation:
- tuple1 + tuple2: Concatenates two tuples.
Example:
combined_tuple = (1, 2) + (3, 4) # combined_tuple = (1, 2, 3, 4)
Repetition:
- tuple1 * 2: Repeats the tuple elements twice.
Example:
repeated_tuple = (1, 2) * 2 # repeated_tuple = (1, 2, 1, 2)
Tuple Methods:
- x.index(element): Returns the index of the first occurrence of the element.
Example:
index = tuple_name.index(2) # index = 1
- Sets are unordered collections of unique elements. They do not allow duplicate values.
Adding Elements:
- set_name.add(element): Adds the element to the set.
Example:
set_name.add(5) # set_name = {1, 2, 3, 4, 5}
Removing Elements:
- set_name.remove(element): Removes the element from the set (raises KeyError if not
found).
Example:
set_name.remove(3) # set_name = {1, 2, 4, 5}
- Intersection:
Example:
intersection_set = set1 & set2 # intersection_set = {3}
- Difference:
Example:
difference_set = set1 - set2 # difference_set = {1, 2}
- Symmetric Difference:
Example:
sym_diff_set = set1 ^ set2 # sym_diff_set = {1, 2, 4, 5}
Accessing Elements:
- dict_name["key"]: Accesses the value associated with the key.
Example:
name = dict_name["name"] # name = "John"
Modifying Elements:
- dict_name["key"] = value: Updates the value associated with the key.
Example:
dict_name["age"] = 31 # dict_name becomes {"name": "John", "age": 31}
Dictionary Methods:
- x.update({key: value}): Updates or adds key-value pairs to the dictionary.
Example:
dict_name.update({"age": 32}) # {"name": "John", "age": 32, "location": "New York"}
- x.items(): Returns a view object containing the dictionary’s key-value pairs as tuples.
Example:
items = dict_name.items() # dict_items([("name", "John"), ("age", 32), ("location", "New
York")])
Week 4 ControlFlow
1. Comparison Operators:
- Comparison operators are used to compare values and return True or False.
- ==: equal to
- !=: not equal to
- >: greater than
- <: less than
- >=: greater than or equal to
- <=: less than or equal to
Example:
x=5
y=3
print(x > y) # True
2. Logical Operators:
- Identity operators check if two objects are the same object in memory.
- is: returns True if both operands are the same object.
- is not: returns True if both operands are not the same object.
Example:
a = [1, 2, 3]
b=a
print(a is b) # True, because they refer to the same object.
4. Membership Operators:
- if...else statements are used when you have two possible outcomes.
Example:
x=3
if x % 2 == 0:
print("Even number")
else:
print("Odd number")
7. match-case Statements:
Week 5-Looping
1. The range() Function:
- The range() function generates a sequence of numbers. It is typically used with loops.
Syntax:
range(start, stop, step)
- start: Starting number (default is 0)
- stop: End of the range (exclusive)
- step: Increment between each number (default is 1)
Example:
for i in range(1, 10, 2):
print(i)
# Outputs: 1, 3, 5, 7, 9
- The range function is commonly used in both for loops and while loops.
2. For Loops:
- A for loop iterates over a sequence (list, tuple, dictionary, set, or string) a fixed number of
times.
- The <holder> variable refers to the current element being accessed.
Syntax:
for <holder> in <sequence>:
<action block>
Example:
for elem in [1, 2, 3, 4]:
print(elem)
# Outputs: 1, 2, 3, 4
- You can also use the range function to loop through a sequence of numbers.
Example:
for i in range(5):
print("Hello")
# Outputs "Hello" five times.
- Nested for loops are used for multi-dimensional sequences (e.g., lists of lists).
Example:
x = [[1, 2, 3], [4, 5, 6]]
for out_list in x:
for elem in out_list:
print(elem)
# Outputs: 1, 2, 3, 4, 5, 6
3. While Loops:
- Python does not have a native do-while loop, but we can simulate it with a while loop.
Example:
i=0
while True:
i += 1
if i >= 1:
break
print(i)
# Outputs: 1
6. Infinite Loops:
- An infinite loop occurs when the condition in a while loop is always True and there is no
exit condition.
- To stop an infinite loop, use Control + C in Python.
Example of an infinite loop:
while True:
print("This will run forever")
- Loops help eliminate repetitive code by executing similar actions multiple times.
- They also reduce errors and make future changes easier.
- Use loops to gather user inputs, validate inputs, or process large amounts of data.
Example:
for _ in range(3):
score = input("Enter score: ")
# Process score and store it
Week 6:Functions
What are Functions?
Functions are reusable blocks of code designed to perform a specific task. They consist of a
function definition (block of code) and a function call (to execute the code). Functions
reduce redundancy, simplify code, and promote modular programming.
Structure of a Function
A function generally follows this format:
def function_name(arguments):
"""Optional docstring explaining the function."""
action_block
return value (optional)
Code:
def greeting():
print("Welcome!")
Output:
Welcome!
Code:
result = multiply_values(4, 5)
print(result)
Output:
20
Code:
print(multiply_values.__doc__)
Output:
This function returns the product of two values.
Code:
def sum_values(*args):
return sum(args)
print(sum_values(1, 2, 3, 4))
Output:
10
Code:
def print_kwargs(**kwargs):
return kwargs
print(print_kwargs(a=1, b=2, c=3))
Output:
{'a': 1, 'b': 2, 'c': 3}
Function Scoping
The scope of a variable determines where it can be accessed. Variables defined inside a
function are local to
that function and cannot be accessed outside it, whereas global variables are accessible
from any function.
a = 10 # Global variable
def print_value():
a = 5 # Local variable
print(a)
print_value()
print(a)
Output:
5
10
Functions
Lambda functions are small anonymous functions used for simple operations. They are
often used in higher-order functions.
add = lambda x, y: x + y
print(add(2, 3))
Output:
5
Code:
numbers = [1, 2, 3, 4]
print(squares)
Output:
[1, 4, 9, 16]
Code:
numbers = [1, 2, 3, 4, 5, 6]
print(even_numbers)
Output:
[2, 4, 6]
Week 7-Modules
1. What are Modules?
Modules in Python refer to a file containing Python code, such as functions, classes, and
variables. Modular programming involves breaking down a large program into smaller,
manageable modules. This makes the code simpler, more maintainable, and reusable.
2. Modular Programming
Modular programming refers to breaking down a large task or application into smaller parts
called modules.
Each module contains specific code to perform part of the task, improving simplicity and
reusability.
Advantages:
- **Simplicity**: Focus on smaller parts of the problem.
- **Maintainability**: Modify a module without affecting other parts.
- **Reusability**: Share modules across projects.
1. **Built-in Modules**: Modules that come with Python (standard library). Examples
include os, math, random, and datetime.
2. **Custom Modules**: Python files (.py) created by users that contain their custom code.
4. Importing Modules
You can import modules using the following ways:
- **Importing an entire module**: This makes all functions and variables in the module
available for use.
Example:
```python
import math
print(math.sqrt(16)) # Output: 4.0
```
- **Importing specific functions**: Only the specified functions are imported from the
module.
Example:
```python
from math import sqrt
print(sqrt(16)) # Output: 4.0
```
- **Using an alias**: Shorten the name of the module for easier reference.
Example:
```python
import math as m
print(m.sqrt(16)) # Output: 4.0
```
os Module
The os module provides functions to interact with the operating system. Some commonly
used functions include:
Example:
```python
import os
os.chdir('/path/to/directory')
print(os.getcwd()) # Output: /path/to/directory
```
math Module
The math module provides mathematical functions beyond basic arithmetic, such as
trigonometric and logarithmic functions.
- **math.pi**: Value of π.
- **math.e**: Value of Euler’s number.
- **math.sin(x)**: Returns the sine of x (angle in radians).
- **math.sqrt(x)**: Returns the square root of x.
Example:
```python
import math
print(math.pi) # Output: 3.141592653589793
print(math.sqrt(16)) # Output: 4.0
```
random Module
The random module is used to generate random numbers and perform operations like
shuffling a sequence.
Example:
```python
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice([1, 2, 3])) # Randomly selects an element
```
datetime Module
The datetime module provides classes for working with dates and times.
Example:
```python
import datetime
print(datetime.date.today()) # Output: current date
print(datetime.datetime.now()) # Output: current date and time
```
You can also use `strptime` to parse strings into datetime objects based on these format
codes.
Example:
```python
import os
os.mkdir('new_folder') # Creates a directory named 'new_folder'
print(os.listdir()) # Lists the content of the current directory
```
Example:
```python
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pow(2, 3)) # Output: 8.0
print(math.log(10, 10)) # Output: 1.0
```
Example:
```python
import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output: Shuffled list
print(random.randint(10, 20)) # Output: Random integer between 10 and 20
```
Week 8-Packages
1. External Packages
Packages are collections of modules that provide tools for performing complex
programming tasks. Python has an extensive set of external packages that can be used for
tasks such as data analysis, machine learning, and scientific computing. These packages are
typically found in the Python Package Index (PyPI) and can be installed using package
managers like pip or conda.
To manage external packages, Python uses package managers like pip and conda.
- **pip**: The most common Python package manager used to install and manage
packages from PyPI.
Example:
```bash
pip install package_name --user
```
- **conda**: A modern package manager that can install and manage packages across
different systems.
Example:
```bash
conda install package_name
```
3. numpy Package
- To install numpy:
```bash
pip install numpy
```
- Importing numpy:
```python
import numpy as np
```
4. n-dimensional Arrays
numpy arrays are collections of elements of the same type in n dimensions. They improve
performance over traditional
Python lists by storing data more efficiently.
Example:
```python
import numpy as np
array_2d = np.array([[1, 2], [3, 4]])
print(array_2d)
```
5. ndarray Class
The ndarray class is used to represent numpy arrays. Some of its attributes include:
Example:
```python
numpy_array = np.array([1, 2, 3, 4])
print(numpy_array.shape) # Output: (4,)
```
7. pandas Package
pandas is a powerful data analysis and manipulation package built on top of numpy. It
provides data structures like Series
and DataFrames for handling large datasets, including tabular data.
- To install pandas:
```bash
pip install pandas
```
- Importing pandas:
```python
import pandas as pd
```
Example:
```python
import pandas as pd
series_example = pd.Series([1, 2, 3, 4])
dataframe_example = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
```
9. Exploring DataFrames
Example:
```python
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
print(df.head())
print(df.describe())
```
Example:
the_df = the_df.sort_values("Name", ascending=False) # sorts by "Name" in descending
order
Function: the_df.groupby(by).agg(func)
- "by": column(s) to group by (string or list)
- "func": function to apply to grouped data (e.g., sum, count)
Example:
the_df = the_df.groupby("category").sum() # groups by "category" and sums numerical
columns
3. Deriving Data
Deriving data creates new columns by performing operations on existing ones.
Example:
the_df["NewCol"] = the_df["ColA"] + the_df["ColB"] * 0.1 # derives a new column
Function: the_df[col].astype(dtype)
- "col": column to convert
- "dtype": target data type (e.g., int, float, string)
Example:
the_df["Amount"] = the_df["Amount"].astype(float) # converts "Amount" to float
5. Mapping Functions
Apply functions row-wise, column-wise, or element-wise to modify data.
Functions:
- apply(): row/column-wise
- applymap(): element-wise across DataFrame
- map(): element-wise across Series
Examples:
the_df.apply(lambda x: x * 2) # doubles each element row/column-wise
the_df['Col'].map(lambda x: x.lower()) # converts strings to lowercase in a specific column
Example:
the_df = the_df.rename(columns={"old_col": "new_col"}) # renames a column
the_df = the_df[["col1", "col2"]] # filters the DataFrame to keep only certain columns
Function:
- pivot(): reshapes based on unique values in columns
- melt(): converts wide data to long format
Example:
the_df.pivot(index="ID", columns="category", values="value") # pivots to show categories
as columns
8. Combining Data
DataFrames can be merged using functions like concat(), join(), and merge().
Function:
- concat(): joins DataFrames along a particular axis
- merge(): SQL-style joins on common columns
Example:
result_df = pandas.concat([df1, df2], axis=1) # concatenates along columns
Function: the_df[col].str.function()
- Functions: len(), lower(), upper(), replace()
Example:
the_df["Name"] = the_df["Name"].str.upper() # converts names to uppercase
Function:
- pd.to_datetime(): converts strings to datetime objects
- dt accessor: extracts components (e.g., year, month, day)
Example:
the_df["date"] = pd.to_datetime(the_df["date"]) # converts string to datetime
the_df["year"] = the_df["date"].dt.year # extracts the year component
x = list(range(10))
y = list(range(0, 20, 2))
z = list(range(20, 40, 2))
# Add legend
ax.legend()
x = list(range(10))
y = list(range(0, 20, 2))
z = list(range(20, 40, 2))
3. Scatter Plot
import numpy as np
import matplotlib.pyplot as plt
x = list(range(100))
y = list(range(100)) + 50 * np.random.random(100) # Random values added
# Show plot
plt.show()
4. Bar Chart
plt.tight_layout()
plt.show()
5. Pie Chart
ax.legend()
plt.tight_layout()
plt.show()
6. Histogram
import numpy as np
import matplotlib.pyplot as plt
# Create a histogram
ax.hist(x, label="Random Data", color="r")
plt.tight_layout()
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
# Create a DataFrame
df = pd.DataFrame({
'length': [1.5, 0.5, 1.2, 0.9, 3],
'width': [0.7, 0.2, 0.15, 0.2, 1.1]
}, index=['pig', 'rabbit', 'duck', 'chicken', 'horse'])
# Plot DataFrame
df.plot(title="DataFrame Plot")
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
# Create a Series
srs = pd.Series([1, 2, 3, 3])
The optional third argument 'buffer' is used for handling large files.
2. Types of Files
Files are categorized into two types:
Regardless of file type, the process is the same: Open the file, process it (read/write), and
close the file.
• the_ptr = open(filename, 'mode'): Opens the file with the specified mode (read, write, etc.).
5. Reading Example
file_ptr = open("example.txt", "r")
the_lines = file_ptr.readlines()
print(the_lines)
file_ptr.close()
Explanation: This code reads the file into a list and prints each line after stripping newline
characters using `strip()` method.
6. Writing Example
file_ptr = open("output.txt", "w")
file_ptr.write("I create this file using Python.")
file_ptr.write("I write headers and values.")
file_ptr.write("")
file_ptr.write("Name Age Number")
file_ptr.write("Jim 16 2090943")
file_ptr.close()
Explanation: This example demonstrates writing to a file. Escape sequences like '\n' are
used for newlines, and '\t' for tabs.
Explanation: Binary data is written to and read from a binary file. A list is converted to a
bytearray before writing to the file.
9. CSV Files
CSV (Comma Separated Values) files are text files with a structured format for tabular data,
where rows are separated by newlines and columns by commas.
file_ptr.close()
Explanation: The `csv.reader()` function reads the contents of a CSV file row by row,
returning each row as a list.
11. CSV Writing Example
import csv
file_ptr.close()
Explanation: The `csv.writer()` function writes rows of data to a CSV file, where each row is
a list.
# JSON string
json_data = """
{
"number": 118,
"name": "Jim Smith",
"age": 42,
"city": ["Perth", "Melbourne"],
"Status": null
}
"""
Explanation: This code converts a JSON string into a Python dictionary using `json.loads()`.
The dictionary is then modified and written back to a JSON file using `json.dump()`.
Explanation: This example reads an Excel file into a Pandas DataFrame using
`pandas.read_excel()` and writes it back to another Excel file using `to_excel()`.
import csv
file_ptr.close()
Explanation: In this example, the `csv.DictReader()` reads the CSV file row by row. Each row
is returned as an OrderedDict, where the keys correspond to the column headers. The `for`
loop iterates over each row, allowing you to access the data by field names (headers). This
method is useful for structured CSV files where each column represents a specific attribute,
such as 'Name', 'Age', and 'Score'.
Key points:
• The first row of the CSV file must contain the headers (field names).
• The values in the dictionary can be accessed by their respective header names (e.g.,
`each_row['Name']`).
• This method simplifies accessing specific fields in CSV rows without needing to
manage index positions manually.
• **Abstraction**: Simplifies complex logic by hiding unnecessary details and showing only
essential features.
3. Creating a Class
A class serves as a blueprint for creating objects. It defines the structure (attributes and
methods) that will be shared by all objects created from that class.
Example:
class Pet:
"""A simple class to represent a pet."""
Explanation: In this example, we define a `Pet` class with two attributes: `species` and
`breed`. The `__init__` method is called when an object is instantiated and is used to initialize
the object's attributes.
4. Instantiating an Object
Once a class is defined, you can create instances (objects) of that class by calling it like a
function.
Example:
my_pet = Pet("Dog", "Pug")
Explanation: Here, `my_pet` is an instance of the `Pet` class, and it represents a dog of the
breed 'Pug'.
5. Object Methods
Methods are functions defined within a class that operate on instances of the class. They can
access and modify an object's attributes.
Example:
class Student:
def __init__(self, first_name, last_name, student_number):
self.first_name = first_name
self.last_name = last_name
self.student_number = student_number
def full_name(self):
return f"{self.first_name} {self.last_name}"
Explanation: In this example, the `full_name()` method combines the `first_name` and
`last_name` attributes and returns the full name of the student.
6. Accessor Methods (Getters)
Accessor methods, or getters, are used to retrieve the value of an attribute while
maintaining encapsulation.
Example:
def get_first_name(self):
return self.first_name
Explanation: This accessor method returns the value of the `first_name` attribute.
Example:
def set_first_name(self, first_name):
self.first_name = first_name
8. Static Methods
Static methods do not operate on class attributes or require an instance of the class. They
are typically used as utility or helper functions within a class.
Example:
@staticmethod
def greeting():
return "Hello, world!"
9. Inheritance
Inheritance allows a class to inherit attributes and methods from another class. This
promotes code reuse by creating specialized subclasses from more general classes.
Example:
class Programmer(Student):
def __init__(self, first_name, last_name, student_number, language):
super().__init__(first_name, last_name, student_number)
self.language = language
def __str__(self):
return f"{self.first_name} {self.last_name} ({self.language})"
Example:
class Lecture:
def __init__(self, students, lecture_name):
self.students = students
self.lecture_name = lecture_name
def number_of_students(self):
return len(self.students)
Explanation: In this example, the `Lecture` class contains a list of `Student` objects as one of
its attributes, demonstrating aggregation.