0% found this document useful (0 votes)
5 views44 pages

Python Functions and Data Structures Guide

This document provides an overview of basic Python programming concepts, including functions, data structures (lists, dictionaries, and tuples), control flow, loops, and the use of modules and packages. It emphasizes the importance of functions for code reusability and maintainability, and explains the characteristics and methods associated with different data structures. Additionally, it covers conditional logic and iteration techniques to control program flow effectively.

Uploaded by

waktubrown32
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Python Functions and Data Structures Guide

This document provides an overview of basic Python programming concepts, including functions, data structures (lists, dictionaries, and tuples), control flow, loops, and the use of modules and packages. It emphasizes the importance of functions for code reusability and maintainability, and explains the characteristics and methods associated with different data structures. Additionally, it covers conditional logic and iteration techniques to control program flow effectively.

Uploaded by

waktubrown32
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Nawasena Team

Basic Python Programming


Understanding
Data Structure
and Control Flow
Nawasena Team

What is Function in Python? Why Use It?

A function is an organized and Reusability: The “Don't Repeat


reusable block of code used to Yourself” principle. Write once,
perform a single related action. use many times.
Functions provide better modularity Decomposition: Breaking down
and a high level of code reuse. complex problems into smaller,
more manageable parts.
Maintainability: Code that is
easier to read, debug, and
update.
Nawasena Team

Structure Function
Key Components

def: Keyword for defining a


function.
Parameters: Input variables
(optional) in parentheses.
Docstring: Function
documentation (optional).
Body: Block of code that is
executed.
Return: Returns a value to the
caller (optional). If none is
specified, returns None.
Nawasena Team

Function Scope
Local vs Global
Variables defined within a function. Variables defined in the main body of
They can only be accessed within the script. Can be accessed
that function. They disappear after anywhere. Alternatively, you can use
the function finishes. the GLOBAL keyword to make a
variable global.
Nawasena Team

Flexible Parameters: *args & **kwargs


*args (Non-Keyword) vs **kwargs (Keyword)
Allows the function to accept an Allows the function to accept an
unlimited number of positional unlimited number of keyword
arguments. arguments.

Data is received as a Tuple. Data is received as a Dictionary.


Nawasena Team

Example of *args Implementation


*args (Non-Keyword)
The sum_all function takes a number of arguments and
returns their sum. When called with sum_all(1,2,3), the
result is 6.

Here we see a real example of the power of *args.


Notice the *args parameter. The asterisk acts like a
vacuum that sucks up all the numbers we enter,
whether it's 3 numbers, 10 numbers, or 100 numbers,
and compresses them into a single Tuple package. This
is what makes this function so flexible; we don't need to
define a, b, c manually.
Nawasena Team

Example of **kwargs Implementation


**kwargs (Keyword)
The user_profile function accepts flexible parameters
via kwargs, then prints each key and value as user
profile data.

If *args handles lists of numbers, **kwargs handles data


that has labels or names. Take a look at this code: we
enter user data such as name, role, and location.

Thanks to kwargs, this function doesn't care whether we


send 3 pieces of data or 10 pieces of data, as long as
there are labels. Behind the scenes, Python converts
this input into a Dictionary, so we can process it using
standard dictionary methods such as .items() to display
it one by one.
Nawasena Team

Lambda Expressions
Anonymous Function
Lambda is a small, unnamed function (anonymous).
Lambda can have multiple arguments but only one
expression.

Syntax

Very useful when you need a short function for a short


period of time, often used as an argument for higher-
order functions (such as map or filter).
Nawasena Team

Example lambda Implementation


Filter() Map() Sorted()
Filter elements from the list. Modify each element. Customize the sort key.
Nawasena Team

Data Structure in Python is a way to


Data Structure store, organize, and manage data so
it can be accessed and processed
efficiently.

List Dictionary Tuple


List is used to store multiple items in Dictionary is ordered, mutable (can Tuple is used to store multiple items
a single variable. Lists are created be changed), and does not allow in a single variable, similar to a list.
using square brackets ([]). Their duplicate keys. The values in a Unlike lists, tuples use parentheses
characteristics include being ordered, dictionary are accessed by referring (()). Tuples are ordered, immutable
mutable (can be changed), allowing to the key associated with the value (cannot be changed), and allow
duplicate values, and supporting any you want to retrieve. duplicate values. The contents of a
data type within the same list. The tuple follow index positions, where
contents of a list follow index the first item is index [0], the second
positions, where the first item is is index [1], and so on.
index [0], the second is index [1], and
so on.
Nawasena Team

