Python List

Python List Introduction:

Lists are one of the most commonly used data structures in Python. A list is a collection of elements, which can be of any type, including numbers, strings, and other lists etc. Lists are mutable, which means you can make changes in the list by adding, removing, or changing elements.

List declaration:

To declare a list in Python, you can use square brackets [] and separate the elements with commas. Here’s an example:

new_list = [ 1, 2, 3, 4, 5 ]

In the above example, we created a list called new_list that contains five integers.

You can also create an empty list by using the list() function or just an empty set of square brackets [].  Here are some examples:

list_1 = list()
list_2 = []

Both of the examples above create an empty list called empty_list_1 and list_2.

You can also create a list of a specific size filled with a default value using the * operator.  Here’s an example:

empty_list_1 = []
empty_list_2 = list()

In the example above, we created a list called my_list that contains three 1 values.

my_list = [1, 1, 1]

Python list features:

  1. Mutable: Lists are mutable, meaning you can modify their elements by assigning new values to specific indices.
  2. Ordered: Lists maintain the order of elements as they are added.
  3. Dynamic Size: Python lists can dynamically grow or shrink in size as elements are added or removed.
  4. Heterogeneous Elements: Lists can contain elements of different data types. For example, a single list can store integers, floats, strings, or even other lists.
  5. Indexing and Slicing: You can access individual elements in a list using square bracket notation and their index. Additionally, you can slice lists to extract a portion of elements by specifying start and end indices.
  6. Iteration: Lists can be easily iterated over using loops or list comprehensions, allowing you to process each element or perform operations on the entire list.
  7. Built-in Functions: Python provides a range of built-in functions specifically designed for working with lists. These include functions like `len()`, `max()`, `min()`, `sum()`, `sorted()`, and more.
  8. Versatile Data Structure: Lists are a versatile data structure used in a variety of scenarios.
  9. List Comprehensions: Python allows you to create new lists by performing operations on existing lists using concise and expressive syntax called list comprehensions.
  10. Extensive Methods: Python lists come with a range of built-in methods that enable various operations like adding or removing elements, sorting, reversing, searching, and more.

Python List Indexing and Slicing

In Python first element in the list has an index of 0. You can access elements in a list by their index using square brackets. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Access the first element
first_element = my_list[0] # 'apple'

# Access the second element
second_element = my_list[1] # 'banana'

# Access the third element
third_element = my_list[2] # 'cherry'

# Print the elements
print("First element:", first_element)
print("Second element:", second_element)
print("Third element:", third_element)

You can also use negative indexing to access the list elements in the reverse order. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Access the last element
last_element = my_list[-1] # 'cherry'

# Access the second-to-last element
second_last_element = my_list[-2] # 'banana'

# Access the third-to-last (or first) element
third_last_element = my_list[-3] # 'apple'

# Print the elements

print("Last element:", last_element)
print("Second-to-last element:", second_last_element)
print("Third-to-last element:", third_last_element)

Slicing rules to create a sublist:

Here are the rules for slicing in Python:

  1. Slicing uses the colon : operator to specify a range of indices. The syntax is my_list[start_index:end_index:step].
  2. The start_index is the index of the first element to include in the slice. If not specified, it defaults to 0.
  3. The end_index is the index of the first element to exclude from the slice. If not specified, it defaults to the length of the list.
  4. The step parameter specifies the step size between elements in the slice. If not specified, it defaults to 1.
  5. All parameters can be negative, in which case they specify the index relative to the end of the list. For example, my_list[-1] refers to the last element of the list.
  6. Slicing returns a new list that contains the specified range of elements from the original list.

You can also use slicing to access a subset of the list. Slicing allows you to extract a range of elements from the list. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']

# Slice to get the first three elements
first_three = my_list[0:3] # ['apple', 'banana', 'cherry']

# Slice to get elements from index 2 to the end
from_second_onwards = my_list[2:] # ['cherry', 'date', 'elderberry']

# Slice to get the last two elements
last_two = my_list[-2:] # ['date', 'elderberry']

# Slice with a step of 2 (every second element)
every_second = my_list[::2] # ['apple', 'cherry', 'elderberry']

