Coding Bootcamp - Student Reference Guide
Coding Bootcamp - Student Reference Guide
Coding Bootcamp - 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
# 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)
2. Variable Initialization
• Purpose: To store data values that the program will use.
• Format: Assign a value to a variable using =.
• Example:
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.
4. Output
• Purpose: To display results or communicate with the user.
• Format: Use the print() function to show output on the screen.
• Example:
Comments
Comments are an essential part of any program. They make your code easier to
understand and maintain.
Types of Comments
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.
"""
Variables
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.
Syntax:
variable_name = value
Examples:
age = 25 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_happy = True # Boolean
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'>
# 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
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.
Syntax:
print(value) #value: The content you want to display (can be text, numbers, or
variables).
Example:
print("Hello, World!")
Output:
Hello, World!
2. Printing Numbers
You can directly display numbers or the results of calculations.
Example:
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'
Output:
Alice
25
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.
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).
Examples:
name = "Alice"
age = 25
Output:
My name is Alice and I am 25 years old.
The value of pi is approximately 3.14.
1. Basic Printing
print("Hello, World!")
Output:
Hello, World!
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.
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.
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 + "!")
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}.")
Example:
# Reading an integer
age = int(input("Enter your age: "))
print(f"You are {age} years old.")
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}.")
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
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.
1. Addition (+)
Output:
Addition: 15
2. Subtraction (-)
result = x - y
print("Subtraction:", result)
Output:
Subtraction: 5
3. Multiplication (*)
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
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
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
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)
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.
Examples of If Statement
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.
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.
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
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
Output:
x is zero
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.
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
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.
Real-Life Example:
"If it's raining:
• If I have an umbrella:
o Then I will go outside."
if condition1:
# Code block for condition1
if condition2:
# Code block for condition2
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.")
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.")
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.
if num > 0:
print("The number is positive.")
if num % 2 == 0:
print("The number is even.")
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")
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:
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")
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")
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.
match day:
case "Monday":
print("Start of the work week.")
case "Saturday" | "Sunday":
print("It's the weekend!")
case _:
print("Just another weekday.")
match num:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("Number not recognized")
match color:
case "red":
print("Stop!")
case "green":
print("Go!")
case "yellow":
print("Slow down!")
case _:
print("Unknown color")
You can use the | (or) operator to match multiple values in the same case.
match fruit:
case "apple" | "banana" | "cherry":
print("This fruit is available.")
case _:
print("This fruit is not available.")
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.
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.
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
# Proper condition
while count <= 5:
# Proper body (begin and end)
print(f"Count is: {count}")
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
print("Loop ended.")
Output:
Loop ended.
• The loop body does not execute because the condition (count <= 5) is false
initially.
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): ")
# 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.
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.
Example:
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
Output:
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Output:
Current value: 2
Current value: 4
Current value: 6
Current value: 8
Output:
I like apple
I like banana
I like cherry
Output:
Character: h
Character: e
Character: l
Character: l
Character: o
Output:
Countdown: 10
Countdown: 8
Countdown: 6
Countdown: 4
Countdown: 2
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
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.
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!
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.
Syntax:
while condition1: # Outer loop
# Code for the outer loop
while condition2: # Inner loop
# Code for the inner loop
Output:
123
246
369
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.
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.
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
Output:
123
246
369
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.
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.
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.
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]
Output:
1
2
3
4
5
i=0
while i < len(characters):
print(characters[i])
i += 1
Output:
a
b
c
for i in range(n):
num = int(input(f"Enter element {i + 1}: "))
numbers.append(num)
You can print all elements in a list using a loop or directly using the print() func-
tion.
Output:
apple
banana
cherry
Output:
['apple', 'banana', '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]
Output:
Sum of numbers: 15
Output:
Maximum value: 50
Output:
Reversed array: [5, 4, 3, 2, 1]
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.
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.
Syntax: array[row][column]
Example: Accessing Elements
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Traversing a 2D Array
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)
Output:
2D Array:
[1, 2, 3]
[4, 5, 6]
print("2D Array:")
for row in matrix:
print(row)
Output:
2D Array:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Operations on 2D Arrays
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
total = 0
Output:
Sum of all elements: 45
max_value = matrix[0][0]
Output:
Maximum element: 9
3. Transposing a 2D Array
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]
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.
Functions in Python
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).
Examples of Functions
Output:
Hello, welcome to Python programming!
def greet(name):
print(f"Hello, {name}! Welcome to Python programming!")
Output:
Hello, Alice! Welcome to Python programming!
Output:
The sum is: 8
1. Positional Parameters
Parameters are passed based on their position in the function call.
def subtract(a, b):
return a - b
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}!")
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.")
Example:
def multiply(a, b):
return a * b
result = multiply(4, 3)
print("The product is:", result)
Output:
The product is: 12
Combining Concepts
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
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.