Item 1 Item 2 Item 3 Item 4


1. Python Lists
tem 1

em 2 Ordered, mutable collections of items. The bread and butter of


Python data science.
em 3

em 4

0 5 10 15 20
1. Python Lists
List Methods: Adding Elements

Method Description Code Example

fruits = ['apple']
Adds an item to the end of
append(x) [Link]('banana')
the list.
# ['apple', 'banana']

Extends the list by nums = [1, 2]


extend(iterable) appending all items from [Link]([3, 4])
the iterable. # [1, 2, 3, 4]

data = ['a', 'c']


Inserts an item at a given
insert(i, x) [Link](1, 'b')
position i.
# ['a', 'b', 'c']
1. Python Lists
List Methods: Removing Elements

Method Description Code Example

Removes the first item vals = [10, 20, 10]


remove(x) from the list whose value is [Link](10)
equal to x. # [20, 10]

stack = [1, 2, 3]
Removes & returns item at
pop([i]) item = [Link]()
pos i (default last).
# item is 3, stack is [1, 2]

logs = ['err1', 'err2']


Removes all items from the
clear() [Link]()
list.
# []
1. Python Lists
List Methods: Utility

Method Description Code Example

Returns zero-based index l = ['a', 'b']


index(x)
of first item equal to x. idx = [Link]('b') # 1

Returns the number of l = [1, 1, 2]


count(x)
times x appears in the list. c = [Link](1) # 2

Sorts the items of the list in n = [3, 1, 2]


sort()
place. [Link]() # [1, 2, 3]

Reverses the elements of n = [1, 2, 3]


reverse()
the list in place. [Link]() # [3, 2, 1]
1. Python Lists
List Methods: Adding Elements

Method Description Code Example

Returns zero-based index l = ['a', 'b']


index(x)
of first item equal to x. idx = [Link]('b') # 1

Returns the number of l = [1, 1, 2]


count(x)
times x appears in the list. c = [Link](1) # 2

Sorts the items of the list in n = [3, 1, 2]


sort()
place. [Link]() # [1, 2, 3]

Reverses the elements of n = [1, 2, 3]


reverse()
the list in place. [Link]() # [3, 2, 1]
Nawasena Team

Item 1 Item 2 Item 3 Item 4


2. Dictionaries
tem 1

em 2 Key-Value pairs designed for fast lookups. Essential for handling


JSON data and configurations.
em 3

em 4

0 5 10 15 20
2. Python Dictionary
Dictionary: Access Methods

Method Description Code Example

d = {'a': 1}
Returns value for key k, or
get(k, d) val = [Link]('b', 0)
default d if not found.
# val is 0

d = {'a': 1, 'b': 2}
Returns a view object
keys() k = list([Link]())
displaying a list of all keys.
# ['a', 'b']

Returns a view object


v = list([Link]())
values() displaying a list of all
# [1, 2]
values.

Returns a view object


i = list([Link]())
items() displaying a list of (key,
# [('a', 1), ('b', 2)]
value) tuples.
2. Python Dictionary
Dictionary: Modification Methods

Method Description Code Example

Updates the dictionary d = {'a': 1}


update(other) with elements from [Link]({'b': 2})
another. # {'a': 1, 'b': 2}

Removes key k and returns val = [Link]('a')


pop(k)
its value. # val is 1, d is {'b': 2}

Removes and returns the


pair = [Link]()
popitem() last inserted (key, value)
# ('b', 2)
pair.
2. Python Dictionary
Dictionary: Utility Methods

Method Description Code Example

Returns a shallow copy of


copy() new_d = old_d.copy()
the dictionary.

Returns value of k. If not d = {}


setdefault(k, d) present, inserts k with v = [Link]('x', 10)
value d. # d is {'x': 10}, v is 10

