Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Data Analysis Bootcamp Week 1 Study Note

Uploaded by

Josh O. Owo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Data Analysis Bootcamp Week 1 Study Note

Uploaded by

Josh O. Owo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

We're excited to offer a bootcamp for beginners on programming

with Python. These weekly hands-on sessions will run from Sep
17-Oct 15, 2024, Tuesdays, 11 am EST (or 4 pm WAT, 5 pm SAST, or 6
pm EAT). Sign up here: https://chi2.io/Wp8g9BRo

Introduction to Python
Python is one of the most widely used programming languages globally,
known for its simplicity and versatility. Developed in the early 1990s, Python
can be applied to various domains, from automating simple tasks to building
complex machine learning models. It’s especially favored by researchers, data
scientists, and engineers due to its easy-to-read syntax and an extensive array
of open-source packages that make development more efficient.

Simple Explanation of Terminology:

Programming is a way of communicating with computers. Just as we use


languages like English or French to converse with each other, programming
languages have their own sets of rules and syntax that allow us to instruct
computers. By writing code in these languages, we give computers clear,
understandable commands to perform specific tasks. Statistical software like
Stata, SPSS, and SAS also utilizes programming but is designed specifically for
statistical analysis. Think of them as specialized calculators that come with
pre-set functions for different types of calculations and analyses. Python, as a
programming language, is more general-purpose and can do much more
than just statistical analysis.
Benefits of Learning Python:

● Easy-to-read syntax: Python’s syntax is designed to be clear and


straightforward, which helps beginners quickly grasp the fundamentals
of programming.
● Cross-platform compatibility: Python applications can run on various
operating systems like Windows, macOS, and Linux without major
changes.
● Rich ecosystem: With a vast collection of libraries and frameworks
available, Python enables faster development across areas like web
development, data analysis, automation, and artificial intelligence.
● Active community: The Python community is both large and
supportive, providing a wealth of resources, documentation, and
tutorials for newcomers.

Use Cases and Applications:

● Web development: With frameworks like Django and Flask, Python is


often used to develop robust and scalable web applications.
● Data science and machine learning: Python libraries such as Pandas,
NumPy, and TensorFlow make it a go-to choice for data analysis,
machine learning, and AI.
● Automation: Python scripts are commonly used to automate repetitive
tasks like data extraction and file handling.
● Scientific computing: Researchers and scientists frequently employ
Python to model complex problems and run simulations.

Simple Explanation of Terminology:

Framework: A framework is like the foundation and blueprint of a house. It


gives you the main structure—walls, floors, and rooms—so you don’t have to
figure out how to build everything from scratch. You just follow the
framework's plan, but you still get to decide how to decorate or organize the
rooms.

Library: A library is like your toolbox full of handy gadgets for building or
maintaining the house. Need a hammer to hang a picture or a screwdriver to
fix a door? You don’t have to make these tools yourself—they’re ready to go
when you need them for specific tasks. You can think of libraries in
programming as similar to Excel functions like SUM(), VLOOKUP(), IF(), which
are all pre-built tools that you can use to perform specific tasks in your
spreadsheet without needing to write complex formulas yourself. Similarly,
libraries in programming are collections of pre-written code (functions,
classes, etc.) that you can use to perform specific tasks in your program
without writing everything from scratch.

Script: A script is like a set of instructions or a checklist for a home project. It


tells you exactly what to do step by step—like painting a wall or assembling
furniture. The script helps you complete one specific task, following it exactly
as written. We use the word 'scripts' in programming similar to how we use
'SMS' in communication. Just like an SMS refers to a brief message containing
text, a script in programming refers to a set of instructions written to perform
specific tasks. Both are typically straightforward and to the point: SMS delivers
a message, while a script executes commands in a program

Running Python Code:

Python is an interpreted language, meaning code is executed directly by an


interpreter, without the need for compilation. This makes the edit-test-debug
process faster. To run Python code, you need a Python runtime environment,
which you can set up easily on your machine.

Simple Explanation of Terminology:

Think of compiled languages and interpreted languages like cooking recipes:


