Section 2: Python Basics and Syntax
2.1 Variables and Data Types
In this section, we'll delve into the concept of variables, their significance, naming conventions,
and how to assign values to them using the assignment operator.
What Are Variables and Why Are They Used?
Variables are placeholders for storing data in a program. They allow us to store values,
manipulate them, and refer to them by a name. Variables are essential for making programs
dynamic and adaptable. By using variables, we can write code that works with different values
without having to change the code itself.
Naming Conventions for Variables (snake_case)
When naming variables, it's important to follow certain naming conventions for consistency and
readability. In Python, the convention is to use lowercase letters and underscores to separate
words, known as snake_case. Variable names should be descriptive and reflect the purpose of
the stored data.
Examples of valid variable names:
● age
● name
● favorite_color
● total_amount
Assigning Values to Variables Using the Assignment Operator (=)
The assignment operator (=) is used to assign a value to a variable. The value on the right side
of the operator is assigned to the variable on the left side.
● # Assigning values to variables
● age = 30
● name = "Alice"
In this example, the variable age is assigned the value 30, and the variable name is assigned
the string "Alice".
Practice Exercises:
Exercise 1: Variable Naming
Choose three things you like and create variable names for them using snake_case.
Write a comment explaining the purpose of each variable.
Exercise 2: Variable Assignment
Create variables for your age and favorite programming language.
Assign appropriate values to these variables.
Print a message that includes both variables.
2.2 Operators and Expressions
In this section, we'll explore various types of operators in Python, including arithmetic operators,
comparison operators, and logical operators. We'll also learn how to combine these operators to
form expressions.
**2.2.1 Arithmetic Operators: +, -, *, /, %, ****
Arithmetic operators are used to perform mathematical operations on numeric values.
● +: Addition
● -: Subtraction
● *: Multiplication
● /: Division
● %: Modulus (remainder)
● **: Exponentiation
Example:
● # Arithmetic operations
● result = 10 + 5 # Addition
● result = 15 - 7 # Subtraction
● result = 3 * 4 # Multiplication
● result = 20 / 5 # Division
● result = 21 % 4 # Modulus
● result = 2 ** 3 # Exponentiation
Comparison Operators: ==, !=, <, >, <=, >=
Comparison operators are used to compare values and determine their relationship.
● ==: Equal to
● !=: Not equal to
● <: Less than
● >: Greater than
● <=: Less than or equal to
● >=: Greater than or equal to
Example:
● # Comparison operations
● result = 10 == 5 # False
● result = 15 != 7 # True
● result = 3 < 4 # True
● result = 20 > 5 # True
● result = 21 <= 4 # False
● result = 2 >= 3 # False
Logical Operators: and, or, not
Logical operators are used to combine and manipulate Boolean values.
● and: Returns True if both operands are True.
● or: Returns True if at least one operand is True.
● not: Returns the opposite Boolean value.
Example:
● # Logical operations
● result = True and False # False
● result = True or False # True
● result = not True # False
Combining Operators to Form Expressions
Operators can be combined to form more complex expressions.
● # Complex expression
● result = (10 + 5) * 3 - 7
In this example, the expression calculates (10 + 5) * 3 - 7.
Practice Exercises :
Exercise 1: Arithmetic and Comparison Operators
Write an expression that calculates the area of a rectangle given its length and width.
Write an expression that checks if a given number is even.
Exercise.2: Logical Operators
Write an expression that checks if a number is both positive and odd.
Write an expression that checks if a student is eligible for a scholarship if their GPA is
greater than 3.5 or their SAT score is above 1500
Example Project:
Project: Simple Calculator Create a simple calculator program that takes two numbers and an
operator as input from the user, then performs the corresponding arithmetic operation and
displays the result.
Project Details:
● Prompt the user for two numbers and an operator (+, -, *, /).
● Use conditional statements to determine the operation to perform.
● Perform the calculation and display the result to the user.
2.3 Conditional Statements (if, elif, else)
Conditional Statements (if, elif, else)
In this section, we'll explore conditional statements in Python, including the if, elif (else if), and
else clauses. We'll learn how to use these statements to make decisions and execute different
code blocks based on conditions.
Using if Statements to Make Decisions
The if statement is used to execute a block of code if a certain condition is True.
● # Using if statement
● age = 18
● if age >= 18:
● print("You are an adult.")
Adding elif and else Clauses for More Complex Conditions
The elif (else if) and else clauses are used to handle multiple branching conditions.
● # Using if, elif, else
● grade = 75
● if grade >= 90:
● print("You got an A.")
● elif grade >= 80:
● print("You got a B.")
● else:
● print("You need to improve your grade.")
Nested Conditionals for Multiple Branching
You can nest one conditional inside another to create multiple levels of branching.
● # Nested conditionals
● age = 20
● if age >= 18:
● if age < 21:
● print("You are an adult but not yet allowed to drink.")
● else:
● print("You are allowed to drink.")
● else:
● print("You are not an adult.")
Practice Exercises
Exercise 1: Age Categories
Write a program that takes a person's age as input and prints different messages
depending on whether they are a child (age < 13), teenager (13 ≤ age < 18), or adult
(age ≥ 18).
Exercise 2: Grading System
Create a program that prompts the user for their test score and prints their grade based
on the following scale: A (90-100), B (80-89), C (70-79), D (60-69), F (below 60).
Example Project
Project: Ticket Pricing Create a program that calculates the ticket price for a movie theater
based on the age of the customer. Use conditional statements to determine the price based on
the following criteria:
● Age < 12: Child price
● 12 ≤ Age < 18: Teen price
● 18 ≤ Age: Adult price
Project Details:
● Prompt the user for their age.
● Use conditional statements to determine the appropriate ticket price.
● Display the calculated ticket price to the user.
2.4 Loops (for, while)
In this section, we'll explore two types of loops in Python: for loops and while loops. We'll learn
how to use these loops to perform repetitive tasks and iterate over sequences.
for Loops for Iterating Over Sequences (Lists, Strings)
The for loop is used to iterate over a sequence, such as a list, string, or range. It allows you to
perform a set of actions for each item in the sequence.
● # Using a for loop with a list
● fruits = ["apple", "banana", "cherry"]
● for fruit in fruits:
● print(fruit)
● # Using a for loop with a string
● word = "Python"
● for letter in word:
● print(letter)
while Loops for Iterative Execution Based on a Condition
The while loop is used to repeatedly execute a block of code as long as a specified condition is
True.
● # Using a while loop
● count = 0
● while count < 5:
● print("Count:", count)
● count += 1
Loop Control Statements: break, continue
break: Used to exit a loop prematurely.
continue: Used to skip the rest of the current iteration and proceed to the next iteration.
● # Using break and continue
● numbers = [1, 2, 3, 4, 5]
● for num in numbers:
● if num == 3:
● break
● print(num)
● for num in numbers:
● if num == 3:
● continue
● print(num)
Practice Exercises :
Exercise 1: Multiplication Table
Write a program that takes a number as input and prints its multiplication table from 1 to
10 using a for loop.
Exercise 2: Countdown
Create a program that counts down from 10 to 1 using a while loop.
Example Project
Project: Password Validation Create a simple password validation program using a while loop.
The program should repeatedly prompt the user to enter a password until they provide the
correct password.
Project Details:
● Set a predefined password.
● Use a while loop to repeatedly prompt the user for a password.
● If the entered password matches the predefined password, print a success message and
exit the loop.
● If the entered password is incorrect, print an error message and continue the loop.
2.5 Functions and Scope
In this section, we'll delve deeper into defining and calling functions, including the use of
function parameters and return values. Additionally, we'll explore the concept of local and global
scope of variables, understanding where variables can be accessed and modified.
Defining and Calling Functions
Defining Functions: Functions are defined using the def keyword, followed by the function name
and parameters within parentheses. The code block of the function is indented beneath the
function definition.
● # Defining a function
● def greet(name):
● print("Hello,", name)
Calling Functions: To call a function, use its name followed by parentheses. If the function has
parameters, provide the values within the parentheses.
● # Calling the greet function
● greet("Alice")
Function Parameters and Return Values
Function Parameters: Parameters allow us to pass information into functions when they are
called. They help make functions more versatile and reusable.
● # Function with parameters
● def add(a, b):
● return a + b
Return Values: The return statement is used to send a value back to the caller from the
function. This value can then be used in other parts of the program.
● # Function with return value
● result = add(3, 5)
● print("Result:", result)
Local vs. Global Scope of Variables
Local Scope: Variables defined inside a function are considered local variables. They are only
accessible within the function's scope and are not visible outside of it.
● # Function with local variable
● def my_function():
● local_var = 5
● print("Local variable:", local_var)
● my_function()
Global Scope: Variables defined outside of any function are global variables. They can be
accessed and modified from anywhere in the program.
● # Global variable
● global_var = 10
● print("Global variable:", global_var)
Practice Exercises
Exercise 1: Area of a Triangle
Write a function calculate_triangle_area that calculates and returns the area of a triangle
given its base and height.
Exercise 2: FizzBuzz
Create a function fizz_buzz that takes a number as a parameter and returns "Fizz" if the
number is divisible by 3, "Buzz" if divisible by 5, and "FizzBuzz" if divisible by both 3 and
5.
Example Project
Project: Password Generator Create a password generator program using functions. The
program should allow the user to specify the length of the password and generate a random
password accordingly.
Project Details:
● Define a function generate_password that takes a length parameter.
● Use the random module to generate random characters for the password.
● Provide options for including uppercase letters, lowercase letters, digits, and special
characters.
2.6 Error Handling (try, except)
In this section, we'll dive deeper into error handling using the try and except blocks. We'll
explore how to catch and handle exceptions, including specific exceptions using except clauses,
and learn about the finally block for resource cleanup.
Using try and except Blocks to Handle Exceptions
The try block is used to enclose code that might raise an exception. The except block is used to
handle exceptions that occur within the try block.
# Using try and except blocks
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
Catching Specific Exceptions Using except Clauses
You can specify the type of exception to catch using the except clause. This allows you to
handle different exceptions differently.
# Catching specific exceptions
try:
file = open("nonexistent.txt", "r")
except FileNotFoundError:
print("Error: The file does not exist.")
except PermissionError:
print("Error: Permission denied.")
Cleaning Up Resources with finally
The finally block is used to define cleanup code that should be executed regardless of whether
an exception was raised.
# Using finally for resource cleanup
try:
file = open("data.txt", "r")
data = file.read()
except FileNotFoundError:
print("Error: The file does not exist.")
finally:
file.close()
Practice Exercises
Exercise 1: Safe Division
Write a program that takes two numbers as input and performs division. Handle the
division by zero exception using a try and except block.
Exercise 2: File Reader
Create a program that reads the content of a file specified by the user. Handle the file
not found exception using a try and except block.
Example Project
Project: Data Analyzer Create a program that reads numerical data from a file and calculates
the average value. Handle potential exceptions related to file reading and invalid data using try,
except, and finally.
Project Details:
● Prompt the user for a filename.
● Read the numerical data from the file and calculate the average.
● Handle exceptions related to file reading and invalid data.
● Close the file in the finally block.
Practice Exercises for Section 2: Python Basics and Syntax
Exercise 2.1: Working with Variables
● Declare a variable name and assign your name to it.
● Create a variable age and assign your age as a number.
● Print out a message introducing yourself using these variables.
Exercise 2.2: Arithmetic Expressions
● Calculate and print the result of 5 + 3 * 2.
● Calculate the square root of a number using the exponentiation operator (**).
Exercise 2.3: Conditional Statements
● Write a program that checks if a given number is even or odd.
● Extend the program to handle negative numbers as well.
Exercise 2.4: Loop Practice
● Write a program to print all even numbers from 1 to 20 using a for loop.
● Use a while loop to find the factorial of a given positive integer.
Exercise 2.5: Creating Functions
● Write a function that takes two numbers as arguments and returns their sum.
● Test the function with different input values.
Exercise 2.6: Exception Handling
● Write a program that takes user input as a number and handles potential value errors.
● Use a try-except block to catch the error and provide user-friendly feedback.