sdfsd5
sdfsd5
Conditional statements in Python are used to execute specific blocks of code based on certain
conditions. Let’s explore the different types of conditional statements, along with flowcharts and
examples of simple programs.
Conditional Statements
1. if Statement The if statement checks a condition and executes the associated block of code if the
condition is true.
o Example:
temperature = 30
if temperature > 25:
print("It's a hot day!")
2. if-else Statement The if-else statement provides an alternative block of code to execute if the
condition is false.
o Example:
temperature = 20
if temperature > 25:
print("It's a hot day!")
else:
print("It's a cool day!")
3. if-elif-else Statement The if-elif-else statement allows multiple conditions to be checked in sequence.
The first true condition's block is executed, and if none are true, the else block is executed.
o Example:
temperature = 10
if temperature > 30:
print("It's a very hot day!")
elif temperature > 20:
print("It's a warm day!")
elif temperature > 10:
print("It's a cool day!")
else:
print("It's a cold day!")
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 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:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Best Practices and Optimization Tips:
Use list comprehension for concise and efficient code:
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]