● Compiled languages, like C++, are like following a recipe that has been
fully written and finalized into a single book (a cookbook). You gather all
the ingredients, carefully prepare everything according to the book, and
once it's ready, you cook the entire meal in one go. The final dish is
prepared, and it works perfectly. However, if you realize you missed
something, you have to go back, edit the book, and recompile it into a
new edition before cooking again. This is efficient for large batches but
takes time to prepare.
● Interpreted languages, like R and Python, are more like cooking with a
chef standing next to you, giving you step-by-step instructions in real
time. The chef says, "Chop the onions," and you do it. Then, "Add them
to the pan," and you follow that instruction. If you make a mistake, the
chef can immediately correct it, but the process might be a bit slower
than having the whole recipe prepared in advance. This approach
allows for flexibility and quick feedback during the cooking process.

Python as an object-oriented
language
Learning Python is like learning a regular language. You have to learn the
nouns (names of person, place or thing), the verbs (action words), and
punctuation (syntax).

The way nouns and verbs are used in English is not very different from how
we use them in programming. Refresh your memory of nouns and verbs with
the images below:
Similarly, everything in Python can be roughly classified as either a “noun”
(the thing that receives the action), or a verb (the thing doing the action).

We call the nouns “objects”, while the verbs are called “functions”.

Examples of objects include variables in your dataset. All variables in this


world can be grouped into six classes discussed below.

Types of variables
There are 6 different types of variables we need to be aware of before we can
start writing code.

#1. Numeric (int, float)

Simple Explanation: Think of a calculator or a number line with whole