# Print the results
print("First three elements:", first_three)
print("From second onwards:", from_second_onwards)
print("Last two elements:", last_two)
print("Every second element:", every_second)

In the example above, we used slicing to extract a subset of the list that starts at index 0 and ends at index 3 (excluding index 3).


Updating list values:

Lists in Python are mutable, and their values can be updated by using the slice and assignment the ( = ) operator.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Remove elements at indices 1 to 3
my_list[1:4] = []

# Print the updated list
print(my_list)

Iterating over a list

We can use a for loop to iterate over the list elements. Here’s an example:

# Define a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date']

# Use a for loop to iterate over the list
for fruit in fruits:
print(fruit)

Membership operator in list

We can use operator (i.e. in or not in) on list elements. If an element is in list then it returns True. If an element is not in list it return False. Here’s an example:

# Example list
fruits = ['apple', 'banana', 'cherry', 'date']

# Using 'in' to check if an element is in the list
print('apple' in fruits) # Output: True
print('orange' in fruits) # Output: False


# Using 'not in' to check if an element is not in the list
print('grape' not in fruits) # Output: True
print('banana' not in fruits) # Output: False

Repetition on list

We can use the (*) operator for the repetition of a list. Here’s an example:

# Example list
fruits = ['apple', 'banana', 'cherry']

# Using * operator for repetition
repeated_list = fruits * 3

print(repeated_list)
# Output: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry']

Concatenation of a list

We can use the (+) operator for the concatenation of a list. Here’s an example:

# Example lists
list1 = ['apple', 'banana']
list2 = ['cherry', 'date']

# Using + operator for concatenation
combined_list = list1 + list2

print(combined_list)
# Output: ['apple', 'banana', 'cherry', 'date']

Python String

String Introduction:

A string is a sequence of characters. In Python, you can define a string using either single quotes () or double quotes (), or triple quotes (”’ or “””) for multiline strings. Here are some examples:

Re-assign Strings:

In Python, you can reassign a string to a new value by simply assigning the new value to the variable that holds the string.  Here’s an example:

# Initial string assignment
my_string = "Hello, World!"
print("Original string:", my_string)

# Reassigning the string to a new value
my_string = "Welcome to Python!"
print("Reassigned string:", my_string)

In the example above, the first print statement outputs “Hello, World!” because my_string is initially assigned that value. Then, my_string is reassigned to “Sqatools” and the second print statement outputs the new value.

# Example to demonstrate string immutability in Python

# 1). String Concatenation
greeting = "Hello"
new_greeting = greeting + ", World!"
print("Original string (after concatenation):", greeting) # Output: Hello
print("New string (concatenation result):", new_greeting) # Output: Hello, World!

# 2). String Replacement
my_string = "Hello, Python!"
new_string = my_string.replace("Python", "World")
print("\nOriginal string (after replacement):", my_string) # Output: Hello, Python!
print("New string (replacement result):", new_string) # Output: Hello, World!

# 3). String Slicing
text = "Immutable"
sliced_text = text[:3] # Taking the first three characters
print("\nOriginal string (after slicing):", text) # Output: Immutable
print("Sliced string (slicing result):", sliced_text) # Output: Imm

Deleting string:

In Python, you cannot delete individual characters in a string because strings are immutable. However, you can delete the entire string object from memory using the del statement.  Here’s an example:

In the example above, the first print statement outputs the value of my_string, which is “Hello, World!”. Then, the del statement deletes the my_string object from memory. When we try to print my_string again, we get a NameError because the variable no longer exists.


String formatting methods:

Python provides several methods for formatting strings. Here are the most commonly used methods:

  1. The % operator: This operator allows you to format strings using placeholders, which are replaced with values at runtime. Here’s an example:
# Using the % operator for string formatting
name = "Alice"
age = 25

formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, %s and %d are placeholders for the name and age variables, respectively. The values of these variables are provided in a tuple that follows the % operator.


  1. The str.format() method: This method allows you to format strings using placeholders that are enclosed in curly braces. Here’s an example:
# Using the str.format() method for string formatting
name = "Alice"
age = 25

formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, {} is a placeholder for the name and age variables. The values of these variables are provided as arguments to the str.format() method.


  1. F-strings: It allows you to embed expressions inside placeholders that are enclosed in curly braces preceded by the f character. Here’s an example:
# Using f-strings for string formatting
name = "Alice"
age = 25

# Embedding variables directly into the string
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, the f character before the string indicates that it is an f-string. The expressions inside the curly braces are evaluated at runtime and the resulting values are inserted into the string.


String operators:

In Python, strings support several operators that can be used to perform various operations on strings. Here are some of the most commonly used string operators:

  1. Concatenation (+): The + operator can be used to concatenate two or more strings. Here’s an example:
# Using the + operator to concatenate strings
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2 # Adding a space between the words

print(combined_str)
# Output: Hello World
  1. Repetition (*): The * operator can be used to repeat a string a certain number of times. Here’s an example:
# Using the * operator to repeat a string
str1 = "Hello "
repeated_str = str1 * 3 # Repeating the string 3 times

print(repeated_str)

# Output: Hello Hello Hello
  1. Membership (in): The in operator can be used to check if a substring exists within a string. It returns True if the substring is found, and False otherwise. Here’s an example:
# Using the 'in' operator to check membership
sentence = "Python is awesome!"

# Checking if a substring exists within the string
substring = "Python"
result = substring in sentence

print(result)
# Output: True
  1. Indexing ([]): The [] operator can be used to access individual characters within a string. You can use a positive index to access characters from the beginning of the string, and a negative index to access characters from the end of the string. Here’s an example:
# Using the [] operator for indexing a string
my_string = "Python"

# Accessing characters using positive indices
first_char = my_string[0] # First character
last_char = my_string[5] # Last character (index 5 for "n")

print("First character:", first_char) # Output: P
print("Last character:", last_char) # Output: n

# Accessing characters using negative indices
second_last_char = my_string[-2] # Second last character (index -2 for "o")
print("Second last character:", second_last_char) # Output: o
  1. Slicing ([start:end]): The [] operator can also be used to extract a substring (or slice) from a string. The start argument specifies the starting index of the slice (inclusive), and the end argument specifies the ending index of the slice (exclusive). Here’s an example:
# Using the [] operator for string slicing
my_string = "Python Programming"

# Extracting a substring using slicing
substring = my_string[0:6] # From index 0 to 5 (6 is exclusive)
print(substring) # Output: Python
  1. Comparison (==, !=, <, <=, >, >=): The comparison operators can be used to compare two strings alphabetically.
# Comparison of strings using various operators
string1 = "Apple"
string2 = "Banana"

# Checking if the strings are equal
print(string1 == string2) # Output: False

# Checking if the strings are not equal
print(string1 != string2) # Output: True

# Checking if string1 is alphabetically less than string2
print(string1 < string2) # Output: True

# Checking if string1 is alphabetically greater than string2
print(string1 > string2) # Output: False

# Checking if string1 is alphabetically less than or equal to string2
print(string1 <= string2) # Output: True

# Checking if string1 is alphabetically greater than or equal to string2
print(string1 >= string2) # Output: False

String indexing and slicing:

Indexing:

Indexing: Each character in a string is assigned an index starting from 0. You can access a particular character in a string using its index. Here’s an example:

# Using indexing to access characters in a string
my_string = "Python"

# Accessing individual characters using their indices
first_char = my_string[0] # First character
second_char = my_string[1] # Second character
last_char = my_string[5] # Last character

print("First character:", first_char) # Output: P
print("Second character:", second_char) # Output: y
print("Last character:", last_char) # Output: n
Slicing:

You can extract a portion of a string using slicing. Slicing is done using the [] operator, with two indices separated by a colon (:) inside the brackets. Here’s an example:

# Using slicing to extract a portion of a string
my_string = "Python Programming"

# Slicing from index 0 to 6 (exclusive of index 6)
substring = my_string[0:6] # This gives 'Python'

print(substring) # Output: Python

In the example above, my_string[0:5] returns the first five characters of the string, my_string[:5] returns all the characters up to the fifth character, and my_string[-5:] returns the characters from the fifth-last to the last character.

