Coding Bootcamp - Student Reference Guide

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

CODING BOOT CAMP

STUDENT REFERENCE GUIDE

TALENCIAGLOBAL
INDEX

Contents
Structure of a Python Program .................................................................................................... 3
Explanation of Program Elements ........................................................................................... 3
Comments .......................................................................................................................................... 5
Types of Comments .................................................................................................................... 5
Best Practices for Writing Comments.................................................................................... 7
Variables.............................................................................................................................................. 8
Examples of Variables in Action ............................................................................................ 10
Best Practices for Using Variables ........................................................................................ 11
Output Statement........................................................................................................................... 12
Formatted Output........................................................................................................................... 14
Console Input ................................................................................................................................... 16
Examples of Input in a Program ............................................................................................ 18
Arithmetic Operators in Python ................................................................................................. 19
Examples of Arithmetic Operators ........................................................................................ 19
If Statements .................................................................................................................................... 22
Examples of If Statement ......................................................................................................... 22
Nested If Statements ..................................................................................................................... 26
Examples of Nested If Statements ........................................................................................ 26
Key Points About Nested If Statements ............................................................................... 28
Using if-elif-else Statements .................................................................................................. 30
Using match Statement (Python 3.10 and Later) ................................................................. 31
While Loop ......................................................................................................................................... 35
Requirements for Writing a While Loop ............................................................................... 35
Properties of a While Loop ....................................................................................................... 35
Examples to Illustrate Requirements and Properties ..................................................... 36
For Loop .............................................................................................................................................. 39
Properties of a For Loop ............................................................................................................ 40
Examples of For Loops ............................................................................................................... 40
Nested Loops .................................................................................................................................... 44
Arrays in Python (Using Lists) ..................................................................................................... 48

Coding Bootcamp Student Guide


INDEX

Basic Operations on Arrays (Lists) ............................................................................................ 51


Examples of Array (List) Operations ..................................................................................... 52
Two-Dimensional Arrays in Python .......................................................................................... 54
Accessing Elements in a 2D Array......................................................................................... 54
Traversing a 2D Array ................................................................................................................ 55
How to Input Values into a 2D Array ..................................................................................... 56
How to Output All Values from a 2D Array.......................................................................... 57
Operations on 2D Arrays .......................................................................................................... 58
Key Points ...................................................................................................................................... 60
Functions in Python ........................................................................................................................ 61
How to Declare a Function....................................................................................................... 61
Examples of Functions .............................................................................................................. 62
Passing Parameters to Functions ......................................................................................... 63
Returning Values From Functions ......................................................................................... 64
Scope of Variables in Functions ............................................................................................ 65

Coding Bootcamp Student Guide


INDEX

Structure of a Python Program

Here’s the general structure of a simple Python program:

# 1. Comments and Documentation


# Description: This program calculates the area of a rectangle.

# 2. Variable Initialization
length = 10
width = 5

# 3. Logic/Operations
area = length * width # Calculate the area of the rectangle

# 4. Output
print("The area of the rectangle is:", area)

Explanation of Program Elements

1. Comments and Documentation


• Purpose: To describe the program or explain specific parts of the code.
• Format: Begin a line with # for single-line comments.
• Example:
# This program calculates the area of a rectangle.

2. Variable Initialization
• Purpose: To store data values that the program will use.
• Format: Assign a value to a variable using =.
• Example:

length = 10 # Length of the rectangle


width = 5 # Width of the rectangle

3. Logic/Operations
• Purpose: To perform calculations, make decisions, or execute loops based
on the program’s goal.
• Example:

area = length * width # Multiply length and width to calculate the area.

Coding Bootcamp Student Guide


INDEX

4. Output
• Purpose: To display results or communicate with the user.
• Format: Use the print() function to show output on the screen.
• Example:

print("The area of the rectangle is:", area)

Coding Bootcamp Student Guide


INDEX

Comments

Comments are an essential part of any program. They make your code easier to
understand and maintain.

What Are Comments?


• Comments are lines in a program that Python ignores during execution.
• They are used to explain what the program does or to leave notes for future
reference.
Key Characteristics:
• They do not affect the program's behaviour.
• They are purely for the benefit of programmers (yourself and others).

Why Do We Use Comments?


1. Code Clarity: To explain complex logic or calculations in your code.
2. Collaboration: To help others understand your code when working in a
team.
3. Future Reference: To remind yourself why you wrote the code in a certain
way.
4. Debugging: To temporarily disable parts of the code without deleting them.

Types of Comments

Python supports two types of comments:


1. Single-line Comments
• Begin with the # symbol.
• Used for short, one-line explanations.
Example:
# This is a single-line comment
x = 5 # Assigning the value 5 to variable x