Creates a new dictionary d = [Link](['a', 'b'],


fromkeys(seq, v) with keys from seq and 0)
value v. # {'a': 0, 'b': 0}
2. Python Dictionary
Dictionary: Utility Methods

Method Description Code Example

Returns a shallow copy of


copy() new_d = old_d.copy()
the dictionary.

Returns value of k. If not d = {}


setdefault(k, d) present, inserts k with v = [Link]('x', 10)
value d. # d is {'x': 10}, v is 10

Creates a new dictionary d = [Link](['a', 'b'],


fromkeys(seq, v) with keys from seq and 0)
value v. # {'a': 0, 'b': 0}
Nawasena Team

Item 1 Item 2 Item 3 Item 4


3. Tuples
tem 1

em 2 Immutable, ordered sequences. Perfect for fixed data records.


em 3

em 4

0 5 10 15 20
3. Tuple
count(x)
The count() method in a tuple is used to return the number of times a specified value
appears in the tuple.
Here are its key characteristics:
Returns an integer representing the frequency of the element.
Returns 0 if the element is not found (unlike index(), which raises an error).
It searches through the entire tuple to find all matches.
3. Tuple
index(x)
The index() method searches for a
specified element within a tuple and
returns the position (index) of its first
occurrence.
Key Characteristics:
Zero-based: The count starts at 0
(the first item is index 0).
First Match Only: If the item
appears multiple times, it only
returns the position of the first
one.
Error Handling: It raises a
ValueError if the item is not
found in the tuple.
Conditional Logic
Control the flow of your program with if, elif, and else statements.
1. If
The if statement is the most basic form of decision-making in Python. It allows the program to run a block
of code only if a specific condition is True.
How it works:
Python checks the condition.
If True: It executes the indented code block.
If False: It skips the indented block entirely and continues with the rest of the program.
2. If Else
The if-else statement is used when you want the program to choose between two specific options. It
guarantees that one block of code will run.
How it works:
The Check: Python evaluates the condition.
True Path: If the condition is True, the code inside the if block is executed.
False Path: If the condition is False, the code inside the else block is executed.
Unlike the simple if statement (which might do nothing), the if-else statement ensures an action is taken
either way.
3. If - Elif - Else
The if-elif-else statement is used for decision-making in Python. It allows the program to execute different
blocks of code based on specific conditions.
if: This is the first condition. The program checks this first. If it is True, it runs the code inside and
skips the rest.
elif (else if): This stands for "else if." It is only checked if the previous if (or elif) condition was False.
You can have multiple elif blocks.
else: This is the fallback option. It runs only if all previous conditions were False. It catches
everything that didn't fit the specific criteria.
4. Nested If
A Nested IF is simply an if statement placed inside another if statement.
Think of it like a building with multiple security doors. You must pass through the main entrance (the
Outer IF) before you can even try to open the specific room door (the Inner IF).
Key Characteristics:
Hierarchical Check: The inner condition is only checked if the outer condition is True.
Granular Control: It allows for very specific decision-making paths.
Outer vs. Inner: If the outer condition is False, the inner code block is completely ignored
Loops & Iteration
Automate repetitive tasks with For and While loops.
1. While Loop
he while loop is a control flow statement that allows code to be executed repeatedly as long as a specific
condition is True.
Key Characteristics:
Condition-Based: Unlike a for loop (which counts through a list), a while loop runs based on a
True/False state.
Pre-Check: The condition is checked before the code runs. If it starts as False, the code never runs.
Infinite Loop Risk: You must ensure the condition eventually becomes False (usually by updating a
variable inside the loop), otherwise, the loop will run forever and crash the program.
2. For Loop
he while loop is a control flow statement that allows code to be executed repeatedly as long as a specific
condition is True.
Key Characteristics:
Condition-Based: Unlike a for loop (which counts through a list), a while loop runs based on a
True/False state.
Pre-Check: The condition is checked before the code runs. If it starts as False, the code never runs.
Infinite Loop Risk: You must ensure the condition eventually becomes False (usually by updating a
variable inside the loop), otherwise, the loop will run forever and crash the program.
3. Nested Loop
It is simply a loop inside another loop.
Key Rule
"For every 1 step of the Outer Loop, the Inner Loop runs completely from start to finish."
Total Iterations = Outer Loop Count $\times$ Inner Loop Count.
4. Loop Control (break)
The break statement is used to terminate (stop) the loop entirely. When Python encounters break, it exits
the loop immediately, regardless of whether the loop condition is still true.
4. Loop Control (continue)
The continue statement is used to skip the rest of the current iteration. Instead of stopping the whole
loop, it jumps back to the top to start the next iteration.
4. Loop Control (pass)
The pass statement is a null operation. It does nothing. It is used as a placeholder when the syntax
requires a line of code, but you don't want any command to execute yet.
MODULE, PACKAGE, & LIBRARY
WHAT IS MODULE? PURPOSE OF USING MODULES