Note that the first index in a slice is inclusive and the second index is exclusive. So, my_string[0:5] returns characters from index 0 to index 4, but not the character at index 5.

In addition to the two indices separated by a colon, you can also add a third index to specify the step value. Here’s an example:

# Using slicing with a step
my_string = "Python Programming"

# Extracting every second character from index 0 to index 12
substring = my_string[0:13:2] # From index 0 to 12, taking every second character

print(substring) # Output: Pto rg

Python Loops

Python Loops Introduction

Loops are one of the most important concepts in Python. They allow you to execute a block of code repeatedly, which makes tasks like iterating through lists, performing calculations, or automating repetitive operations much easier

A loop in Python is used to execute a set of statements multiple times until a certain condition is met. This helps avoid writing the same code over and over again. There are mainly two types of loops in Python:

  • for loop
  • while loop

The range() function is commonly used in loops to generate a sequence of numbers. It’s very useful when you want to repeat an action a specific number of times.

Syntax:

range(start, stop, step)

  • start – the starting number (default is 0)
  • stop – the number at which the range ends (not included)
  • step – the difference between each number (default is 1)
Example 1:
Here, the loop runs 5 times, printing numbers from 0 to 4.

for i in range(5):
print(i)
Output :
0
1
2
3
4
Example 2:

for i in range(2, 10, 2):
    print(i)
Output :
2
4
6
8

A for loop is used when you know how many times you want to execute a block of code. It’s great for iterating through sequences like lists, tuples, or strings.

# Example 1: Iterating through a list|

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Output: 

apple
banana
cherry
# Example 2: Iterating through a string

for letter in "Python":
    print(letter)
Output:
P
y
t
h
o
n

A nested loop means having one loop inside another. This is often used for working with multidimensional data, like matrices or tables.

# Example:
for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3

Here, the inner loop runs completely every time the outer loop runs once

A while loop continues to run as long as a given condition is True. You use it when you don’t know how many times you need to repeat a block of code.

Example:

count = 0
while count < 5:
    print("Count is:", count)
    count += 1
Output:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4

If the condition never becomes False, the loop runs forever (an infinite loop). To avoid that, always make sure the condition changes within the loop.


The break statement is used to stop a loop immediately, even if the loop’s condition is still True.

# Example:

for i in range(10):
    if i == 5:
        break
    print(i)
Output:

0
1
2
3
4

The loop stops when i equals 5, skipping the rest of the iterations.

The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next one

# Example:

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
Output:

1
3
5
7
9

Here, every time i is even, the loop skips the print() statement and continues to the next iteration.

You can use both break and continue in the same loop to control its flow precisely.

# Example:

for i in range(10):
    if i == 3:
        continue
    if i == 8:
        break
    print(i)
Output:

0
1
2
4
5
6
7

When i is 3, the continue statement skips that iteration. When i reaches 8, the break statement stops the loop entirely

Here’s a simple example that uses both a while loop and break:

password = "python123"
attempts = 0

while attempts < 3:
    guess = input("Enter password: ")
    if guess == password:
        print("Access granted!")
        break
    else:
        print("Wrong password, try again.")
        attempts += 1
else:
    print("Too many attempts. Access denied.")

# This loop lets the user try three times before locking them out

ConceptDescriptionExample
for loopRuns a block of code a set number of timesfor i in range(5): print(i)
while loopRuns as long as a condition is truewhile x < 10:
range()Generates a sequence of numbersrange(1, 10, 2)
breakStops the loopif i == 5: break
continueSkips current iterationif i % 2 == 0: continue
Nested loopA loop inside anotherfor i in range(3): for j in range(3): …

Python DataTypes

Introduction :

In Python, every value has a specific data type associated with it. Data types define the nature of the variables, objects, or values you can work with in your code. Understanding different data types is crucial for effective programming. Let’s explore the commonly used data types in Python.


Numeric Types:

  • Integer (int): Represents whole numbers without decimal points.

In Python, the integer data type (int) represents whole numbers without any decimal points. Integers can be positive or negative, and they have no limit on their size, allowing you to work with both small and large numbers.