2. Multi-line Comments
• Enclosed within triple quotes (''' or """).
• Used for longer explanations or documentation.
Example:
"""
This is a multi-line comment.
It can span multiple lines and is often used
for detailed explanations or documentation.
"""

Coding Bootcamp Student Guide


INDEX

Examples of Comments in Action


Here’s how comments can be used in a program:
# This program calculates the area of a rectangle

# Step 1: Initialize variables


length = 10 # Length of the rectangle
width = 5 # Width of the rectangle

# Step 2: Calculate the area


area = length * width # Multiply length and width

# Step 3: Display the result


print("The area of the rectangle is:", area)

Coding Bootcamp Student Guide


INDEX

Using Multi-line Comments:


"""
This program demonstrates the use of multi-line comments.
It calculates the area of a rectangle and displays the result.
"""
length = 10
width = 5
area = length * width
print("The area of the rectangle is:", area)

Best Practices for Writing Comments

1. Be concise: Write comments that are clear and to the point.


2. Avoid redundancy: Don’t describe the obvious.
o Bad: x = 10 # Assign 10 to x
o Good: x = 10 # Represents the initial value
3. Keep comments updated: Ensure your comments match your code.

Coding Bootcamp Student Guide


INDEX

Variables

Variables are a fundamental concept in programming. They act as containers to


store and manipulate data.

What Are Variables?


• A variable is a name given to a memory location where data is stored.
• It allows you to store values and refer to them later in your program.
• Think of a variable as a label for a specific value.

Key Points:
1. Variables have a name (identifier) that you choose.
2. The value stored in a variable can change during program execution.

Example:
x = 5 # Here, 'x' is a variable storing the value 5.

How Do We Declare Variables?


• Variables in Python are declared by simply assigning a value using the =
operator.
• No need to explicitly specify the type of variable; Python determines it
automatically.

Syntax:
variable_name = value

Rules for Naming Variables:


1. Must start with a letter or an underscore (_).
2. Can contain letters, numbers, and underscores but cannot start with a
number.
3. Cannot use reserved keywords (like if, while, for, etc.).
4. Variable names are case-sensitive (Name and name are different).

Examples:
age = 25 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_happy = True # Boolean

How Do We Determine the Data Type of Variables?


• Python automatically assigns a data type to variables based on the value

Coding Bootcamp Student Guide


INDEX

you assign.
• You can check the data type using the type() function.
Example:
x = 10
print(type(x)) # Output: <class 'int'>

y = "Hello"
print(type(y)) # Output: <class 'str'>

z = 3.14
print(type(z)) # Output: <class 'float'>

Coding Bootcamp Student Guide


INDEX

Examples of Variables in Action

Example 1: Storing Different Types of Data


# Declaring variables
name = "John" # String
age = 30 # Integer
height = 5.9 # Float
is_student = False # Boolean

# Using variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is a student:", is_student)

Output:
Name: John
Age: 30
Height: 5.9
Is a student: False

Example 2: Reassigning Variables


x = 10 # Initial value
print(x) # Output: 10

x = 20 # Reassigning a new value


print(x) # Output: 20

Example 3: Determining Data Types


a = 42
b = "Hello"
c = 3.14
d = True

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


print(type(b)) # Output: <class 'str'>
print(type(c)) # Output: <class 'float'>
print(type(d)) # Output: <class 'bool'>

Coding Bootcamp Student Guide


INDEX

Best Practices for Using Variables


1. Use meaningful names to describe the data they hold.
o Bad: x = 10
o Good: age = 10
2. Follow naming conventions (e.g., use lowercase words with underscores for
readability: total_score).
3. Avoid overwriting built-in Python functions (e.g., don’t name your variable
print or type).

Coding Bootcamp Student Guide


INDEX

Output Statement

In Python, the print() function is used to display information on the screen. This is
the simplest way to interact with users by showing text or the result of calcula-
tions.

How Do We Make an Output in Python?


To display a message or value on the screen, use the print() function.

Syntax:
print(value) #value: The content you want to display (can be text, numbers, or
variables).

Examples of Output Statements


1. Printing Text
You can display plain text (known as a string) by enclosing it in quotes (' or ").

Example:
print("Hello, World!")

Output:
Hello, World!

2. Printing Numbers
You can directly display numbers or the results of calculations.
Example:

print(42) # Prints a number


print(10 + 5) # Prints the result of 10 + 5
Output:
42
15

3. Printing Variables
You can display the value of a variable by passing it to the print() function.
Example:

name = "Alice"
age = 25
print(name) # Prints the value of 'name'
print(age) # Prints the value of 'age'

Coding Bootcamp Student Guide


INDEX

Output:
Alice
25

4. Printing a Combination of Text and Variables


You can combine text and variables in the same print() statement using commas
,.
Example:
name = "Bob"
score = 95
print("Name:", name)
print("Score:", score)

Output:
makefile
Name: Bob
Score: 95

Key Points
1. The print() function is your primary tool to display output on the screen.
2. You can print text, numbers, variables, or a combination of these.
3. Always use the correct syntax to avoid errors.

Coding Bootcamp Student Guide


INDEX

Formatted Output

Formatted output allows you to present variables and values in a structured and
readable way. Python provides a simple and powerful way to format output using
f-strings (formatted string literals).

Why Use Formatted Output?


• To combine text and variables neatly.
• To control the appearance of the output (e.g., decimal places, alignment).

Using f-strings (Formatted String Literals)


An f-string is a string prefixed with f or F that allows you to include variables inside
curly braces {}.
Syntax:
print(f"Your text {variable_name}")

Examples:
name = "Alice"
age = 25

# Example 1: Simple formatted output


print(f"My name is {name} and I am {age} years old.")

# Example 2: Formatting numbers


pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}.") # Limits to 2 decimal places

Output:
My name is Alice and I am 25 years old.
The value of pi is approximately 3.14.

Examples of Output Statements

1. Basic Printing
print("Hello, World!")
Output:
Hello, World!

Coding Bootcamp Student Guide


INDEX

2. Printing Variables
name = "Bob"
score = 90
print(f"Name: {name}, Score: {score}")

Output:
Name: Bob, Score: 90

3. Printing Calculations
x = 10
y=5
print(f"The sum of {x} and {y} is {x + y}.")

Output:
The sum of 10 and 5 is 15.

Key Points
1. Use print() for basic output to display text, numbers, or variables.
2. Use f-strings for combining variables with text in a clean, readable format.
3. You can control the appearance of numbers or alignments using format-
ting options in f-strings.

Coding Bootcamp Student Guide


INDEX

Console Input

In Python, the input() function is used to take input from the user through the con-
sole. This allows your program to interact with users by asking for and processing
data.

How Do We Take Input in Python?


The input() function reads a line of text entered by the user and returns it as a
string.

Syntax:
variable = input(prompt)
• prompt: A message displayed to the user before they input their response
(optional).
• variable: The value entered by the user is stored in the variable.

Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")

Output (example user input in bold):


Enter your name: **Alice**
Hello, Alice!

Important Points About input()


1. Input is Always a String:
o The input() function returns data as a string, even if the user enters a
number.
o If you need the input as a specific data type (e.g., integer or float),
you must convert it using typecasting.

Variants of Input
1. Reading Text Input
By default, input() returns a string.

Example:
favorite_color = input("What is your favorite color? ")
print(f"Your favorite color is {favorite_color}.")

Coding Bootcamp Student Guide


INDEX

2. Reading Numeric Input


To handle numeric input, convert the string into a number using int() for integers
or float() for decimals.

Example:
# Reading an integer
age = int(input("Enter your age: "))
print(f"You are {age} years old.")

# Reading a floating-point number


height = float(input("Enter your height in meters: "))
print(f"Your height is {height} meters.")

Output (example user input in bold):

Enter your age: **25**


You are 25 years old.

Enter your height in meters: **1.75**


Your height is 1.75 meters.

3. Using Input for Calculations


You can use user input directly in calculations after converting it to the appropri-
ate type.

Example:
# Adding two numbers provided by the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"The sum of {num1} and {num2} is {num1 + num2}.")

Output (example user input in bold):


Enter the first number: **10**
Enter the second number: **15**
The sum of 10 and 15 is 25.

Coding Bootcamp Student Guide


INDEX

4. Input Without a Prompt

You can use input() without any message, but this is less user-friendly.

Example:
data = input()
print(f"You entered: {data}")

Output:
**Hello**
You entered: Hello

Examples of Input in a Program

Example 1: Asking for User Details

name = input("What is your name? ")


age = int(input("How old are you? "))
print(f"Hello, {name}. You are {age} years old.")

Output (example user input in bold):


What is your name? **Alice**
How old are you? **25**
Hello, Alice. You are 25 years old.

Example 2: Performing Calculations


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"The area of the rectangle is {area}.")

Output (example user input in bold):


Enter the length of the rectangle: **10**
Enter the width of the rectangle: **5**
The area of the rectangle is 50.0.

Key Points
1. Use input(prompt) to take user input from the console.
2. Always remember that input() returns a string; use typecasting for numeric
operations.
3. Provide clear prompts to guide the user on what input is expected.

Coding Bootcamp Student Guide


INDEX

4. Combine input() with other logic to make interactive programs.

Arithmetic Operators in Python

Arithmetic operators are symbols that perform mathematical operations on


numbers. Python supports a variety of operators for performing basic arithmetic.

What Are Arithmetic Operators?


Arithmetic operators in Python allow you to perform operations like addition, sub-
traction, multiplication, division, and more. These operators work with numbers
and return the result of the operation.

List of Arithmetic Operators


Operator Operation Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division (float) 5/3 1.666...
// Floor Division 5 // 3 1
% Modulus (Remainder) 5 % 3 2
** Exponentiation 5 ** 3 125

Examples of Arithmetic Operators

1. Addition (+)

Adds two numbers together.


x = 10
y=5
result = x + y
print("Addition:", result)

Output:
Addition: 15

2. Subtraction (-)

Subtracts one number from another.


x = 10
y=5

Coding Bootcamp Student Guide


INDEX

result = x - y
print("Subtraction:", result)

Output:
Subtraction: 5

3. Multiplication (*)

Multiplies two numbers.


x = 10
y=5
result = x * y
print("Multiplication:", result)

Output:
Multiplication: 50

4. Division (/)
Divides one number by another and returns a float.
x = 10
y=4
result = x / y
print("Division:", result)

Output:
Division: 2.5

5. Floor Division (//)


Divides one number by another and returns the integer part of the result (trun-
cates the decimal).

x = 10
y=4
result = x // y
print("Floor Division:", result)

Output:
Floor Division: 2

6. Modulus (%)
Returns the remainder of a division.
x = 10

Coding Bootcamp Student Guide


INDEX

y=4
result = x % y
print("Modulus:", result)

Output:
Modulus: 2

7. Exponentiation (**)
Raises one number to the power of another.
x=2
y=3
result = x ** y
print("Exponentiation:", result)

Output:
Exponentiation: 8

Using Arithmetic Operators in Programs


Example 1: Basic Calculator

a = int(input("Enter the first number: "))


b = int(input("Enter the second number: "))

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)

Output (example user input in bold):

Enter the first number: **10**


Enter the second number: **3**
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus:

Coding Bootcamp Student Guide


INDEX

If Statements

The if statement is one of the most important tools in programming. It allows you
to make decisions in your program based on certain conditions.

What Is an If Statement?
An if statement checks whether a condition is true or false:
• If the condition is true, it executes a block of code.
• If the condition is false, it skips that block of code.
Think of it like making a decision in real life:
"If it's raining, I'll take an umbrella."

Parts of an If Statement
An if statement has the following structure:

if condition:
# Code to execute if the condition is true
• if: This keyword introduces the condition.
• condition: This is a statement that evaluates to True or False.
• Code block: The indented block of code that runs if the condition is true.

How Does the If Statement Work?


1. The program evaluates the condition.
2. If the condition is true, it executes the indented code block.
3. If the condition is false, it skips the indented block.

Examples of If Statement

Example 1: Checking a Condition


x = 10

if x > 5:
print("x is greater than 5")

Output:
x is greater than 5
• The condition x > 5 is true, so the code inside the if block runs.

Coding Bootcamp Student Guide


INDEX

Adding an else Statement


The else statement specifies what to do when the condition is false.
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false

Example 2: If-Else Statement


x=3

if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

Output:
x is not greater than 5
• Since x > 5 is false, the code inside the else block runs.

Using elif for Multiple Conditions

The elif statement stands for "else if" and is used to check additional conditions if
the first one is false.

if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition1 is false and condition2 is true
else:
# Code to execute if all conditions are false

Example 3: If-Elif-Else Statement


x=0

if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")

Coding Bootcamp Student Guide


INDEX

Output:
x is zero

• The program checks each condition in order:


o x > 0 is false.
o x == 0 is true, so it executes the corresponding block.

How If Statements Are Evaluated


1. The condition is evaluated from left to right.
2. If the first condition is true, the corresponding block runs, and the rest are
skipped.
3. If none of the conditions are true, the else block (if present) runs.

Example 4: Order of Evaluation


x = 10

if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")

Output:

x is greater than 5
• The program stops at the first true condition (x > 5) and skips the rest.

Key Points to Remember


1. The condition in an if statement must evaluate to True or False.
2. Indentation is crucial: The code inside the if, elif, or else block must be in-
dented.
3. You can have multiple elif blocks, but only one else block.
4. If no condition is true and there’s no else, the program does nothing.

Coding Bootcamp Student Guide


INDEX

Examples for Practice


Try these examples to understand how if statements work:

Example 1: Even or Odd


num = int(input("Enter a number: "))

if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")

Example 2: Grading System


score = int(input("Enter your score: "))

if score >= 90:


print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")

Coding Bootcamp Student Guide


INDEX

Nested If Statements

Sometimes, you may need to check multiple conditions, where one condition de-
pends on another. In such cases, you can use nested if statements. A nested if
statement is simply an if statement placed inside another if statement.

What Are Nested If Statements?

A nested if statement allows you to write an if statement inside another if block.


This means:
1. The first condition is checked.
2. If the first condition is true, then the program checks the second condition.
3. If all conditions are true, the nested block of code executes.

Real-Life Example:
"If it's raining:
• If I have an umbrella:
o Then I will go outside."

Syntax of Nested If Statements

if condition1:
# Code block for condition1
if condition2:
# Code block for condition2

How Do Nested If Statements Work?


1. The program checks the outer condition (condition1).
2. If condition1 is true, it moves inside the block and checks the inner condi-
tion (condition2).
3. If condition2 is also true, it executes the inner block of code.
4. If any condition is false, the program skips the corresponding block.

Examples of Nested If Statements

Example 1: Checking Age and Citizenship


age = int(input("Enter your age: "))

if age >= 18:


print("You are eligible to vote.")
citizenship = input("Are you a citizen? (yes/no): ")

Coding Bootcamp Student Guide


INDEX

if citizenship == "yes":
print("You can vote in the election.")
else:
print("You cannot vote in the election.")
else:
print("You are not old enough to vote.")

Output (Example 1 User Input):


Enter your age: 20
You are eligible to vote.
Are you a citizen? (yes/no): no
You cannot vote in the election.

Example 2: Grading System with Distinction


score = int(input("Enter your score: "))

if score >= 50:


print("You passed.")
if score >= 90:
print("Congratulations! You scored a distinction.")
else:
print("You failed.")

Output (Example 2 User Input):


Enter your score: 95
You passed.
Congratulations! You scored a distinction.

Example 3: Temperature Check


temperature = float(input("Enter the temperature in Celsius: "))

if temperature > 0:
print("It's above freezing.")
if temperature > 30:
print("It's a hot day!")
else:
print("The weather is pleasant.")
else:
print("It's freezing.")

Coding Bootcamp Student Guide


INDEX

Output (Example 3 User Input):


Enter the temperature in Celsius: 35
It's above freezing.
It's a hot day!

Key Points About Nested If Statements

1. Indentation is crucial:
o The inner if statement must be indented inside the outer if block.
o This shows that the inner if is part of the outer condition.
2. Avoid too many levels:
o Excessive nesting can make your code hard to read and maintain.
3. Conditions are evaluated one by one:
o The program evaluates the outer condition first and only evaluates
the inner condition if the outer one is true.
4. Use meaningful conditions:
o Ensure your conditions are clear and logical to make the program
easier to understand.

Examples for Practice

Example 1: Eligibility Check for a Loan


income = int(input("Enter your monthly income: "))
credit_score = int(input("Enter your credit score: "))

if income > 5000:


print("You meet the income requirement.")
if credit_score > 700:
print("You are eligible for the loan.")
else:
print("Your credit score is too low for a loan.")
else:
print("You do not meet the income requirement.")

Example 2: Number Classification


num = int(input("Enter a number: "))

if num > 0:
print("The number is positive.")
if num % 2 == 0:
print("The number is even.")

Coding Bootcamp Student Guide


INDEX

else:
print("The number is odd.")
else:
print("The number is not positive.")

Best Practices
1. Keep your nested conditions simple and clear.
2. Avoid unnecessary nesting; use logical operators (and, or) if it simplifies
your code.
o Example: Instead of nesting:
if x > 0:
if x < 10:
print("x is between 0 and 10")

You can write:


if 0 < x < 10:
print("x is between 0 and 10")

Coding Bootcamp Student Guide


INDEX

Using if-elif-else Statements

An if-elif-else chain can be used as a substitute for a switch statement. This is the
most straightforward way to handle multiple conditions.

Example:

choice = int(input("Enter a number (1-3): "))

if choice == 1:
print("You chose option 1")
elif choice == 2:
print("You chose option 2")
elif choice == 3:
print("You chose option 3")
else:
print("Invalid choice")

Coding Bootcamp Student Guide


INDEX

Using match Statement (Python 3.10 and Later)

Starting with Python 3.10, you can use the match statement, which is similar to a
switch statement in other languages. It matches a value to specific patterns and
executes the corresponding block of code.

Example:
choice = int(input("Enter a number (1-3): "))

match choice:
case 1:
print("You chose option 1")
case 2:
print("You chose option 2")
case 3:
print("You chose option 3")
case _:
print("Invalid choice")

Which Approach to Use?


• Use if-elif-else for small and simple conditions.
• Use a dictionary lookup for concise and efficient mapping of specific val-
ues to actions.
• Use match if you are working with Python 3.10+ and need advanced pat-
tern matching.

The match Statement in Python

The match statement, introduced in Python 3.10, is a powerful feature for pattern
matching. It allows you to write cleaner and more readable code for handling
multiple conditions, similar to a switch statement in other languages but with
added flexibility.

How Does the match Statement Work?


The match statement checks a value against patterns and executes the corre-
sponding block of code for the first matching pattern.
• You use the case keyword to define the patterns.
• If no pattern matches, you can define a default case using _ (wildcard).

Coding Bootcamp Student Guide


INDEX

Syntax of the match Statement


match value:
case pattern1:
# Code block for pattern1
case pattern2:
# Code block for pattern2
case _:
# Default case (optional)

Elements of the match Statement


1. match Keyword:
o Starts the pattern matching process.
o You provide a value that will be compared to the patterns.
2. case Keyword:
o Defines individual patterns to match the value.
o Each case block contains code to execute if the pattern matches.
3. Patterns:
o Patterns can be:
▪ Literals (e.g., numbers, strings)
▪ Variables
▪ Tuples
▪Objects
4. Wildcard (_):
o Acts as a default or fallback case.
o Matches any value if no other pattern matches.

Examples of the match Statement

1. Matching Literal Values


This is the simplest use case, similar to a switch statement.
day = input("Enter a day of the week: ")

match day:
case "Monday":
print("Start of the work week.")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Just another weekday.")

Coding Bootcamp Student Guide


INDEX

Output (Example 1 User Input):


Enter a day of the week: Saturday
It's the weekend!

2. Matching Numeric Values


num = int(input("Enter a number: "))

match num:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("Number not recognized")

Output (Example 2 User Input):


Enter a number: 2
Two

3. Using the Wildcard (_)

The _ case matches any value if no other case matches.


color = input("Enter a color: ")

match color:
case "red":
print("Stop!")
case "green":
print("Go!")
case "yellow":
print("Slow down!")
case _:
print("Unknown color")

Output (Example 3 User Input):


Enter a color: blue
Unknown color

Coding Bootcamp Student Guide


INDEX

4. Matching Multiple Values in One Case

You can use the | (or) operator to match multiple values in the same case.

fruit = input("Enter a fruit: ")

match fruit:
case "apple" | "banana" | "cherry":
print("This fruit is available.")
case _:
print("This fruit is not available.")

Output (Example 4 User Input):


Enter a fruit: banana
This fruit is available.

How Does the match Statement Get Evaluated?


1. The value after match is compared sequentially to each case pattern.
2. The first pattern that matches is executed.
3. If no patterns match and _ is defined, the wildcard case runs.

Key Points
1. The match statement is flexible and can handle complex conditions.
2. The _ wildcard is optional but recommended for handling unmatched
cases.
3. Patterns can be as simple as literals or as complex as objects and condi-
tions.
4. Always ensure your patterns are clear and unambiguous.

Coding Bootcamp Student Guide


INDEX

While Loop

The while loop is a fundamental looping construct in Python that allows repeated
execution of a block of code as long as a specified condition is true.

Requirements for Writing a While Loop


To write a proper while loop, the following requirements must be met:
1. Proper Initial Values for Control Variables:
o The variables used in the condition must be initialized correctly be-
fore the loop begins.
Example:

count = 1 # Initialize the control variable

2. Proper Condition:
o The condition in the while statement must evaluate to True or False.
Example:
while count <= 5: # Ensure the condition makes logical sense

3. Proper Begin and End (Body of the Loop):


o The loop body must be correctly indented to define the code that
runs while the condition is true.
Example:
while count <= 5:
print(count)
count += 1

4. Proper Change of Control Variables:


o The control variable should be updated in a way that ensures the
loop eventually terminates.
Example:
count += 1 # Modify the control variable

Properties of a While Loop


1. Pre-Tested:
o The condition is evaluated before entering the loop body. If the con-
dition is false initially, the loop body will not execute.
2. May Not Execute at All:
o Since the condition is checked first, the loop body might not run if the
condition is false from the beginning.

Coding Bootcamp Student Guide


INDEX

3. Re-Entry and Exit:


o The loop re-evaluates the condition each time before running the
body.
o The loop exits when the condition becomes false.

Examples to Illustrate Requirements and Properties

Example 1: Proper Initial Values, Condition, and Control

# Proper initial value for control variable


count = 1

# Proper condition
while count <= 5:
# Proper body (begin and end)
print(f"Count is: {count}")

# Proper change to control variable


count += 1 # Increment to ensure termination

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Example 2: Loop Does Not Execute (Condition False Initially)

# Initial value set to skip the loop


count = 10

# The condition is false from the start


while count <= 5:
print(f"Count is: {count}")
count += 1

print("Loop ended.")

Coding Bootcamp Student Guide


INDEX

Output:
Loop ended.

• The loop body does not execute because the condition (count <= 5) is false
initially.

Example 3: Infinite Loop (No Proper Change to Control Variable)

# Improper change to control variable


count = 1

while count <= 5:


print(f"Count is: {count}")
# Missing `count += 1` will cause an infinite loop

Output: (This will print Count is: 1 indefinitely, so be cautious!)


• The loop runs forever because the control variable (count) is not updated.

Example 4: Validating Input Using a While Loop

This example demonstrates re-entering the loop until valid input is provided.
# Proper initial value
user_input = ""

# Proper condition
while user_input != "yes":
# Proper body with indentation
user_input = input("Do you want to exit? (type 'yes' to exit): ")

print("You chose to exit.")

Output (Example User Input):


Do you want to exit? (type 'yes' to exit): no
Do you want to exit? (type 'yes' to exit): maybe
Do you want to exit? (type 'yes' to exit): yes
You chose to exit.

Coding Bootcamp Student Guide


INDEX

Example 5: Using a While Loop for Pre-Tested Logic

This example illustrates a pre-tested loop where the condition determines


whether the body executes.

# Proper initial value


num = -1

# Pre-tested condition
while num > 0:
print(f"Number is: {num}")
num -= 1 # Proper change to control variable

print("Loop completed.")

Output:

Loop completed.
• The loop does not execute because the condition (num > 0) is false initially.

Summary
1. Requirements for Writing a While Loop:
o Proper initial values for control variables.
o Logical condition to control the loop.
o Properly defined body of the loop with correct indentation.
o Control variables updated appropriately to terminate the loop.
2. Properties of a While Loop:
o Pre-tested: Condition is evaluated before execution.
o May not execute: If the condition is false initially, the loop body is
skipped.
o Re-evaluates condition: Checks the condition after each iteration
and exits when false.

Coding Bootcamp Student Guide


INDEX

For Loop

A for loop is used to iterate over a sequence (like a list, range, or string) or perform
a set number of repetitions. It is a powerful and concise way to execute repetitive
tasks.

What Is a For Loop?


• A for loop allows you to iterate over elements in a sequence or a range of
values.
• At each iteration, the loop assigns the next value in the sequence to a vari-
able (called the control variable) and executes the body of the loop.

Why Do We Use a For Loop?


1. To iterate over sequences (e.g., lists, tuples, dictionaries, strings).
2. To perform a task a fixed number of times using the range() function.
3. To write concise and readable code for repetitive tasks.

Example:

for i in range(5): # Iterates 5 times


print("Iteration:", i)

Requirements for a For Loop


To write a proper for loop, ensure the following:
1. Initialization Value:
o The loop control variable starts with an initial value.
o Example:
for i in range(5): # Starts at 0

2. Final Value:
o The loop stops when the control variable reaches or exceeds a final
value (depending on the range).
o Example:
for i in range(5): # Stops when i >= 5

3. Stepping (Increment/Decrement):
o The control variable is automatically incremented or decremented
based on the range step.
o Example:
for i in range(0, 10, 2): # Step of 2

Coding Bootcamp Student Guide


INDEX

4. Proper Begin and End:


o The loop body must be indented, and the task performed inside the
loop should be clearly defined.
o Example:
for i in range(3):
print(i) # Indented body

5. Control Variable Update:


o The control variable is updated automatically by Python, based on
the sequence or range.
o Example:
for char in "hello": # Updates to the next character in each it-
eration

Properties of a For Loop


1. Pre-Tested:
o The loop checks if there are more items in the sequence before each
iteration.
o If there are no more items, the loop terminates.
2. Known Number of Iterations:
o The number of iterations is typically determined by the sequence or
range.
3. Control Variable Changes Automatically:
o The loop control variable updates to the next value in the sequence
without manual intervention.
4. Efficient and Concise:
o Suitable for iterating over sequences and performing fixed iterations.

Examples of For Loops

Example 1: Iterating Over a Range


for i in range(5): # Iterates from 0 to 4
print("Iteration:", i)

Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

Coding Bootcamp Student Guide


INDEX

Example 2: Custom Start, End, and Step

for i in range(2, 10, 2): # Starts at 2, ends before 10, step of 2


print("Current value:", i)

Output:
Current value: 2
Current value: 4
Current value: 6
Current value: 8

Example 3: Iterating Over a List


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

for fruit in fruits:


print("I like", fruit)

Output:
I like apple
I like banana
I like cherry

Example 4: Iterating Over a String


for char in "hello":
print("Character:", char)

Output:
Character: h
Character: e
Character: l
Character: l
Character: o

Example 5: Counting Backwards


for i in range(10, 0, -2): # Starts at 10, ends before 0, steps by -2
print("Countdown:", i)

Output:
Countdown: 10
Countdown: 8
Countdown: 6

Coding Bootcamp Student Guide


INDEX

Countdown: 4
Countdown: 2

For Loop with Conditional Logic

Example 6: Skipping Values with if


for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print("Odd number:", i)

Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9

Example 7: Breaking Out of the Loop


for i in range(5):
if i == 3:
print("Breaking the loop at", i)
break
print("Iteration:", i)

Output:
Iteration: 0
Iteration: 1
Iteration: 2
Breaking the loop at 3

Summary
1. Requirements:
o Proper initialization, condition, and step values.
o Defined loop body with correct indentation.
o Automatic updates to control variables based on the sequence or
range.
2. Properties:
o Pre-tested, known number of iterations.
o Concise and efficient.
o Control variables change automatically.

Coding Bootcamp Student Guide


INDEX

3. Uses:
o Iterating over sequences (range, list, string).
o Performing repetitive tasks with a fixed number of iterations.

With these principles and examples, writing effective and error-free for loops be-
comes straightforward. Let me know if you'd like additional clarifications or exam-
ples!

Coding Bootcamp Student Guide


INDEX

Nested Loops

A nested loop is a loop inside another loop. It allows you to perform repeated ac-
tions at multiple levels, which is useful for tasks like processing multi-dimensional
data or creating patterns.

How Nested Loops Work


• The outer loop runs first and controls the number of iterations for the inner
loop.
• For each iteration of the outer loop, the inner loop executes completely.
• Once the inner loop finishes, the outer loop moves to its next iteration and
the inner loop runs again.

Using a while Loop Within a while Loop


A nested while loop is used when you need to repeatedly perform a task within
another repeated task.

Syntax:
while condition1: # Outer loop
# Code for the outer loop
while condition2: # Inner loop
# Code for the inner loop

Example 1: Multiplication Table


i=1

while i <= 3: # Outer loop: controls the row


j=1
while j <= 3: # Inner loop: controls the column
print(i * j, end=" ") # Multiply and print
j += 1 # Increment inner loop control variable
print() # Move to the next line after each row
i += 1 # Increment outer loop control variable

Output:
123
246
369

Coding Bootcamp Student Guide


INDEX

Explanation:
1. The outer loop (i) runs from 1 to 3.
2. For each i, the inner loop (j) runs from 1 to 3.
3. The inner loop completes all iterations for each value of i.

Example 2: Generating a Pattern


rows = 4

i=1
while i <= rows: # Outer loop for rows
j=1
while j <= i: # Inner loop for columns
print("*", end=" ")
j += 1
print() # Move to the next line
i += 1

Output:
*
**
***
****
Explanation:
1. The outer loop (i) runs for each row.
2. The inner loop (j) runs to print stars (*) equal to the current row number.

Using a for Loop Within a for Loop

Nested for loops are commonly used when working with sequences or for tasks
like processing multi-dimensional arrays.

Syntax:
for variable1 in sequence1: # Outer loop
for variable2 in sequence2: # Inner loop
# Code for the inner loop

Example 3: Multiplication Table (Using for Loop)


for i in range(1, 4): # Outer loop: controls the row
for j in range(1, 4): # Inner loop: controls the column
print(i * j, end=" ") # Multiply and print
print() # Move to the next line after each row

Coding Bootcamp Student Guide


INDEX

Output:
123
246
369

Example 4: Generating a Pattern


rows = 4

for i in range(1, rows + 1): # Outer loop for rows


for j in range(1, i + 1): # Inner loop for columns
print("*", end=" ")
print() # Move to the next line
Output:
*
**
***
****

Example 5: Printing a 2D Grid


rows, cols = 3, 3

for i in range(rows): # Outer loop for rows


for j in range(cols): # Inner loop for columns
print(f"({i}, {j})", end=" ") # Print the grid coordinates
print() # Move to the next line

Output:
(0, 0) (0, 1) (0, 2)
(1, 0) (1, 1) (1, 2)
(2, 0) (2, 1) (2, 2)

Explanation:
1. The outer loop iterates over rows.
2. The inner loop iterates over columns.
3. Together, they generate all coordinates in a 2D grid.

Key Points About Nested Loops


1. Order of Execution:
o The outer loop runs first and controls how many times the inner loop
is executed.
o The inner loop runs completely for each iteration of the outer loop.

Coding Bootcamp Student Guide


INDEX

2. Indentation is Crucial:
o Proper indentation is needed to separate the inner loop code from
the outer loop.
3. Performance Considerations:
o Nested loops can become slow for large datasets. Avoid excessive
nesting if possible.
4. Use Cases:
o Creating patterns or grids.
o Processing multi-dimensional data structures (e.g., 2D arrays).

Summary
• Nested while Loops:
o Use when the number of iterations is controlled by a condition.
• Nested for Loops:
o Use when iterating over sequences or ranges.
• Common Use Cases:
o Generating patterns.
o Processing multi-dimensional data.
o Repeatedly applying logic within a loop.

Coding Bootcamp Student Guide


INDEX

Arrays in Python (Using Lists)

Python does not have a built-in array type like some other languages. Instead,
lists are used to work with collections of data. Lists in Python can hold elements of
any data type and are flexible and easy to use.
In this section, we’ll cover single-dimensional arrays (simple lists) and basic oper-
ations like declaration, traversal, input/output, and storage.

What Is an Array (List) in Python?


An array (or list in Python) is a collection of elements stored in a single variable.
These elements can be of the same type (e.g., integers, floats, strings) or different
types.

How to Declare Arrays (Lists) in Python


In Python, you declare a list by enclosing elements in square brackets ([]).

Array of Integers
numbers = [1, 2, 3, 4, 5]

Array of Characters
characters = ['a', 'b', 'c', 'd']

Array of Strings
fruits = ["apple", "banana", "cherry"]

Array of Floats
temperatures = [36.5, 37.8, 39.0]

Array of Boolean Values


flags = [True, False, True]

How to Traverse an Array (List)


You can traverse a list using a for loop or a while loop.

Example 1: Traversing with a for Loop


numbers = [1, 2, 3, 4, 5]

for num in numbers:


print(num)

Coding Bootcamp Student Guide


INDEX

Output:
1
2
3
4
5

Example 2: Traversing with a while Loop


characters = ['a', 'b', 'c']

i=0
while i < len(characters):
print(characters[i])
i += 1

Output:
a
b
c

How to Input/Store Values in an Array (List)


You can input values from the user and store them in a list using a loop and the
append() method.

Example: Inputting Values from the User


n = int(input("Enter the number of elements: "))
numbers = []

for i in range(n):
num = int(input(f"Enter element {i + 1}: "))
numbers.append(num)

print("You entered:", numbers)

Example User Input:


Enter the number of elements: 3
Enter element 1: 5
Enter element 2: 10
Enter element 3: 15
Output:
You entered: [5, 10, 15]

Coding Bootcamp Student Guide


INDEX

How to Output All Values from an Array

You can print all elements in a list using a loop or directly using the print() func-
tion.

Example 1: Printing Values with a Loop

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

for fruit in fruits:


print(fruit)

Output:
apple
banana
cherry

Example 2: Printing the Entire List Directly


fruits = ["apple", "banana", "cherry"]
print(fruits)

Output:
['apple', 'banana', 'cherry']

Coding Bootcamp Student Guide


INDEX

Basic Operations on Arrays (Lists)

1. Accessing Elements by Index


fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Access the first element
print(fruits[2]) # Access the third element
Output:
apple
cherry

2. Modifying Elements
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange" # Change the second element
print(fruits)
Output:
['apple', 'orange', 'cherry']

3. Adding Elements
numbers = [1, 2, 3]
numbers.append(4) # Add 4 to the end of the list
print(numbers)

Output:
[1, 2, 3, 4]

4. Removing Elements
numbers = [1, 2, 3, 4]
numbers.remove(2) # Remove the element with value 2
print(numbers)

Output:
[1, 3, 4]

Coding Bootcamp Student Guide


INDEX

Examples of Array (List) Operations

Example 1: Sum of All Elements


numbers = [1, 2, 3, 4, 5]
total = 0

for num in numbers:


total += num

print("Sum of numbers:", total)

Output:
Sum of numbers: 15

Example 2: Finding the Maximum Value


numbers = [10, 20, 30, 40, 50]
max_value = numbers[0]

for num in numbers:


if num > max_value:
max_value = num

print("Maximum value:", max_value)

Output:
Maximum value: 50

Example 3: Reversing the Array


numbers = [1, 2, 3, 4, 5]
reversed_numbers = []

for i in range(len(numbers) - 1, -1, -1): # Traverse in reverse


reversed_numbers.append(numbers[i])

print("Reversed array:", reversed_numbers)

Output:
Reversed array: [5, 4, 3, 2, 1]

Coding Bootcamp Student Guide


INDEX

Summary
1. Declaration:
o Use square brackets to define lists ([]).
o Elements can be integers, floats, strings, characters, or booleans.
2. Traversal:
o Use for or while loops to iterate through the list.
3. Input/Output:
o Use input() and append() to input values.
o Use loops or print() to output values.
4. Basic Operations:
o Access elements by index.
o Modify, add, or remove elements.

Coding Bootcamp Student Guide


INDEX

Two-Dimensional Arrays in Python

A two-dimensional array is like a table or a grid, where data is stored in rows and
columns. In Python, we use nested lists to represent 2D arrays.

What Is a Two-Dimensional Array?


A 2D array is a collection of elements arranged in rows and columns.
Think of it as a list of lists, where:
• Each sublist represents a row.
• Each element in the sublist represents a column.

How to Declare a 2D Array


In Python, a 2D array can be created by nesting lists inside another list.

Example: Declaring a 2D Array


matrix = [
[1, 2, 3], # Row 1
[4, 5, 6], # Row 2
[7, 8, 9] # Row 3
]

Here, the array has:


• 3 rows: [1, 2, 3], [4, 5, 6], [7, 8, 9]
• 3 columns: 1, 4, 7, 2, 5, 8, 3, 6, 9

Accessing Elements in a 2D Array


You can access elements in a 2D array using row and column indices.

Syntax: array[row][column]
Example: Accessing Elements
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

print(matrix[0][0]) # Element at row 0, column 0 -> Output: 1


print(matrix[1][2]) # Element at row 1, column 2 -> Output: 6
print(matrix[2][1]) # Element at row 2, column 1 -> Output: 8

Coding Bootcamp Student Guide


INDEX

Traversing a 2D Array

You can traverse a 2D array using nested loops:


1. The outer loop iterates over rows.
2. The inner loop iterates over columns.

Example: Traversing and Printing All Elements


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

for row in matrix: # Outer loop: Iterates through rows


for col in row: # Inner loop: Iterates through elements in each row
print(col, end=" ")
print() # Move to the next line after each row
Output:
123
456
789

Coding Bootcamp Student Guide


INDEX

How to Input Values into a 2D Array


You can take user input to fill a 2D array using nested loops.

Example: Inputting a 2D Array


rows = 2
cols = 3
matrix = []

for i in range(rows):
row = []
for j in range(cols):
val = int(input(f"Enter value for row {i+1}, column {j+1}: "))
row.append(val)
matrix.append(row)

print("2D Array:")
for row in matrix:
print(row)

Example User Input:


Enter value for row 1, column 1: 1
Enter value for row 1, column 2: 2
Enter value for row 1, column 3: 3
Enter value for row 2, column 1: 4
Enter value for row 2, column 2: 5
Enter value for row 2, column 3: 6

Output:
2D Array:
[1, 2, 3]
[4, 5, 6]

Coding Bootcamp Student Guide


INDEX

How to Output All Values from a 2D Array

You can print all elements of a 2D array row by row.

Example: Printing the 2D Array


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

print("2D Array:")
for row in matrix:
print(row)
Output:
2D Array:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Coding Bootcamp Student Guide


INDEX

Operations on 2D Arrays

1. Finding the Sum of All Elements

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

total = 0

for row in matrix:


for col in row:
total += col

print("Sum of all elements:", total)

Output:
Sum of all elements: 45

2. Finding the Maximum Element


matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

max_value = matrix[0][0]

for row in matrix:


for col in row:
if col > max_value:
max_value = col

print("Maximum element:", max_value)

Output:
Maximum element: 9

Coding Bootcamp Student Guide


INDEX

3. Transposing a 2D Array

Transposing an array swaps rows and columns.


matrix = [
[1, 2, 3],
[4, 5, 6]
]

transpose = []

# Transpose logic
for i in range(len(matrix[0])): # Number of columns in the original matrix
row = []
for j in range(len(matrix)): # Number of rows in the original matrix
row.append(matrix[j][i])
transpose.append(row)

print("Original Matrix:")
for row in matrix:
print(row)

print("Transposed Matrix:")
for row in transpose:
print(row)
Output:
Original Matrix:
[1, 2, 3]
[4, 5, 6]
Transposed Matrix:
[1, 4]
[2, 5]
[3, 6]

Coding Bootcamp Student Guide


INDEX

Key Points
1. Declaration:
o Use nested lists to represent 2D arrays.
o Example: array = [[1, 2, 3], [4, 5, 6]]
2. Accessing Elements:
o Use array[row][col] to access an element.
3. Traversal:
o Use nested loops to iterate through rows and columns.
4. Input and Output:
o Use nested loops to take user input or print values.
5. Common Operations:
o Sum, maximum value, transpose, etc.

Coding Bootcamp Student Guide


INDEX

Functions in Python

A function is a reusable block of code that performs a specific task. Functions


help organize code, avoid repetition, and make programs easier to understand
and maintain.

What Is a Function?
• A function is a block of code that runs when it is called.
• Functions can take input (called parameters) and return an output (a
result).

Why Use Functions?


1. Reusability: Write the code once and reuse it multiple times.
2. Organization: Divide large programs into smaller, manageable parts.
3. Readability: Functions make code easier to read and understand.

How to Declare a Function

A function is defined using the def keyword.


Syntax:
def function_name(parameters):
# Code to execute
return value # Optional
• def: Starts the function definition.
• function_name: The name of the function (choose a meaningful name).
• parameters: Input values passed to the function (optional).
• return: Outputs a value (optional).

How to Call a Function


To execute a function, you call it by its name followed by parentheses ().

Coding Bootcamp Student Guide


INDEX

Examples of Functions

Example 1: A Simple Function Without Parameters


def greet():
print("Hello, welcome to Python programming!")

# Calling the function


greet()

Output:
Hello, welcome to Python programming!

Example 2: A Function With Parameters


Parameters allow you to pass information into a function.

def greet(name):
print(f"Hello, {name}! Welcome to Python programming!")

# Calling the function with an argument


greet("Alice")

Output:
Hello, Alice! Welcome to Python programming!

Example 3: A Function That Returns a Value


A function can compute a result and return it using the return keyword.
def add_numbers(a, b):
return a + b

# Calling the function and storing the result


result = add_numbers(5, 3)
print("The sum is:", result)

Output:
The sum is: 8

Coding Bootcamp Student Guide


INDEX

Passing Parameters to Functions

1. Positional Parameters
Parameters are passed based on their position in the function call.
def subtract(a, b):
return a - b

result = subtract(10, 5) # a=10, b=5


print("Result:", result)
Output:
Result: 5

2. Default Parameters
You can assign default values to parameters. If no value is passed, the default is
used.
def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Alice") # Passes "Alice"


greet() # Uses the default value "Guest"

Output:
Hello, Alice!
Hello, Guest!

3. Keyword Parameters
You can pass arguments by specifying the parameter names, regardless of their
order.
def introduce(name, age):
print(f"My name is {name}, and I am {age} years old.")

introduce(age=25, name="Bob") # Order doesn't matter


Output:
My name is Bob, and I am 25 years old.

Coding Bootcamp Student Guide


INDEX

Returning Values From Functions

The return statement sends a value back to the caller.

Example:
def multiply(a, b):
return a * b

result = multiply(4, 3)
print("The product is:", result)

Output:
The product is: 12

Combining Concepts

Example: A Function to Find the Largest Number


def find_largest(a, b, c):
if a > b and a > c:
return a
elif b > c:
return b
else:
return c

largest = find_largest(10, 20, 15)


print("The largest number is:", largest)
Output:
The largest number is: 20

Coding Bootcamp Student Guide


INDEX

Scope of Variables in Functions

Local Variables
Variables declared inside a function are local to that function and cannot be
accessed outside it.

def show_number():
number = 10 # Local variable
print("Number inside function:", number)

show_number()
# print(number) # Error: number is not defined outside the function

Global Variables
Variables declared outside functions are global and can be accessed anywhere.
number = 10 # Global variable

def show_number():
print("Number inside function:", number)

show_number()
print("Number outside function:", number)
Output:
Number inside function: 10
Number outside function: 10

Key Points About Functions


1. Declaration: Use the def keyword to declare a function.
2. Calling: Call a function by its name followed by parentheses ().
3. Parameters: Functions can accept arguments to process data.
4. Return Values: Functions can return values to the caller using the return
statement.
5. Scope: Variables inside a function are local unless explicitly defined as
global.

Practice Exercises
1. Write a function to calculate the square of a number.
2. Write a function to check if a number is even or odd.
3. Write a function to find the factorial of a number.

Coding Bootcamp Student Guide

You might also like