A Module is a Phyton file (.py) that contains a Breaking large programs into smaller logical
collection of: parts
Functions Reducing code duplication
Classes Improving readability and maintainability
Variables Facilitating teamwork on large projects

Modules can make programs more structured,


easier to maintain, and reusable.

WHAT IS A PACKAGE? WHAT IS A LIBRARY?

A Package is a folder containing several A collection of functions and code in the form of
modules. many modules/packages
It functions to group modules based on specific Usually for a specific purpose (e.g. data science,
categories/tasks images, web, etc.)
Requires an __init__.py file to be recognized as a Examples of Library: Pandas, NumPy, Matplotlib,
package etc.
BENEFITS OF
MODULES & PACKAGES
TECHINCAL BENEFITS PRACTICAL BENEFITS

Modularity Facilitates team collaborations


Code is separated by function
More professional project structures
Reusability
Modules can be used across multiple Easier debugging due to separate
projects functions

Maintainability Supports iterative development


Easier to repair or expand

Scalability
Suitable for large applications
IMPLEMENTATION OF MODULES AND
PACKAGES
Section Function

Import os Using the os module to create folders/files

[Link](“geometry”) Creates a package folder

__init__.py To treat the folder as a package

[Link] Module contains the area function

import [Link] Import the module

[Link] (4) Executes the function


STRING MANIPULATION IN PHYTON
DEFINITION
String manipulation is the process of changing, modifying, and managing text using various Python
functions and methods.
Strings in Python are always enclosed in quotation marks: "..." or '...'.

REPLACE CONCATENATE
Used to replace certain words or characters in a string. Concatenate means to combine two or more strings.
Usually, the + operator is used.
STRING MANIPULATION IN PHYTON
LEN JOIN
Counts the number of characters in a string. Used to combine list elements into one string, with a
specific separator.

SPLIT
Used to split a string into a list, based on a specific
FORMAT
separator. Used to create dynamic strings by inserting variables.
NUMPY

WHAT IS NUMPY? WHY USE NUMPY?

NumPy (Numerical Phyton) is a library Faster and more efficient than regular
for numerical computing Phyton lists

One of the essential skills to master in Support multi-dimensional data


data science, especially during the data structure (1D, 2D, 3D)
preparation stage
Contains built-in mathematical,
NumPy ability to perform multidi- statistical, and algebra functions
mensional array operations more quickly
and efficiently.
NUMPY ARRAY
NumPy arrays can store integers, floating-point numbers, booleans, or complex numbers.
However, the data type must be homogeneous (only one data type is allowed).

[Link]()
To convert a Python list into an array

single-dimensional array

[Link]()
To display an array with values spaced at specific intervals

two-dimensional array

[Link]()
To generate a new array of a specified size filled with zeros

three-dimensional array

[Link]()
To generate a new array of a specified size filled with ones
MANIPULATE NUMPY ARRAY
Reshape Concatenate
To make an array without change the data Used to combine two or more arrays that have the same
shape

Flatten Stack
Used to display an array as a single-dimensional array Used to join a sequence of NumPy arrays along a new axis

Transpose Split
Used to reshape an array without altering its data by Used to split a 1-D array into multiple subarrays
transposing the positions of its rows and columns
MANIPULATE NUMPY ARRAY
Resize Delete
Used to reshape an array into a specified size Used to delete values from an array along a given axis
before a specified index

Append Unique
Used to append values at the end of an arrayUsed to Used to find unique elements within an array
append values at the end of an array

Insert Slicing
Used to insert values into an array along a given axis before a Used to retrieve elements from one index to another
specified index

You might also like