sdfsd2
sdfsd2
if test expression:
Body of if
else:
Body of else
if-elif ladder
Elif stands for “else if.” It enables us to check for several expressions at the same time. If the if
condition is False, the next elif block’s condition is checked, and so on. The body of else is executed if
all of the conditions are False.
if test expression:
Body of if
elif test expression:
Body of elif
else: Body of else
Nested if statements
An if…elif…else sentence can be nestled inside another if…elif…else statement. In
computer programming, this is referred to as nesting.
For Loop
The for statement allows you to specify how many times a statement or compound statement should
be repeated. A for statement’s body is executed one or more times until an optional condition is met.
Syntax -
Data Types
Basic Data Types
1. Integers (int):
o Definition: Whole numbers without a decimal point.
o Example: 5, 100, -42
o Usage: Used for counting, indexing, and mathematical operations.
o Range: Integers can be positive, negative, or zero. Python supports very large integers, limited by
available memory.
2. Floating-Point Numbers (float):
o Definition: Numbers that contain a decimal point.
o Example: 3.14, 0.99, -7.5
o Usage: Used for precise measurements, calculations involving fractions, and scientific calculations.
o Precision: Floating-point numbers are approximate and have a limited precision based on the
number of bits used to store them. They are subject to rounding errors.
3. Strings (str):
o Definition: Sequences of characters enclosed in single (') or double quotes (").
o Example: "Hello", 'World', "123"
o Usage: Used for text processing, displaying messages, and handling user input.
4. Booleans (bool):
o Definition: Represents truth values, either True or False.
o Example: True, False
o Usage: Used for conditional statements and logical operations.
5. Complex Numbers (complex)
Definition: Numbers that have both a real and an imaginary part. The imaginary part is indicated by
the letter j or J.
Format: A complex number is written as real_part + imaginary_part * j.
Example: 3 + 4j, -2 - 5j
Examples
Integer:
number = 10
print(type(number)) # Output: <class 'int'>
2. Floating-Point:
pi = 3.14159
print(type(pi)) # Output: <class 'float'>
3. Complex:
z = 2 + 3j
print(type(z)) # Output: <class 'complex'>
Compound Data Types
1. Lists (list):
o Definition: Ordered, mutable collections of items enclosed in square brackets ([]). Items can be of
different types.
o Example: [1, 2, 3, 4], ['apple', 'banana', 'cherry']
o Usage: Used to store multiple items in a single variable and to perform operations on those items.
2. Tuples (tuple):
o Definition: Ordered, immutable collections of items enclosed in parentheses (()). Items can be of
different types.
o Example: (1, 2, 3, 4), ('red', 'green', 'blue')
o Usage: Used to store multiple items in a fixed order where the data shouldn’t change.
3. Dictionaries (dict):
o Definition: Unordered collections of key-value pairs enclosed in curly braces ({}). Keys are unique, and
values can be of any type.
o Example: {'name': 'Alice', 'age': 25, 'city': 'New York'}
o Usage: Used to store and retrieve data efficiently using keys.
4. Sets (set):
o Definition: Unordered collections of unique items enclosed in curly braces ({}).
o Example: {1, 2, 3}, {'apple', 'banana'}
o Usage: Used to store unique items and perform mathematical set operations like union, intersection,
and difference.
Special Data Types
1. NoneType (None):
o Definition: Represents the absence of a value or a null value.
o Example: None
o Usage: Used to signify that a variable has no value or to represent missing or undefined data.
In Python, None is a special constant that represents the absence of a value or a null value. It’s a
unique data type, NoneType, and is used in various scenarios to indicate that something is undefined
or missing.
Mapping(dictionary)
In Python, a dictionary is a built-in data structure that allows you to store and manage data in key-
value pairs. It’s a type of mapping where each key is associated with a value, making it easy to look
up data based on a unique identifier.
Dictionaries (dict):
o Definition: Collections of key-value pairs where the data can be modified after creation.
o Operations: You can add, update, or remove key-value pairs.
o Example:
student = {"name": "Alice", "age": 18}
student["age"] = 19 # Updates the value
student["grade"] = "A" # Adds a new key-value pair
3. Sets (set):
o Definition: Unordered collections of unique elements that can be modified.
o Operations: You can add or remove elements from a set.
o Example:
numbers = {1, 2, 3}
numbers.add(4) # Adds a new element
numbers.remove(2) # Removes an element
Immutable Data Types
Immutable data types are those whose values cannot be changed after they are created. Any
operation that seems to modify the object actually creates a new object.
Tuples (tuple):
o Definition: Ordered collections of elements, similar to lists but immutable.
o Operations: Any modification creates a new tuple object.
o Example:
coordinates = (10, 20)
new_coordinates = coordinates + (30,) # Creates a new tuple
Expressions and Statements
Expression: An expression is a combination of values, variables, operators, and functions that
evaluates to a single value. Expressions can be as simple as 5 + 3 or as complex as ((2 * 3) + (4 / 2)).
Expressions always return a result.
o Example:
result = 5 * (2 + 3) # 5 * 5 = 25, so the expression evaluates to 25
Statement: A statement is a complete unit of execution that performs an action. Statements include
assignments, loops, conditionals, and function calls. Statements do not return a value but execute an
operation.
o Example:
x = 10 # This is an assignment statement
print(x) # This is a print statement
Precedence of Operators
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before operators with lower precedence. For
instance, multiplication (*) has higher precedence than addition (+), so in the expression 2 + 3 * 4, the
multiplication is performed first, giving 2 + 12, which results in 14.
Example:
result = 10 + 3 * 2 # The multiplication is done first, so 10 + (3 * 2) = 16
Evaluation of an Expression
When an expression is evaluated, Python performs operations based on operator precedence and
associativity rules. Parentheses can be used to override default precedence and force specific order
of operations.
Example:
value = (8 + 2) * 5 # Parentheses ensure that 8 + 2 is evaluated first, so (10 * 5) = 50
Type Conversion
Type conversion allows you to change the data type of a value. This can be done implicitly by Python
or explicitly by the programmer.
Explicit Conversion: Done using functions like int(), float(), and str() to convert between types.
o Example:
num_str = "123"
num_int = int(num_str) # Converts the string "123" to the integer 123
Implicit Conversion: Python automatically converts types when necessary, such as converting
integers to floats during arithmetic operations involving both types.
o Example:
result = 10 + 2.5 # The integer 10 is implicitly converted to a float, so the result is 12.5
Understanding these concepts helps you write more effective and error-free code by ensuring
expressions are evaluated correctly and data types are managed properly.
Flow of Control
The flow of control refers to the order in which the individual statements, instructions, or function
calls are executed or evaluated in a programming language. In Python, this flow is managed using
different constructs like sequences, conditions, and loops.
Use of Indentation
Python uses indentation (whitespace) to define blocks of code. Unlike some other programming
languages that use braces or keywords, Python’s indentation is crucial for defining the structure and
flow of the program. Proper indentation ensures that code blocks (such as those following
conditional statements or loops) are correctly associated with their control statements.
Example:
if True:
print("This is inside the if block") # Indented block
print("This is outside the if block") # Not indented
Iterative Statement:
Iterative statements allow you to execute a block of code repeatedly based on certain conditions. In
Python, the primary iterative statements are for loops and while loops. Here's how they work:
for Loop
The for loop iterates over a sequence (like a list, tuple, or string) or a range of numbers. It’s useful
when you know in advance how many times you want to repeat a block of code.
Example:
for i in range(5):
print(i) # Prints numbers from 0 to 4
range() Function
The range() function generates a sequence of numbers and is commonly used with for loops. It can
take up to three arguments: start, stop, and step.
Example:
for i in range(2, 10, 2):
print(i) # Prints 2, 4, 6, 8
while Loop
The while loop executes as long as its condition remains true. It’s useful when you don’t know
beforehand how many times you’ll need to repeat the code.
Example:
count = 0
while count < 5:
print(count)
count += 1 # Increment count
break and continue Statements
break: Exits the loop immediately, regardless of the loop condition.
o Example:
for i in range(10):
if i == 5:
break # Exits the loop when i is 5
print(i)
continue: Skips the current iteration and continues with the next iteration of the loop.
o Example:
for i in range(10):
if i % 2 == 0:
continue # Skips even numbers
print(i) # Prints only odd numbers
Nested Loops
Nested loops involve placing one loop inside another. They are useful for working with multi-
dimensional data or generating patterns.
Example:
for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print() # New line after inner loop
Strings
Strings are sequences of characters used to represent text in Python. They are one of the most
commonly used data types and are essential for handling textual data. Here’s a brief overview of
strings and some of their key operations.
Introduction to Strings
A string is a collection of characters enclosed in single quotes ('), double quotes ("), or triple quotes
(''' or """). Strings are immutable, meaning once created, their content cannot be changed.
Example:
message = "Hello, World!"
String Operations
1. Concatenation: Concatenation combines two or more strings into one. This is done using the +
operator.
o Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
2. Repetition: Repetition allows you to repeat a string a certain number of times using the * operator.
o Example:
echo = "Hello! " * 3
print(echo) # Output: Hello! Hello! Hello!
4. Slicing: Slicing extracts a part of the string. You use indexing to specify the start and end positions.
The syntax is string[start:end].
o Example:
phrase = "Hello, World!"
slice1 = phrase[0:5] # Extracts 'Hello'
slice2 = phrase[7:] # Extracts 'World!'
print(slice1) # Output: Hello
print(slice2) # Output: World!
o vowels is a string containing all vowel characters.
o For each character in text, check if it is in the vowels string.
o Increment count if a vowel is found.
Functions in Python
A function can be defined as the organized block of reusable code which can be called whenever
required. In other words, Python allows us to divide a large program into the basic building blocks
known as function.
Python provide us various inbuilt functions like range() or print(). Although, the user can able to
create functions which can be called user-defined functions.
Creating Function
In python, a function can be created by using def keyword.
Syntax:
def my_function():
Statements
return statement
The function block is started with the colon (:) and all the same level block statements remain at the
same indentation.
Example:
def sample(): #function definition
print ("Hello world")
Modules in Python
In python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved with
the extension (.py) is treated as the module.
Modules in Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.
Creating Module
Example: demo.py
# Python Module example
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
In the above example we have defined 4 functions sum(), sub(), mul() and div() inside a module
named demo.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of
statements as defined below.
1. import statement
2. from-import statement
Python Modules
Python modules are a great way to organize and reuse code across different programs. Think of a
module as a file containing Python code that defines functions, classes, and variables you can use in
your own programs. By importing these modules, you can make use of their functionality without
having to rewrite code.
“Modules” in Python are files that contain Python code. It can contain functions, classes, and
variables, and you can use them in your scripts. It help to reuse code and keep the project organized.
Tuple
A tuple in Python is a collection of elements that is ordered and immutable. Tuples are created using
parentheses () and can also hold elements of different data types.
Example:
my_tuple = (1, 'banana', False)
print(my_tuple)
Advantages:
Immutable – Elements cannot be changed after creation.
Faster access time compared to lists for read-only operations.
Disadvantages:
Cannot be modified once created.
Use Cases and Applications:
Used for fixed collections of elements where immutability is desired.
Returning multiple values from a function.
Set
A set in Python is a collection of unique elements that is unordered and mutable. Sets are created
using curly braces {} or the set() function.
Example:
my_set = {1, 2, 3}
print(my_set)
Advantages:
Contains unique elements only, eliminating duplicates.
Fast membership testing and operations like intersection and union.
Disadvantages:
Not ordered – Elements are not stored in a specific order.
Use Cases and Applications:
Removing duplicates from a list.
Checking for membership or common elements between sets.
Dictionary
You create dictionaries in Python using curly braces {} and colons : to define key-value pairs.
They let you store unordered and mutable collections of data.
Example:
my_dict = {'key1': 'value1', 'key2': 2}
print(my_dict)
Advantages:
Fast lookups based on keys.
Key-value pair structure allows for easy data retrieval.
Disadvantages:
Not ordered – No guarantee on the order of key-value pairs.
Use Cases and Applications:
Storing data with a key for easy retrieval.
Mapping unique identifiers to values for quick access.
Practical Implementation
Lists in Python
Lists are versatile data structures in Python that can hold heterogeneous elements.
Practical Implementation Example:
Let’s create a list of fruits and print each fruit:
numbers = [1, 2, 3]
for num in numbers[:]:
numbers.append(num * 2)
Tuples in Python
Tuples are immutable sequences in Python, typically used to represent fixed collections of items.
Practical Implementation Example:
Creating a tuple of coordinates:
point = (3, 4)
distances = {(0, 0): 0, (1, 1): 1}
distance_to_origin = distances.get(point, -1)
Common Pitfalls and Solutions:
Attempting to modify a tuple will result in an error. If mutability is required, consider using a list.
Sets in Python
Use sets in Python when you need to store unique elements, test for membership, or eliminate
duplicates without caring about order.
Practical Implementation Example:
Creating a set of unique letters in a word:
word = 'hello'
unique_letters = set(word)
print(unique_letters)
Best Practices and Optimization Tips:
Use set operations like intersection, union, and difference for efficient manipulation of data:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection = set1 & set2
Common Pitfalls and Solutions:
Accidentally mutating a set during iteration can lead to unexpected behavior. To prevent this,
operate on a copy of the set.
Dictionaries in Python
Dictionaries are key-value pairs that allow for fast lookups and mappings between items.
Practical Implementation Example:
Creating a dictionary of phone contacts:
Array
An array is defined as a container that stores the collection of items at contiguous memory locations.
The array is an idea of storing multiple items of the same type together and it makes it easier to
calculate the position of each element. It is used to store multiple values in a single variable.
Creating an Array
For creating an array in Python, we need to import the array module.
After importing, the array module we just have to use the array function which is used to create the
arrays in Python.
Syntax
print(myArr)
Explanation
Adding Element to Array
As we all know, arrays are mutable in nature. So we can add an element to the existing array.
We can use 2 different methods to add the elements to the existing array. These methods are:
.append(): This is used to add a single element to the existing array. By using the append
method the element gets added at the end of the existing array.
.extend(): This is used to add an array to the existing array. By using the extend method the
array that we have added to the extend function gets merged at the end of the existing array.
And, finally, we got the updated array where we have the combination of the original and the
new array.
Let's checkout with the help of an example of how these functions are used to add elements at the
end of the array.
Syntax
indOfElement = 2
accessedElement = myArr[indOfElement]