Module 2
Module 2
1. Variables in Python
Variables are names that act as placeholders for values and are used to store and manipulate data within a
program. Python is dynamically typed, meaning you do not need to declare the variable type explicitly—Python
will infer it based on the assigned value.
Creating and Assigning Variables
• You create variables using the assignment operator =.
username = "Alice" # A string variable
age = 25 # An integer variable
salary = 50000.75 # A float variable
Variable Naming Rules
• Identifiers (names of variables) must follow these rules:
o Must begin with a letter (a-z, A-Z) or underscore _.
o Subsequent characters can include letters, numbers (0-9), and underscores.
o Names are case-sensitive: age, Age, and AGE are different variables.
o Avoid using reserved keywords (like if, else, return).
Best Practices for Naming Variables
• Use descriptive names: Make your variables descriptive enough to make the code readable.
full_name = "John Doe"
total_cost = 450.5
• Use snake_case for multi-word variable names, as per Python convention.
2. Data Types in Python
Data types define what kind of data a variable can hold. Python has several built-in data types to manage
different types of information.
Numeric Types
1. int: Used to represent integer numbers (positive, negative, and zero).
o Example: count = 10
2. float: Represents floating-point numbers (decimal numbers).
o Example: pi = 3.14
3. complex: Used for complex numbers, which have a real part and an imaginary part.
o Example: complex_num = 3 + 4j
Text Type
1. str (String): A sequence of characters used to store text data.
o Strings are immutable, meaning they cannot be changed after creation.
o Example:
greeting = "Hello, World!"
Sequence Types
1. list: A mutable (changeable) ordered collection that can hold items of different data types.
o Created with square brackets [].
o Example:
numbers = [1, 2, 3, 4]
2. tuple: An immutable (unchangeable) ordered collection.
o Created with parentheses ().
o Example:
dimensions = (1920, 1080)
3. range: Represents a sequence of numbers, commonly used in loops.
o Example:
for i in range(5): # Outputs numbers 0 to 4
print(i)
Mapping Type
1. dict (Dictionary): A collection of key-value pairs, where each key is unique.
o Created with curly braces {}.
o Example:
student = {"name": "Alice", "age": 21, "grade": "A"}
Set Types
1. set: An unordered collection of unique elements, useful for removing duplicates.
o Created with curly braces {}.
o Example:
unique_numbers = {1, 2, 3, 4, 4} # Will store {1, 2, 3, 4}
2. frozenset: An immutable version of a set, once created it cannot be modified.
o Example:
frozen_set = frozenset([1, 2, 3])
Boolean Type
1. bool: Represents True or False values, often used in conditions and loops.
o Example:
is_active = True
3. Operators in Python
Operators perform specific operations on variables and values, and they are categorized based on the type of
operation they perform.
i. Arithmetic Operators
Arithmetic operators perform mathematical operations.
• Addition (+): Adds two operands.
result = 10 + 5 # result is 15
• Subtraction (-): Subtracts the right operand from the left operand.
result = 10 - 5 # result is 5
• Multiplication (*): Multiplies two operands.
result = 10 * 5 # result is 50
• Division (/): Divides the left operand by the right operand.
result = 10 / 5 # result is 2.0
• Floor Division (//): Divides and returns the integer part (removes decimal).
result = 10 // 3 # result is 3
• Modulus (%): Returns the remainder after division.
result = 10 % 3 # result is 1
• Exponentiation (**): Raises the left operand to the power of the right operand.
result = 2 ** 3 # result is 8
ii. Comparison (Relational) Operators
Comparison operators compare two values and return a Boolean result.
• Equal to (==): Checks if two values are equal.
result = (10 == 5) # result is False
• Not equal to (!=): Checks if two values are not equal.
result = (10 != 5) # result is True
• Greater than (>): Checks if the left value is greater than the right value.
result = (10 > 5) # result is True
• Less than (<): Checks if the left value is less than the right value.
result = (10 < 5) # result is False
• Greater than or equal to (>=): Checks if the left value is greater than or equal to the right value.
result = (10 >= 5) # result is True
• Less than or equal to (<=): Checks if the left value is less than or equal to the right value.
result = (10 <= 5) # result is False
iii. Assignment Operators
Assignment operators assign values to variables and can combine other operations with assignment.
• Assignment (=): Assigns a value.
x=5
• Addition assignment (+=): Adds and assigns.
x += 3 # Equivalent to x = x + 3
• Subtraction assignment (-=): Subtracts and assigns.
x -= 3 # Equivalent to x = x - 3
• Multiplication assignment (*=): Multiplies and assigns.
x *= 3 # Equivalent to x = x * 3
• Division assignment (/=): Divides and assigns.
x /= 3 # Equivalent to x = x / 3
iv. Logical Operators
Logical operators are used to combine multiple conditions and return a Boolean value (True or False). They are
especially useful in conditional statements.
Logical Operators in Python
1. and: Returns True if both conditions are True.
python
Copy code
x=5
y = 10
if x > 2 and y > 5:
print("Both conditions are true")
# Output: Both conditions are true
2. or: Returns True if at least one of the conditions is True.
python
Copy code
if x > 10 or y > 5:
print("At least one condition is true")
# Output: At least one condition is true
3. not: Returns the opposite Boolean value of a condition. If the condition is True, not will make it False,
and vice versa.
if not x > 10:
print("x is not greater than 10")
# Output: x is not greater than 10
v. Bitwise Operators
Bitwise operators perform operations on binary representations of numbers. They treat numbers as a series of
bits (0s and 1s) and operate at the binary level.
Bitwise Operators in Python
1. AND (&): Sets each bit to 1 if both bits are 1.
a=5 # 5 in binary: 0101
b=3 # 3 in binary: 0011
result = a & b # result is 1 (binary: 0001)
2. OR (|): Sets each bit to 1 if at least one of the bits is 1.
result = a | b # result is 7 (binary: 0111)
3. XOR (^): Sets each bit to 1 if only one of the bits is 1.
result = a ^ b # result is 6 (binary: 0110)
4. NOT (~): Inverts all the bits (turns 1 into 0 and vice versa). For example, ~a inverts the bits of a.
result = ~a # result is -6 (binary: -0110 in 2's complement form)
5. Left Shift (<<): Shifts bits to the left by the specified number of positions, adding zeros on the right.
result = a << 1 # result is 10 (binary: 1010), shifts 0101 to 1010
6. Right Shift (>>): Shifts bits to the right by the specified number of positions.
result = a >> 1 # result is 2 (binary: 0010), shifts 0101 to 0010
vi. Membership Operators
Membership operators are used to check if a value exists within a sequence, such as a string, list, tuple, or
dictionary.
Membership Operators in Python
1. in: Returns True if a value is found in the sequence.
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
2. not in: Returns True if a value is not found in the sequence.
print("grape" not in fruits) # Output: True
Membership operators are useful for checking the presence of an element in lists, strings, or dictionaries. For
example:
name = "Alice"
print("A" in name) # Output: True
print("Z" not in name) # Output: True
vii. Identity Operators
Identity operators are used to compare the memory locations of two objects, which means they check if two
objects are actually the same object (not just having the same content but the same location in memory).
Identity Operators in Python
1. is: Returns True if both variables refer to the same object in memory.
x = [1, 2, 3]
y=x
print(x is y) # Output: True, because y points to the same list object as x
2. is not: Returns True if both variables do not refer to the same object in memory.
z = [1, 2, 3]
print(x is not z) # Output: True, because z is a different list object
Identity operators are helpful when you need to compare references rather than values, especially when working
with mutable data types like lists and dictionaries.
4. Branching Statements in Python
Branching statements allow for conditional execution of code blocks.
if Statement
The if statement checks a condition and executes a block of code if the condition is True.
x = 10
if x > 5:
print("x is greater than 5")
if-else Statement
An if-else statement provides an alternative block of code to execute if the condition is False.
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
elif (else if) Statement
The elif statement adds multiple conditions, allowing for multiple branches.
x=7
if x > 10:
print("x is greater than 10")
elif x == 7:
print("x is equal to 7")
else:
print("x is less than 10 and not equal to 7")
Nested if Statements
Nested if statements are if statements within other if statements.
x = 10
y = 20
if x > 5:
if y > 15:
print("Both x and y satisfy the conditions")
else:
print("Only x satisfies the condition")
else:
print("x does not satisfy the condition")
These are the fundamental concepts of Python variables, data types, operators, and branching statements. Each
of these topics forms a crucial part of Python programming.
Nested if-else Statements in Python
In Python, a nested if-else statement refers to an if-else statement inside another if-else block. Nesting is useful
when you need to evaluate multiple conditions that depend on one another, allowing for more complex
decision-making.
Here's a breakdown of the nested if-else structure with examples to illustrate how it works.
Syntax of Nested if-else Statements
if condition1:
# Executes if condition1 is True
if condition2:
# Executes if condition2 is True (inside condition1)
# Code block for condition1 and condition2
else:
# Executes if condition2 is False (inside condition1)
# Code block for condition1 and not condition2
else:
# Executes if condition1 is False
# Code block for not condition1
Example 1: Checking Multiple Conditions with Nested if-else
Consider an example where we check the score of a student and assign a grade based on their performance.
score = 85
Summary
• Nested if-else statements allow you to handle multiple conditions with dependencies.
• They help in creating structured decision trees, useful in scenarios that require multiple levels of checks.
• However, over-nesting can make code harder to read. For complex conditions, consider using elif or
logical operators (and, or) to simplify the structure when possible.