Example:

num1 = 10
  • Floating-Point (float): Represents decimal numbers.

In Python, the float data type represents decimal numbers. Floats are used to represent real numbers, including both positive and negative values. Unlike integers, floats can have decimal points and can represent numbers with fractional parts.

Example:

num2 = 3.14
  • Complex (complex): Represents numbers with real and imaginary parts.

In Python, the complex data type represents numbers with both real and imaginary parts. Complex numbers are often used in mathematical and scientific computations that involve complex arithmetic operations.

Example:

num3 = 4 + 5j

Sequence Types:

  • String (str): Represents a sequence of characters enclosed in quotes.

In Python, a string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). Strings are immutable, which means once created, they cannot be modified. However, you can create new strings based on existing ones.

Example:

name = "John"
  • List (list): Represents an ordered collection of items enclosed in square brackets.

In Python, a list is a versatile and mutable data type that represents an ordered collection of items. Lists can contain elements of different data types, such as numbers, strings, or even other lists. Lists are denoted by square brackets [ ].

Example:

numbers = [1, 2, 3, 4, 5]
  • Tuple (tuple): Represents an ordered collection of items enclosed in parentheses.

In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning they cannot be modified once created. Tuples are typically denoted by parentheses ( ) or can be created without any delimiters.

Example:

coordinates = (10, 20, 30, 40)

Dictionary (dict):

Represents a collection of key-value pairs enclosed in curly braces.

In Python, a dictionary is an unordered collection of key-value pairs. It is also known as an associative array or a hash map. Dictionaries are enclosed in curly braces { }, and each item in the dictionary is represented as a key-value pair separated by a colon (:).

Example:

person = {"name": "John", "age": 25, "city": "New York"}

Set Types:

Set (set): Represents an unordered collection of unique items enclosed in curly braces.

In Python, a set is an unordered collection of unique elements. Sets are denoted by curly braces { }. Each element in a set must be unique, and duplicate values are automatically removed. Sets are mutable, meaning you can modify them after creation.

Example:

fruits = {"apple", "banana", "orange"}

Boolean Type:

Boolean (bool): Represents either True or False.

In Python, the Boolean data type represents truth values. A Boolean value can be either True or False. Booleans are often used for logical operations and comparisons.

In Python, the keywords True and False (with the first letter capitalized) are used to represent Boolean values.

Example:

is_active = True
is_admin = False

Python Conditional Statements

Introduction:

In Python, the if-else statement allows you to execute different blocks of code based on certain conditions. It provides a way to make decisions and control the flow of your program.

The `if` statement is the fundamental building block of a conditional statement. It allows you to execute a block of code if a certain condition is true. The syntax of the `if` statement is as follows:

if condition:
# Code block to execute if the condition is True

The `else` statement is used in conjunction with the `if` statement. It provides an alternative block of code to execute when the condition in the `if` statement is false. The syntax is as follows:

The basic syntax of an if-else statement in Python is as follows:

if condition:
# Code block to execute if the condition is True
else:
# Code block to execute if the condition is False

The condition is an expression that evaluates to either True or False. If the condition is True, the code block immediately following the if statement will be executed. Otherwise, if the condition is False, the code block following the else statement will be executed.

Let’s look at an example to understand it better. Suppose we want to check whether a given number is positive or negative:

number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
else:
print("The number is negative or zero.")

In this example, we use the input() function to get a number from the user, convert it to an integer using int(), and store it in the number variable. The if-else statement then checks whether the number is greater than zero. If it is, it prints “The number is positive.” Otherwise, it prints “The number is negative or zero.”


The `elif` statement allows you to check additional conditions after an initial `if` statement. It provides a way to handle multiple cases within the same conditional statement. The syntax is as follows:

Here’s an example that checks whether a number is positive, negative, or zero:

number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

In this case, the elif statement allows us to check an additional condition. If the first condition is False, it moves to the elif statement and checks whether the number is less than zero. If that condition is True, it prints “The number is negative.” Finally, if both the first and second conditions are False, it executes the code block under the else statement and prints “The number is zero.”