numbers (like 1, 2, 3) and fractions (like 1.5 or 2.75). We call whole numbers
integers, abbreviated as “int”, and these could be negative or positive, while
numbers with fractions are called “floats”. The value of pi is an example of a
numeric value.
#2 String (str)
Simple Explanation: This is like spelling out words with letter blocks. A string
stores characters (like letters or combination of letters and numbers fittingly
called “alphanumeric”. A “string” and "character" are related in that a
character is a single letter, digit, or symbol, like 'A', '5', or '$' whereas a string is a
sequence of characters put together, like "Hello!" or "123abc".

#3 Sequence (list, tuple)


A sequence, which can either be a list or a tuple, is an ordered collection of
objects that can be of any data type, including other lists. Think of how onion
layers are well ordered inside an onion bulb.
The term “tuple” follows a rhyming pattern: single, double, triple, quadruple,
and so on up to “n-tuple”, with names from Latin numbers. Just as these
terms follow a fixed sequence, tuples in programming use round brackets
()—think of them as a 'closed circle,' which represents something
unchangeable and complete. This shows that tuples are immutable; once
created, they can't be altered. In other words, you cannot change the
contents of a tuple once it is created. On the other hand, lists use square
brackets [], similar to a 'shopping list' with checkboxes, where you can easily
add, remove, or change items. This reflects the flexible nature of lists, which
can be modified as needed.

#4 Mapping (dict)
A dictionary is like a real dictionary where you have words (keys) and their
meanings (values). In Python, you match things, like matching a name to a
phone number. You can also think of it as matching a key to a keyhole. Since
the curly bracket { } looks like a keyhole, it is used to hold the values of a
key-value pair.

Think of a dictionary as a collection of labeled boxes. Each box (or key) has a
label, and inside each box is the value associated with that label. For example:
● "name": "John" means the box labeled name contains the value John.
● "age": 30 means the box labeled age contains the value 30.
● "city": "New York" means the box labeled city contains the value New
York.

In the format key: value, the key (like "name", "age", or "city") always comes
before the colon, telling you what kind of information is inside the box, and
the value (like "John", 30, or "New York") comes after the colon, which is the
actual information inside the box.

And it’s all stored inside curly braces {}, like a neat little collection of labeled
boxes that you can look inside whenever you need that information.

So, for the example person = {"name": "John", "age": 30, "city": "New York"}, it’s
like saying, "I have a person, and here are three labeled boxes: one for their
name, one for their age, and one for their city."

#5 Boolean
It’s like flipping a light switch: it’s either on (True) or off (False)—just two
choices!
#6 Set

A set is like a messy, scattered room where toys and objects are randomly
placed everywhere. Since the items are not in any particular order, you can’t
say, "Give me the fourth item," because there’s no fixed order like in a tidy line.
In Python, this is why we can't use indexing with sets, unlike with lists where
items are neatly arranged, and you can easily ask for the first or fourth item.
Sets only care about having unique things, not where they are!

Think of a set in Python like a Venn diagram. A Venn diagram shows groups of
unique items, and each group is inside its own circle. The things inside the
circles are all unique, just like in a Python set where no item repeats.

Now, the curly brackets { } are like the borders around these groups in Python.
They tell us that everything inside belongs to the same set, just like how the
circle in a Venn diagram contains all the items in a group.

So, whenever you see { }, picture it like a circle around a group of unique
things, just like in a Venn diagram!
Python Installation Guide

Step 1: Check if Python is Already Installed

Before installing Python, check if it's already installed on your system:

● Open your terminal or command prompt.

Steps to open terminal or command prompt:


● For Windows Users - Press Win + R, type cmd, and hit Enter.

Hitting ENTER or OK should give you the output below:


● For Mac Users - You can easily search for terminal on the
Launchpad.
● After double clicking on the Terminal icon and typing the input
provided:

Type the following command:

python --version

In the command python --version, the word "version" should be in lowercase


because command-line options are generally case-sensitive. Additionally, the
command must include a space between python and --version.

Step 2a: Download Python Installer

If Python is not installed, you can easily download it from the official Python
website.

● For Windows Users: Download Python for Windows


● For Mac Users: Download Python for macOS

Step 2b: Run the Python Installer


● Run the downloaded installer.

● For Windows Users -


○ Important: Select both checkboxes at the bottom (including "Add
Python to PATH") before clicking "Install Now."
○ Allow it to make changes to your computer.
● For Mac Users - Simply follow the installation prompts.

Step 2c: Complete the Installation

● After clicking "Install Now," the installation process will begin.


● Wait for a few minutes until the installation completes.
● Once done, you should see a confirmation screen that the installation
was successful.
Step 2d: Verify Python Installation

To confirm that Python was successfully installed:

● Open your terminal or command prompt again.

python --version

● You should see the version of Python that was installed displayed on
the screen.
Quick Guide to Download and Install Anaconda

Even after installing Python, you may want to install Anaconda because it
simplifies working with data science tools. Anaconda comes with many
pre-installed libraries like NumPy, pandas, and Jupyter, which you’d otherwise
have to install separately. With Anaconda, you get a complete setup for data
science, including popular tools like Jupyter Notebook and Spyder, all in one
simple installation. This makes it a great choice for beginners looking for an
all-in-one solution. This is like buying a toolkit that already has all the tools you
need, instead of buying each tool one by one.

● Download Anaconda from this link


● Choose the installer for your operating system (Windows, macOS

● After installation, open the setup, run the Installer and simply follow the
installation prompts.

Starting Jupyter Notebook After Installing Anaconda

Next step is to open jupyter notebook application:

● On Start Menu or Launchpad, search for “Anaconda Navigator”, select


Anaconda Navigator from the search results and open it
● Once Anaconda Navigator is open, under the "Home" tab, find the
Jupyter Notebook option.

● Click on the "Launch" button next to Jupyter Notebook.


● A browser window will open with the Jupyter Notebook interface.

Create a New Notebook:

● In the Jupyter Notebook interface, click on New> NoteBook in the


top-right corner and choose Python 3 (or whichever version you're
using).
● A new notebook will open, and you can start coding.
Some basic rules in Python
#1 Variables and Assignment

Variables are a fundamental aspect of programming in Python. They act as


containers that store data values, which can be easily referenced and
manipulated. In Python, variables are dynamically typed, meaning you don't
need to declare a type before using a variable. Instead, Python determines the
type based on the value assigned.

To assign a value to a variable, use the assignment operator =. The variable is


on the left side, while the value or expression is on the right side.

x=1 # x is assigned the value 1

y=x+5 # y is assigned the value of x plus 5

z=y # z is assigned the value of y

In this example, Python automatically recognizes the variables x, y, and z as


integers. Python allows the use of various data types with no need for explicit
type declaration.

#2 Python Variable Naming Convention

A variable in Python can have a short name (e.g., x or y) or a more descriptive


name (e.g., height, distance, or total_income). Here are the rules for naming
variables in Python:

● A variable name must begin with a letter or an underscore (_).


● It cannot begin with a number.
● A variable name can only include letters, numbers, and underscores
(A-Z, 0-9, and _).
● Variable names are case-sensitive, so age, Age, and AGE are considered
different variables.
● You cannot use Python reserved keywords as variable names.

#3 Comments
In Python, you can add comments to your code for documentation purposes.
Comments help explain your code to others (or yourself) when you revisit it
later.

A comment starts with a #, and everything after the # on that line will be
ignored by Python.

#4 Python Data Types (Refresher)

In programming, data types define the kind of data that a variable can hold.
For example:

age = 30

Here, the integer value 30 is assigned to the variable age, making its data type
int.

Overview of Basic Python Data Types

Data Class Description


Type

int, float
Numeric Holds numbers (integers, decimals)

String str Stores a sequence of characters

list, tuple
Sequenc Contains ordered collections of
e items
Mappin dict Stores key-value pairs
g

Boolean bool Represents True or False

Set set Stores unique, unordered items

Since Python is an object-oriented language, all data types are implemented


as classes, and variables are instances (objects) of these classes.

Python Numeric Data Types

Python’s numeric data types include integers, floats (decimals), and complex
numbers:

● int: Represents whole numbers without a fractional component.


● float: Represents real numbers with a decimal point.

You can check the data type of a variable using the type() function:

a = 10

print(type(a)) # Output: <class 'int'>

b = 3.14

print(type(b)) # Output: <class 'float'>

Here, a is an integer, and b is a float.


Python List Data Type

A list is an ordered collection of items that can hold different data types. Items
in a list are enclosed in square brackets [ ] and separated by commas:

fruits = ["apple", "banana", "cherry"]

You can access elements using their index:

print(fruits[0]) # Output: apple

print(fruits[2]) # Output: cherry

Lists are mutable, meaning you can modify their elements after they are
created.

Python Tuple Data Type

Tuples are similar to lists but are immutable—once defined, their elements
cannot be changed. They are defined using parentheses ():

dimensions = (1920, 1080)

Like lists, tuple elements can also be accessed using their index:

print(dimensions[0]) # Output: 1920


Python String Data Type

Strings are sequences of characters enclosed within single (') or double (")
quotes:

name = "Alice"

message = 'Hello, Python!'

You can concatenate strings using the + operator:

greeting = "Hello" + " " + "World!"

print(greeting) # Output: Hello World!

Python Set Data Type

A set is an unordered collection of unique items, defined by curly braces {}:

unique_numbers = {1, 2, 3, 4, 4}

print(unique_numbers) # Output: {1, 2, 3, 4}

Sets do not allow duplicate values, and their elements cannot be accessed via
indexing.

Python Dictionary Data Type

Dictionaries store data in key-value pairs. Keys are unique, and values can be
of any data type. They are defined using curly braces {}:

person = {"name": "John", "age": 30, "city": "New York"}


Access values using the corresponding key:

print(person["name"]) # Output: John

Type Conversion and Casting


in Python
In Python, type conversion refers to changing the data type of a variable or a
value into another data type. There are two main types of conversion:

1. Implicit Type Conversion


2. Explicit Type Conversion (Casting)

#1. Implicit Type Conversion

Python automatically converts one data type to another when it makes sense
to do so. This process is known as implicit conversion. For example, if you add
an integer and a float, Python will automatically convert the integer to a float
to perform the operation.

Example:

x=5 # int

y = 2.5 # float

result = x + y # Python automatically converts `x` to a float

print(result) # Output: 7.5

print(type(result)) # Output: <class 'float'>


In this example, the integer 5 is implicitly converted to a float so that the
addition with 2.5 (a float) can be performed.

#2. Explicit Type Conversion (Casting)

Explicit conversion or casting is when you manually convert one data type to
another using built-in functions like int(), float(), str(), etc.

Common Type Casting Functions:

● int(): Converts a value to an integer.


● float(): Converts a value to a float.
● str(): Converts a value to a string.

Example:

# Convert float to int

a = 7.8

b = int(a) # Explicitly converting float to int

print(b) # Output: 7

# Convert int to string

num = 10

text = str(num) # Explicitly converting int to string

print(text) # Output: '10'

print(type(text)) # Output: <class 'str'>


In the above examples:

● The float value 7.8 is explicitly converted to an int, which results in 7 (the
decimal part is truncated).
● The integer 10 is converted to a string '10'.

Example with user input:


The input function in Python is used to get information from the user. When
you use input("message"), it shows the message to the user and waits for
them to type something. The text they type is then saved in a variable.

For example, if you use input("Please enter your age: "), it will display
"Please enter your age:" and wait for the user to type their age.

In real life, this function is useful whenever you need to get information from
someone using a computer program. For instance, a program might ask for a
user's name, age, or any other details. The input function helps make
interactive programs that can respond to what the user provides.

When accepting input from a user, Python reads the input as a string by
default. To work with numerical data, you need to explicitly convert the input
to the desired data type.

age = input("Please, enter your age: ") # Returns a string

age = int(age) # Convert the input string to an integer


Type Conversion with Collections

A collection is simply a data structure that groups multiple items together


in a single container for easier storage, access, and manipulation. We
already discussed some of the main collections earlier, and they are
summarized below:

Duplica Access
Collection Ordered Mutable tes Type Use cases

Use a list when you need to maintain the order


of items and need to modify (add, remove, or
update) elements frequently, such as
List Yes Yes Yes Index managing a to-do list or storing user inputs.
Use a tuple when you need to store an ordered
set of items that should not change
(immutable), such as coordinates (x, y), or data
that is fixed for the duration of the program like
Tuple Yes No Yes Index constants or database records.

Use a set when you need to ensure all


elements are unique and don’t care about the
Not order, such as when managing a collection of
Set No Yes No applicable tags or filtering duplicate entries in a dataset.

Use a dictionary when you need to store data


as key-value pairs and want to quickly look up
values by their key, such as mapping
No (for Key (for usernames to user profiles or counting
Dictionary No Yes keys) values) occurrences of words in a text.

You can also convert between different collection types like lists, tuples, and
sets.

👀Example 1: Convert list to tuple


# Convert list to tuple

fruits = ["apple", "banana", "cherry"]

fruits_tuple = tuple(fruits)

print(fruits_tuple) # Output: ('apple', 'banana', 'cherry')

💡Proof of proper conversion: We should be able to modify the list “fruit” since
a list is modifiable. However, attempting to modify the tuple “fruits_tuple”
should give us an error as a tuple is not modifiable:
So the operation for the list was a success as we were able to add “mango” to the end.
Now, let’s convert the list to a tuple and attempt doing the exact same thing. It should give us an
error.

👀Example 2: Convert set to list


# Convert set to list

num_set = {1, 2, 3}

num_list = list(num_set)

print(num_list) # Output: [1, 2, 3]

💡Proof of proper conversion: We should be able to index (i.e., reaching out to


pick or reference something at a specific location) to an item in a specific
position in the list “num_list” since a list is indexable. However, attempting to
index the set “num_set” should give us an error as a set is not indexable:
As seen above, the set throws an error when you attempt to index the item at position 0 (i.e., the
first item). Now, let’s convert the set to a list and repeat the same exercise to prove successful
conversion.

Now, we are able to successfully index the first item because of having successfully converted
the set to a list.

By using implicit and explicit type conversions, you can ensure that your code
handles different types of data efficiently and avoids type errors in Python.
Python List Operations and
Methods Explained as Arrays or
Vectors
A list is a versatile and mutable collection that can store multiple values, including different data
types, just like an array in other programming languages. Python lists allow indexing, slicing,
and various operations like adding or removing elements.

Key Concepts:

1. Indexing: Each element in a list is associated with an index, starting from 0.


○ Positive index: Starts from 0, moving left to right.
○ Negative index: Starts from -1, moving right to left.

2. Slicing: Lists can be sliced to access a range of elements.


○ Syntax: list[start:end]
Python Operators
In Python, operators are used to perform operations on variables and values.
Operators are categorized into several types:

1. Arithmetic Operators: Perform mathematical operations.


○ +: Addition
○ -: Subtraction
○ *: Multiplication
○ /: Division
○ %: Modulus (remainder after division)
○ **: Exponentiation (power of)
○ //: Floor division (division that results in an integer)

Example:
a = 10

b=3

print(a + b) # Output: 13

print(a ** b) # Output: 1000 (10 to the power of 3)

print(a // b) # Output: 3 (floor division)

2. Comparison Operators: Compare two 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 = 10
print(x == y) # Output: False

print(x < y) # Output: True

3. Logical Operators: Combine conditional statements.


○ and : Returns True if both statements are true
○ or: Returns True if one of the statements is true
○ not: Reverses the result, returns False if the result is true

Example:

a=5

b = 10

print(a < 10 and b > 5) # Output: True

print(not (a == b)) # Output: True

4. Assignment Operators: Used to assign values to variables.


○ =: Simple assignment
○ Augmented assignment operators

Augmented assignment operators are used to modify the value


of a variable in place by performing an operation and then
assigning the result back to the variable.

Operator Equivalent to Description

+= x=x+3 Add and assign

-= x=x-3 Subtract and assign


*= x=x*3 Multiply and assign

/= x=x/3 Divide and assign (floating-point division)

//= x = x // 3 Floor division and assign (integer division)

%= x=x%3 Modulus and assign (remainder)

**= x = x ** 3 Exponentiation and assign

Example:

x=5

x += 3 # Same as: x = x + 3

print(x) # Output: 8

💡 Note that one equal sign is used for assignment (e.g., X = 5,


meaning assign the value 5 to the object X), whereas two equal
signs is used for mathematical equivalence.

Python if/else Statements


The if statement is used to control the flow of a program based on a
condition. It executes a block of code if a condition is true, and optionally,
another block if the condition is false.

Basic if Statement:

age = 18
if age >= 18:

print("You are an adult.")

if/else Statement:

age = 16

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

if/elif/else:

You can use multiple conditions using elif (else if).

age = 17

if age < 13:

print("You are a child.")

elif age < 18:

print("You are a teenager.")

else:

print("You are an adult.")

Example with Logical Operators:


x=5

y = 10

if x < 10 and y > 5:

print("Both conditions are true.")

else:

print("One or both conditions are false.")

Summary:

● Use if to start the chain of conditions.


● Use elif to specify additional conditions to test if the initial if
condition is false.
● Use else as a final catch-all for cases where none of the if or elif
conditions are true.

elif allows you to handle multiple conditions more flexibly, while else
provides a default action when no other conditions apply.

Python Loops
Loops in Python allow you to execute a block of code repeatedly. There are
two main types of loops: “for” and “while”. Here is how to remember each:

● For = for each thing.


● While = while true, keep going.
for Loop: Used to iterate over a sequence (like a list, tuple, string, etc.).
Basic for Loop Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Looping through a range of numbers:

for i in range(5):

print(i) # Output: 0, 1, 2, 3, 4

while Loop: Repeats as long as a condition is true.

Basic while Loop Example:

count = 0

while count < 5:

print(count)

count += 1

Both for and while loops allow you to repeat a block of code multiple times.

💡Key structural difference between for and while loops and the implications
for infinite loop
When using a while loop, you must manually start it (initialize) and manually
end it (update with +1). Here is the importance of each:

1. Initialize: You must start by setting up the initial condition or variable


that the loop will use. This is like setting the starting point for your loop
to know where to begin. In our example above, we initialized by setting
count to 0. Note that this is done before we set the loop.
2. Update: Inside the loop, you need to make sure you change the
condition or variable in each iteration so that eventually the loop can
stop. This often means incrementing a counter or updating a condition.
If you don’t update this value, the loop could keep running forever,
which is called an infinite loop.

Once your code gets into an infinite loop, the only way to stop it is by
using brute force because the loop keeps running forever since the
condition is staying True forever, causing the infinite loop. In the above
example, this loop will keep printing 0 forever because the value of
count is never changed, and count < 5 will always remain True. This is
why we change the value of the loop variable inside the loop. In
contrast, a for loop does not need this because it
automatically updates the loop variable:

💡Explanatory notes on defining ranges in Python:


In Python, range(5) is equivalent to range(0, 5).

Both will generate the sequence 0, 1, 2, 3, 4. The difference is that


range(5) is a shorthand where Python automatically starts from 0. In
contrast, range(0, 5) explicitly defines the starting value as 0.

Python’s range() function generates numbers starting from the specified


value (defaulting to 0 if not given) and goes up to, but does not include, the
ending value. So, range(5) produces 0, 1, 2, 3, 4.

In R, writing 0:5 generates a sequence that includes both the start and end
values, producing 0, 1, 2, 3, 4, 5. This behavior is different from Python,
where the range stops just before the end value.
What is a Function in
Python?
A function is a reusable block of code that only runs when it’s called by its
name. You can send an input (known as parameters) to the function, and it
can return an output (result) back to you.

The fundamental rule of programming is DRY: Don’t Repeat Yourself.


Whenever you find yourself copying and pasting code, modifying it, and
running it repeatedly, it’s a sign that you should write a function instead. This
can be likened to writing a standard recipe for a meal. Instead of referring to
different cooking instructions from various sources while preparing a dish,
and doing this every time you cook, you compile everything into one single
recipe document. This way, every time you want to cook, you have all the
instructions neatly organized in one place, making the process easier and
more efficient.

Creating a Function:

To create a function in Python, use the def keyword, followed by the function
name and parentheses. Here’s an example:

def my_function():

print("Hello from a function")

Calling a Function:

To run the function, simply call it by its name followed by parentheses:


my_function() # Outputs: Hello from a function

Arguments in Functions:

You can pass information (called arguments) into a function to customize its
behavior. The arguments are placed inside the parentheses when you define
and call the function. For example:

def greet(name):

print("Hello " + name)

greet("John") # Outputs: Hello John

💡HINT: Note that the second line of the function (the print statement)
must be indented. Indentation is how Python identifies blocks of code that
belong together, such as the body of a function. Without proper indentation,
Python will raise an error. By indenting the print statement, Python
recognizes it as part of the greet function, and generates the needed output.
If the function has multiple lines, all lines within the function's body must
be indented. Each line of code that is part of the function must be indented
consistently. When calling the function however, you should not indent it.

Number of Arguments:

When calling a function, you need to provide the correct number of


arguments. If the function expects two arguments, you must pass exactly two
arguments:

def add(a, b):

return a + b

print(add(5, 3)) # Outputs: 8


In this case, calling add(5, 3) works because it matches the two expected
arguments.

Homework
Assignment 1: Looping Over a List

Objective: Write a Python program to loop over a list of country names and
print a sentence indicating the number of letters in each country name.

Instructions:

1. Define the List:

You are given a list of countries:

countries = ['Uganda', 'Canada', 'Malaysia', 'Finland']

2. Loop Through the List:


○ Iterate over each country in the list.
3. Print the Sentence:

For each country, print the following sentence:

{country} contains {len(country)} letters!

Replace {country} with the country name and {len(country)} with the
number of letters in the country name.

Example Output:

Uganda contains 6 letters!


Canada contains 6 letters!

Malaysia contains 8 letters!

Finland contains 7 letters!

Hint: You can only

Assignment 2: Unit Conversion Function

Objective: Write a Python function to convert values between kilometers


(km), meters (m), and centimeters (cm). The function should handle
conversions both to and from these units.

Instructions:

Function Definition: Create a function named convert_units with the


following signature:

def convert_units(value, from_unit, to_unit):

Parameters:

● value (float): The numeric value to be converted.


● from_unit (str): The unit of the value (one of 'km', 'm', 'cm').
● to_unit (str): The unit to which the value should be converted (one of
'km', 'm', 'cm').

Error Handling:

● If the from_unit or to_unit is not in this list ['km', 'm', 'cm'], raise a
ValueError with the message: "Invalid units. Supported units are 'km',
'm', and 'cm'."
Return Value:

● Return the converted value as a string in the format


"{converted_value}{to_unit}". Sample “20km”.

You might also like