In Python, nested if-else statements allow you to have if-else statements within other if-else statements. They provide a way to handle complex conditions and execute different blocks of code based on multiple conditions. The basic syntax of a nested if-else statement in Python is as follows:

if condition1:
# code to execute if condition1 is true
if condition2:
# code to execute if condition1 and condition2 true
else:
# code execute if condition1 true but condition2 false
else:
# code to execute if condition1 is false

In a nested if-else statement, the inner if-else statement is indented further to the right than the outer if-else statement. The inner if-else statement is evaluated only if the condition of the outer if statement is `True`. Here’s an example:

age = 25
has_membership = True

if age >= 18:
if has_membership:
print("Welcome to the exclusive club!")
else:
print("Membership required for entry.")
else:
print("You must be 18 or older to enter.")

Python Variables

Introduction:

Variables are an important concept in any programming language, including Python. In simple language, a variable is a named location in memory that stores a value. In Python, you can use variables to store any type of data, including numbers, strings, and even complex data structures like lists and dictionaries.

Creating Variables in Python:

To create a variable in Python, you need to give it a name and assign a value to it. Here’s an example:

Name = “Omkar”
Age = 25
Profession = “Software Engineer “

Python Variable Naming Rules:

When creating variables in Python, there are a few rules that you need to follow:
1). Variable names must start with a letter or underscore (_), followed by any combination of letters, digits, and underscores.
2). Variable names are case-sensitive, which means name and Name are two different variables.
3). A variable name cannot start with a number.
4). A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ ).


Python Variable Types:

1). Numbers: Consists of integers, floating-point numbers, and complex numbers.
2). Strings: Consist of characters in quotes.
3). Booleans: Consist of True or False values.
4). Lists: Consist of ordered sequences of elements.
5). Tuples: Consist of ordered, immutable sequences of elements.
6). Sets: Consist of unordered collections of unique elements.
7). Dictionaries – Consist of unordered collections of key-value pairs.

Checking Types of the Variable:

First, we will create some variables.

Name = “ Omkar “
Age = 25
Height = 5.8 ft

To check the type of the variable use the type() function.

print(type(Name))    # Output: <class ‘str’>
print(type(Age))          # Output: <class ‘int’>
print(type(Height))      # Output: <class ‘float’>

To check the address of the variable, use the id() function.

print(id(Name))      # Output: 2623848788368
print(id(Age)) # Output: 140718085367336
print(id(Height)) # Output: 2623846066576

Value Assignment:

To assign the value to a variable, use the equal sign (=).
Example:
A = 10
Assign the same value to multiple variables.
A = B = C = 10

Multiple Value Assignment:

We can assign different values to different variables at the same time. We separate the variables and their values by commas ‘,’.

Example:
a, b, c = 40, 50, 60
Here,
Value of variable a is 40 , b is 50 and c is 60.

Scope of Variable:

In Python, the scope of a variable determines where in the code the variable can be accessed and used. The scope of a variable is defined by where the variable is created and assigned a value.
There are two types of variable scopes in Python: global scope and local scope.

1). Global Scope:
Variables created outside of any function or class have a global scope. This means that they can be accessed and modified from anywhere in the code, including within functions and classes.
Example:

number = 100         # global variable

def print_number():
print(number) # accessing global variable

def modify_number():
global number # declaring number as global variable
number = 200 # modifying global variable

print_number() # Output: 100
modify_number()
print_number() # Output: 200

In the example above, the variable number is declared outside of any function, so it has a global scope. The function print_number() can access and print the value of number, and the function modify_number() can modify the value of number by declaring it as a global variable using the global keyword.

2). Local Scope:
Variables created inside a function or class have a local scope. This means that they can only be accessed and modified within that function or class.
Example:

def my_function():
number = 100 # local variable
print(number) # accessing local variable

my_function() # Output: 100
print(number) # NameError: name 'number' is not defined

Basic Mathematical Operations Using Variables:

Creating variables and assigning values to them:
a, b = 10 , 20

Performing operations and printing output:

print(a+b) # Addition       Output: 30
print(a-b) # Subtraction Output: -10
print(a*b) # Multiplication Output: 200
print(a/b) # Division Output: 0.5