What is Python?
Python is a popular programming language known for its simplicity and ease of use. It was developed by Guido van Rossum and first released in 1991. Python is a high-level, interpreted, interactive and object-oriented scripting language. It is easy to learn compared to other programming languages.
Uses of Python (Application of Python):
Python is widely used programming language. It is used for a variety of applications such as Software development, Web development, Game development, Machine Learning and Artificial Intelligence, Data Science, Scientific Computing, Mobile Applications and many more.Python can be used to handle big data and perform complex mathematics. It can easily connect with the database system to store and modify crucial data.
Features of Python (Characteristics of Python):
Easy to learn: Python is the easiest programming language to learn. It has a clean and readable syntax. It looks similar to English, which makes it beginner-friendly.
Easy to Read and Write: Python’s syntax is designed to be clear and easy to understand, which makes it easier for developers to read and write code. Python is designed to be highly readable.
Easy to maintain: Python source code is generally considered easy to maintain due to its clear syntax and readability.
Python is a beginner’s language: Python is a great language for the beginners. Its syntax is simple, and straightforward, hence for beginners, it is the best choice.
Versatile language: Python is a general-purpose programming language that can be used for a lot of different purposes like web development, scientific computation, data analysis etc.
Objective of Python:
The main objective of Python is to provide a powerful, easy-to-learn, and easy-to-use programming language that emphasizes code readability and simplicity, making it accessible for both beginners and experienced developers.
Below are the key objectives of Python:
Code Readability: Python uses clear and straightforward syntax, making it easy to read and understand, even for beginners.
Easy Learn and use: Python’s syntax is designed to be clear and beginner-friendly, allowing new programmers to quickly grasp programming concepts.
Cross-Platform Compatibility: Python is platform-independent, meaning that code written in Python can run on various operating systems without modification.
Versatility: Python can be used for a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, automation, and more.
Support for Multiple Programming Paradigms: Python supports procedural, object-oriented, and functional programming styles, allowing developers to choose the best approach for their projects.
Why to use python?
Python is widely used because of its simplicity, versatility, and powerful features. It is a versatile and widely-used programming language that offers numerous advantages, making it a popular choice among developers, data scientists, and researchers.
Here are the main reasons why we should use Python:
Easy to learn and Use: Python has a simple and readable syntax, which makes it an excellent choice for beginners. Its clear structure allows new programmers to quickly grasp concepts and start coding.
Versatility: Python can be used for various applications, including web development (server side), software development, data analysis, automation, game development, scientific computing, and more.
Cross-Platform Compatibility: Python works on different platforms (operating systems) including Windows, macOS, and Linux, allowing developers to write code that can run on multiple platforms without modification.
Used by Top Companies: Companies like Google, IBM, Instagram, Netflix, and Spotify use Python for development, data analysis, and AI.
Job Opportunities: Python is in high demand in the job market, particularly in fields like data science, web development, and automation, making it a valuable skill for career advancement.
Why Python is Popular?
Python is popular for several key reasons that make it one of the most widely used programming languages today:
Easy to learn and use: Python’s syntax is simple similar to English language makes it beginner-friendly. Python has a simple and readable syntax, which makes it an excellent choice for beginners.
Versatility: Python is a general-purpose programming language that can be used for a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, automation, and more.
Platform Independent: Python code can run on various operating systems like Windows, macOS, and Linux without modification.
Integration Capabilities: Python can easily integrate with other languages and technologies, making it a flexible choice for developers who need to work with different systems.
Strong Industry Adoption: Many companies and organizations including Google, IBM, NASA, Netflix, Spotify use Python for various applications, which further boosts its credibility and encourages new developers to learn it.
Python Programming
Python programming refers to the process of writing code in the Python programming language to create software applications, automate tasks, analyze data, and more.
Python programming is a powerful skill that can be applied in various domains, from web development to data science and automation. Whether a beginner or an experienced developer, Python offers tools and libraries to help achieve our goals.
To start programming in Python, we have to,
· Install Python from the official website (python.org).
· Use an Integrated Development Environment (IDE) like PyCharm, VSCode, or Jupyter Notebook.
Variables in Python
Variables are reserved memory locations to store values. Variables are like containers that are used to store values. In Python, variables are case sensitive and consist of letters, numbers, and underscores. The first character in variable’s name cannot be a number.
Rules for Naming Variables:
- Variable names must start with a letter (a-z, A-Z) or an underscore _.
- Variable names cannot start with a number.
- They can contain letters (both uppercase and lowercase), numbers, and underscores.
- Variable names are case-sensitive, so age and Age are considered different variables.
- Keywords (like
for,if,else, etc.) cannot be used as variable names
For example:
Valid Variable Names:
age, _count, roll_no, total_price_2
Invalid Variable Names:
1st_name # Starts with a digit
roll-no # Contains a hyphen
for # Is a Python keyword
roll no # Contains a space
Data Types in Python
Data types represent the type of data. In python, every value has a datatype, but we need not declare the datatype of variables. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
There are different data types in Python, such as integer, float, string, Booleans, list, tuple, dictionary, set etc.
Integer (int):
The integer data type, represented by the int class, is used to store whole numbers. These numbers can be positive, negative, or zero, and they do not include any fractional or decimal components, like 1, 2, 3,……. 0, -1, -2, -3 etc.
Example:
x = 10 # An integer assignment
Floating-point (float):
The float data type represents real numbers, which are numbers that can have a fractional or decimal component. Float data type is used to store numbers with a decimal point such as 1.2, 3.142, -0.5 etc.
Example:
kilometer =1.5 # A Floating point
String (str):
The string data type represented by the keyword str, is used to store sequences of characters essentially representing text. String values are defined by enclosing them within single quotes ( ‘ ‘ ), double quotes ( “ “ ), or triple quotes ( ‘’’ ‘’’ or “ ” ” “ “ “ ). Triple quotes are particularly useful for multi-line strings.
Example:
name = ”Eliza” # String assignment
Boolean (bool):
Boolean data type represents one of two values : True or False. These values are fundamental for logical operations, conditional statements and controlling program flow. The type of a Boolean variable is bool.
Example:
is_student=True #Boolean value
Type Checking:
The type function ( type() )can be used to verify the data type of a variable.
Example:
x = 10
kilometer =1.5
name = ”Eliza”
is_student=True
print(type(x)) # <class ‘int’>
print(type(kilometer)) #<class ‘float’>
print(type(name)) #<class ‘str’>
print(type(is_student)) #<class ‘bool’>
Keywords and Identifiers in Python
In Python, keywords and identifiers are fundamental concepts that play a crucial role in the structure and functionality of the code.
Keywords:
Keywords are reserved words in Python. They have special meaning and cannot be used as identifiers (names for variables, functions, classes, etc.). For example, if, else, for, while, True, False etc. All the keywords in Python are written in lowercase except True, false and None.
Identifiers:
Identifiers are user-defined names (name given by the programmer) given to a variable, function etc. Identifiers are names used to identify variables, functions etc. Identifiers can be combination of uppercase and lowercase letters, digits or an underscore ( _ ).
Python Output:
In Python, the primary way to produce output is by using the built-in print() function. This function displays information to the console or standard output device.
The simplest use of print() involves passing a value directly to it:
Example:
print(“Hello, Python!”)
print(123)
print(5 + 7)
Output:
Hello, Python!
123
12
Printing Variables:
We can also print the values of variables:
Example:
name = “Jashmina”
age = 20
print(name)
print(age)
Output:
Jashmina
20
Printing Multiple Items:
Multiple items can be printed in a single print() statement by separating them with commas. By default, they will be separated by a space in the output:
Example:
name = “Riya”
age = 18
print(“Name:”, name, “Age:”, age)
Output:
Name: Riya Age: 18
Formatted Output (f-strings):
For more complex and readable output formatting, especially when combining strings and variables, f-strings (formatted string literals) are commonly used:
Example:
name = “Nancy”
age = 20
print(f”Hello {name}”)
print(f”You are {age} years old.”)
Output:
Hello Nancy
You are 20 years old.
Python User Input
Python allows for user input. That means we are able to ask the user for input. Built-in function input() is used for user input. The following example asks for name, and when we enter a name, it gets printed on the screen:
Example:
name = input(“Enter your name:”)
print(f”Hello {name}”)
Output:
Enter your name: Liza
Hello Liza
It’s crucial to remember that the output of the “input()” function will always be a string, even if the user enters a numerical value. If we need to use the input as a number, we’ll need to convert it to the appropriate data type (e.g. int or float).
Example:
age=int(input(“Please enter your age: “))
print(f”You are {age} years old!”)
Output:
Please enter your age: 20
You are 20 years old!
Basic Syntax
Python uses a clean and straightforward syntax that emphasizes readability and simplicity, making it an ideal language for beginners and experienced programmers alike.
Here’s a simple example of a Python program that prints “Hello, World!“:
print(“Hello, World!”)
Python Syntax Rules:
- Python is case sensitive. Hence a variable with name roll is not same as Roll.
- In python, there is no command terminator, which means no semicolon; or anything. So, if we want to print something as output, all we have to do is: print (“Hello, World!”)
- In one line, only a single executable statement should be written and the line change act as command terminator in python.
- To write two separate executable statements in a single line, we should use a semicolon (;) to separate the commands. For example, x=20; print(x)
- In python, we can use single quotes
'', double quotes""to represent string literals.
‘\n’ and ‘\t’ in Python:
In Python, \n and \t are escape sequences used within strings to represent special characters. These escape sequences are fundamental for formatting string output, making it more readable and structured.
\n (Newline character):
This escape sequence represents a line break or newline. When encountered in a string, it causes the subsequent text to appear on a new line in the output. It is commonly used for formatting output and creating multi-line strings.
Example:
print(“Hello\nWorld”)
Output:
Hello
World
\t (Tab character):
This escape sequence represents a horizontal tab. When encountered in a string, it inserts a standard tab space, which typically aligns text horizontally.
Example:
print(“Name:\tHimani Nath”)
print(“Course:\tBA”)
print(“Age:\t18”)
Output:
Name: Himani Nath
Course: BA
Age: 18
Comments in Python:
In python, we can write comments using a hash sign (#) at the start. A comment is ignored by the python interpreter.
# this is a comment
print (“Hello, World!”)
Triple Quotes:
In Python, triple quotes (either single triple quotes ”’ or double triple quotes “””) are used to create multiline strings. They allow us to define strings that span multiple lines without needing to use escape characters like ‘\n’ for newlines.
While triple quotes are typically used for multi-line strings, they can also serve as a way to create multi-line comments because Python ignores string literals that aren’t assigned to a variable or used in an expression. Therefore, we can use triple quotes to create multi-line strings that effectively act as comments.
Here’s an example of using triple quotes to create a multiline string:
multi_str = ”’
Python is easy to learn.
Python is easy to write.
Python code is simple.
”’
print(multi_str)
Multi-Line Statements:
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example,
x=23
y=40
z=50
total=x + \
y+ \
z
print(total);
Multiple Assignment
Python allows us to assign a single value to several variables simultaneously. In following example value 5 is assigned to multiple variables.
a=b=c=5
print(a+b+c)
‘sep’ and ‘end’ parameters in Python print statement
In python, the sep parameter is used as a separator and the end parameter specifies the string that is printed at the end of the line.
The end parameter is used to append any string at the end of the output of the print statement in python while the sep parameter determines the separator between the values passed to the print() function.
Example:
print(‘5′,’6′,’2025′,sep=’-‘)
print(“apple”, “banana”, “cherry”, “orange”, sep=”, “)
print(‘Hello’,end=’ !!!‘)
Output:
5-6-2025
apple, banana, cherry, orange
Hello!!!
Code Indentation:
Indentation is used to define code blocks. This is the most important rule of python programming. In programming language like Java, C or C++, generally curly brackets { } are used to define a code block, but python doesn’t use brackets to indicate blocks of code. Python used indentation for this. It is recommended to use tab for indentation. In Python, wrong indentation can lead to syntax errors.
//Using indentation in conditional statement
x = 10
if x > 10:
print(“x is greater than 10”)
elif x < 10:
print(“x is less than 10”)
else:
print(“x is equal to 10”)
Operators in Python
In Python, operators are special symbols that perform different arithmetic and logical operations on values and variables. These operators are categorized into several types:
Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
Different arithmetic operators available in Python:
| Operator | Operation | Example |
| + | Addition | 2+5=7 |
| – | Subtraction | 7-5=2 |
| * | Multiplication | 2*5=10 |
| / | Division | 10/5=2.0 |
| % | Modulus (returns the remainder) | 7%2=1 |
| ** | Exponent (power) | 3**3=27 |
| // | Floor Division | 7//3=2 |
Example:
a=12
b=5
print(a+b) #Output: 17
print(a-b) #Output: 7
print(a*b) #Output: 60
print(a/b) #Output: 2.4
print(a%b) #Output: 2
print(a**b) #Output: 248832
print(a//b) #Output: 2
Assignment Operator:
The assignment operator is one of the most frequently used operators in Python. These operators are used to assign values to variables.
Different assignment operators available in Python:
| Operator | Name |
| = | Assignment Operator |
| += | Addition assignment |
| -= | Subtraction assignment |
| *= | Multiplication assignment |
| /= | Division assignment |
| %= | Modulus (Remainder) assignment |
| **= | Exponent assignment |
| //= | Floor division assignment |
Example:
a = 12
b = 5
a += b #a=a+b
print(a) #Output: 17
a -= b #a=a-b
print(a) #Output: 12
a *= b #a=a*b
print(a) #Output: 60
a /= b #a=a/b
print(a) #Output: 12.0
a %= b a=a%b
print(a) #Output: 2.0
a**=b a=a**b
print(a) #Output: 32.0
a //= b a=a//b
print(a) #Output: 6.0
Comparison Operators
Comparison operators are used to compare two values/variables. Based on the comparison, they return a Boolean value (True or False). They return True if the comparison is true, otherwise False. Comparison operators are commonly used in decision making and loops. They are also called as Relational Operators.
Comparison operators available in python:
| Operator | Name |
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
Example:
x = 5
y = 3
print(x == y) #False
print(x != y) #True
print(x > y) #True
print(x < y) #False
print(x >= y) #True
print(x <= y) #False
Logical Operators
The logical operators are used to perform logical operations and used to combine conditional statements. They are used in decision making.
Logical operators available in python:
| Operator | Description |
| and | Returns True if both conditions are true |
| or | Returns True if at least one condition is true |
| not | Reverses the result, returns False if the condition is True, and vice versa. |
Example:
x = 7
y = 9
print (x > 5 and y > 5) #True
print (x > 10 or y > 5) #True
print (not (x > 5 and y > 5)) #False
Identity Operators:
Identity operators are used to check if two variables refer to the same memory address.
Identity operators available in python:
| Operator | Description |
| Is | Returns True if both variables refer to the same memory address |
| is not | Returns False if both variables do not refer to the same memory address |
Example:
x = [“apple”, “orange”]
y = [“apple”, “orange”]
z = x
print(x is z) #True
print(x is y) #False
print(x is not z) #False
print(x is not y) #True
Membership Operators:
Membership operators are used to determine whether or not a certain value exists in a sequence ( like string, list, tuple etc.).
Membership operators available in python:
| Operator | Name |
| in | Returns True if the value exists in the given sequence. |
| not in | Returns True if the value does not exist in the sequence. |
Example:
fruits = [“apple”, “grapes”, “orange”]
print(“orange” in fruits) #True
print(“banana” not in fruits) #True
Decision Making Statements:
Decision making statements, also known as conditional statements, allow programs to execute different blocks of code based on whether a condition is true or false. In Python, decision making statements are used to control the flow of a program by executing certain blocks of code only when specific conditions are met.
These statements are fundamental for controlling the flow of a program. Decision making statements let our program choose different paths of execution depending on whether certain conditions are true or false.
Decision Making statements are based on conditional expressions that evaluate to either True or False to determine which code path to follow. Indentation is crucial in Python to define the blocks of code associated with each conditional statement. Conditions often use comparison (==, !=, >, <, >=, <=) and logical operators (and, or, not).
Types of Decision-Making Statements in Python:
If Statement:
In Python, the if statement is used for conditional execution of code. It allows us to execute a block of code only if the specified condition is True.
Here’s the basic syntax:

Example:
age = 20
if age >= 18:
print(“You are eligible to vote.”)
Output:
You are eligible to vote.
OR
age=int(input(“Enter the age: “))
if age >= 18:
print(“You are eligible to vote.”)
Output:
Enter the age: 34
You are eligible to vote.
if…. else Statement:
This statement provides an alternative block of code to execute if the initial if condition is false. Executes one block of code if the condition is True and another block if the condition is False.
Syntax:

Example-1:
age = 10
if age >= 18:
print(“You are eligible to vote.”)
else:
print(“You are not eligible to vote.”)
Output:
You are not eligible to vote.
OR
age=int(input(“Enter the age: “))
if age >= 18:
print(“You are eligible to vote.”)
else:
print(“You are not eligible to vote.”)
Output-1:
Enter the age: 35
You are eligible to vote.
Output-2:
Enter the age: 15
You are not eligible to vote.
Example-2
temperature=25
if temperature>30:
print(“It’s too hot outside”)
else:
print(“it’s not too hot”)
Output:
it’s not too hot
if…elif…else Statement (if…elif ladder):
We can also extend the if statement with elif and else clauses to handle multiple conditions. This allows for checking multiple conditions sequentially. If the first if condition is False, it checks the elif conditions in order. If none of the if or elif conditions are True, the else block is executed.
Syntax:

Example-1:
x=20
if x > 10:
print(“x is greater than 10”)
elif x < 10:
print(“x is less than 10”)
else:
print(“x is equal to 10”)
Output:
x is greater than 10
Example-2:
percentage=85
if percentage>=80:
print(“Grade: A”)
elif percentage>=70:
print(“Grade: B”)
elif percentage>=60:
print(“Grade: C”)
elif percentage>=50:
print(“Grade: D”)
else:
print(“Fail”)
Output:
Grade: A
Nested if Statements:
A nested if statement in Python refers to an if statement that is placed inside another if statement (or elif or else block). This allows for evaluating multiple conditions in a hierarchical manner, where an inner condition is only checked if the outer condition evaluates to True.
Syntax:

Example-1:
num=int(input(“Enter a number: “))
if num> 0:
if num % 3==0:
print(“Positive and divisible by 3”)
else:
print(“Positive, not divisible by 3”)
else:
print(“The number is not positive”)
Output-1:
Enter a number: 10
Positive but not divisible by 3
Output-2:
Enter a number: 12
Positive and divisible by 3
Output-3:
Enter a number: -23
Negative number
Example-2:
age=30
has_license=True
if age>=18:
print(“You are old enough to drive”)
if has_license:
print(“You can legally drive”)
else:
print(“You need to get a license”)
else:
print(“You aren’t old enough to drive”)
Output:
You are old enough to drive
You can legally drive
Python Match Case statement
The match-case statement, introduced in Python 3.10, provides a structured way to handle different conditions based on the value of an expression.
Instead of writing many if…else statements, we can use the match statement. The match-case statement is used to perform different actions based on different conditions. The statements select one of many code blocks to be executed.
Syntax:
match expression:
case x:
code block
case y:
code block
case z:
code block
Example:
day = int(input(“Enter a number of the day of the week: “))
match day:
case 1:
print(“Monday”)
case 2:
print(“Tuesday”)
case 3:
print(“Wednesday”)
case 4:
print(“Thursday”)
case 5:
print(“Friday”)
case 6:
print(“Saturday”)
case 7:
print(“Sunday”)
case _:
print(“Invalid input. Please enter a number between 1-7.”)
Output-1:
Enter a number for the day of the week: 6
Saturday
Output-2:
Enter a number for the day of the week: 9
Invalid input. Please enter a number between 1-7.
Looping Statements (Python Loops):
Loops in Python are control flow statements used to repeatedly execute a block of code. There may be a situation when we need to execute a block of code several number of times. A loop statement allows us to execute a statement or group of statements multiple times.
Python offers two primary types of loop: for loop and while loop.
For Loop:
The for loop is used for iterating over a sequence (like a list, tuple, string, or range) or other iterable objects. It executes a block of code once for each item in the sequence. The basic syntax involves a loop variable that takes on the value of each item in the sequence during successive iterations. Include a colon after for loop statement, and indent code included in the body of the loop.
Syntax:
for iterating_var in sequence:
statement(s)
Here,
- for : for keyword indicating the start of a for loop.
- iterating_var: It is a variable that takes the value of each item in the sequence during each iteration.
- in : in Keyword used to specify the sequence to iterate over.
- sequence : The iterable object(e.g. string, list, range() )that the loop will iterate through.
- : marks the end of the loop header.
- statement (s) : The block of code to be executed repeatedly for each item in the sequence. The block must be indented.
Example-1:
#iterate through a string
name=’ELIZA’
for x in name:
print(x)
Output:
E
L
I
Z
A
Example-2:
# Iterating over a list
animals =[“cow”, “goat”, “dog”, “cat”]
for x in animals:
print (x,end=’ ‘)
Output:
cow goat dog cat
The range() Function:
The range function used to generate sequence of numbers. range (10) will generate numbers from 0 to 9 (10 numbers). It is also possible to define the start, stop and step size as range (start, stop, step size). Step size defaults to 1 if not provided.
Example-1:
for i in range(10):
print(i, end=’ ‘)
Output:
0 1 2 3 4 5 6 7 8 9
Example-2:
for i in range(1,11):
print(i, end=’ ‘)
Output:
1 2 3 4 5 6 7 8 9 10
Example-3:
for i in range(2,21,2):
print(i, end=’ ‘)
Output:
2 4 6 8 10 12 14 16 18 20
While Loop in Python
The while loop repeatedly executes a block of code as long as a given condition remains True. The loop continues to execute until the condition evaluates to False. It is crucial to ensure that the condition eventually becomes False to prevent infinite loops. It is suitable when the number of iterations is not known beforehand.
Syntax:
while condition:
statement (s)
Here,
- while: while keyword indicating the start of a while loop.
- condition: An expression that evaluates to True or False. The loop continues to execute as long as this condition is True.
- : marks the end of the loop header.
- statement (s) : The block of code to be executed repeatedly. This block must be indented.
Example-1:
count = 0
while count<10:
print (count, end=’ ‘)
count+=1
Output:
0 1 2 3 4 5 6 7 8 9
Example-2
n=2
while n<=20:
print(n, end=’ ‘)
n+=2
Output:
2 4 6 8 10 12 14 16 18 20
Example-3:
n=10
while n>=1:
print(n, end=’ ‘)
n-=1
Output:
10 9 8 7 6 5 4 3 2 1
Loop Control Statements:
Break Statement:
The break statement is used to exit a loop early when a certain condition is met. This statement immediately terminates the loop entirely, even if the loop condition is still true or there are more items to iterate over.
Example-For Loop:
for i in range(1,11):
if i == 7:
break
print(i,end=’ ‘)
Output:
1 2 3 4 5 6
Example-While Loop:
n=1
while n<=10:
if n==6:
break
print(n, end=’ ‘)
n=n+1
Output:
1 2 3 4 5
Continue Statement:
The continue statement skips the current iteration and moves to the next iteration of the loop. When continue is encountered, the remaining code within the current iteration is skipped, and the loop’s condition is reevaluated to determine if the next iteration if the next iteration should begin.
Example of For Loop:
Example-1:
for i in range(7):
if i == 4:
continue
print(i,end=’ ‘)
Output:
0 1 2 3 5 6
Example-2:
for i in range(1,21):
if i>10 and i<15:
continue
print(i,end=’ ‘)
Output:
1 2 3 4 5 6 7 8 9 10 15 16 17 18 19 20
Example-3
for i in range(10):
if i % 2 == 0:
continue
print(i, end=’ ‘)
Output:
1 3 5 7 9
Example of While Loop:
n=0
while n<10:
n+=1
if n==6:
continue
print(n, end=’ ‘)
Output:
1 2 3 4 5 7 8 9 10
Pass Statement:
The pass statement in Python is a null operation; It does nothing when executed. It serves as a placeholder where a statement is syntactically required but no action is desired or needed at that moment. The basic usage of the “pass” statement is to create empty blocks of code that will be filled later.
Example-1:
#In a conditional statement (if/else):
x = 10
if x > 5:
pass
else:
print(“x is 5 or less”)
print(“Conditional check complete.”)
Output:
Conditional check complete.
Example-2:
#pass statement in a Loop
for i in range(5):
if i == 2:
pass
else:
print(f”Processing item: {i}”)
print(“Loop finished.”)
Output:
Processing item: 0
Processing item: 1
Processing item: 3
Processing item: 4
Loop finished.
Example-3:
for letter in ‘Python’:
if letter == ‘h’:
pass
print (‘This is pass block’)
else:
print (‘Current Letter :’, letter)
print (“Good bye!”)
Output:
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : o
Current Letter : n
Good bye!
else with Loops:
Else is a conditional statement that is used in combination with the if statement. In Python, we can also use it directly after the body of loop. Both for and while loops can have an optional else block. This block is executed if the loop completes normally (i.e., not terminated by a break statement). Once all iterations are complete, the else block will be executed as part of the loop.
Syntax of For loop:
for iterating_var in sequence:
statement(s)
else:
statements
Syntax of while Loop:
while condition:
statement (s)
else:
statements (s)
Example-1
string=’Good Morning’
for x in string:
print(x,end=’ ‘)
else:
print(“\nhave a nice day”)
Output:
G o o d M o r n i n g
have a nice day
Example-2
for i in range(5):
print(i,end=’ ‘)
else:
print(“\nLoop finished normally.”)
Output:
0 1 2 3 4
Loop finished normally.
Example-3:
count = 0
while count < 10:
print(count,end=’ ‘)
count += 1
else:
print(“\nWhile loop finished normally.”)
Output:
0 1 2 3 4 5 6 7 8 9
While loop finished normally.
Nested Loops:
Loops can be nested, meaning one loop can be placed inside another. A nested loop is simply a loop within another loop. The main loop is considered as outer loop and loop(s) inside the outer loop are known as inner loops. Every iteration of the outer loop causes the inner loop to run all its iterations. The outer loop doesn’t run before the inner loop has terminated. The inner loop completes all its iterations for each single iteration of the outer loop.
Syntax of Nested For Loop:
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# Inner loop code block
# Outer loop code block
In this structure, outer_sequence is the collection of items that the outer loop will iterate over, and inner_sequence is the collection that the inner loop will go through each time the outer loop iterates.
Example-1:
for i in range(2):
for j in range(3):
print(f”Outer: {i}, Inner: {j}”)
Output:
Outer: 0, Inner: 0
Outer: 0, Inner: 1
Outer: 0, Inner: 2
Outer: 1, Inner: 0
Outer: 1, Inner: 1
Outer: 1, Inner: 2
Example-2:
for i in range(1, 5):
for j in range(i):
print(i, end=’ ‘)
print()
Output:
1
2 2
3 3 3
4 4 4 4
Example-3:
list=[“red”, “white”, “yellow”]
flowers = [“rose”, “lily”, “tulip”]
for x in list:
for y in flowers:
print(x, y)
Output:
red rose
red lily
red tulip
white rose
white lily
white tulip
yellow rose
yellow lily
yellow tulip
Syntax of Nested While Loop:
while outer_condition:
while inner_condition:
# inner loop code
# outer loop code
Example:
i=1
while i<10:
j=i
while j<10:
print( j, end=’ ‘)
j+=1
print(” “)
i+=1
Output:
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
4 5 6 7 8 9
5 6 7 8 9
6 7 8 9
7 8 9
8 9
9
Strings in Python:
Strings in python are set of characters. They are surrounded by single quotes (‘ ‘), double quotes (” “) or triple quotes (”’ ”’). The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. An empty string is a string that has 0 characters (i.e., it is just a pair of quotation marks). Strings are immutable, meaning their value cannot be changed after they are created. We cannot change a character at a specific index within an existing string.
Example:
name = “India”
print(name)
message = “I love India.”
print(message)
Output:
India
I love India.
TRAVERSING A STRING
Traversing a string means accessing each of its characters one by one. We can access the characters in a string in three ways.
Indexing:
Indexing can be used to extract single characters from a string. Strings are ordered collections of characters, meaning each character has a specific position or index. Individual characters of a string are accessible through the unique index of each character. Using the indexes, we can traverse a string character by character. The index starts from 0 for the first character of the string. The second character has an index of 1, the third has an index of 2, and so on. The index of the last character is length_of_string – 1.
Example:
s = ‘hello’
print(s[0])
print(s[4])
print(s[6])
Output:
h
o
IndexError: string index out of range
Negative Indexing:
Python allows negative indexing for its strings. Negative indexing can be used to access characters from the end of the string. This provides a convenient way to access elements from the end of the string without knowing its exact length. Negative indexing starts from -1 for the last character of the string. The second to last character has an index of -2, the third to last has an index of -3, and so on.
Example:
s = ‘hello’
print(s[-2])
print(s[-4])
print(s[-8])
Output:
l
e
IndexError: string index out of range
Slicing (String Slices):
Access a range of characters in a string by using the slicing operator colon ( : ). As an English term, we know the meaning of word “slice”, which means – ‘a part of’. In the same way, in Python the term “string slice’ refers to a part of the strings, where strings are sliced using a range of indices.
Note: In a string slice, the character at last index (the one following colon (:) ) is not included in the result. The string slice refers to a part of the string s[start:end] that isthe elements beginning at start and extending up to but not including end.
Note: Missing index before colon is taken as 0 (zero). Missing index after colon is taken as the length of the string.
Example:
s = ‘welcome’
print(s[0:7])
print(s[0:3])
print(s[3:7])
print(s[-6:-2])
print(s[:6])
print(s[:-3])
print(s[5:])
print(s[-5:])
Output:
welcome
wel
come
elco
welcome
welc
me
lcome
STRING OPERATIONS
Many operations can be performed with strings, which makes it one of the most used data types in Python. Python provides a rich set of operations for manipulating strings, including operators and built-in methods.
String Operators:
Equality Operator ( ==) :
We use the == operator to compare two strings. If two strings are equal, the operator returns True. Otherwise, it returns False.
Example:
str1 = “Hello, world!”
str2 = “I love India.”
str3 = “Hello, world!”
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)
Output:
False
True
Concatenation (+) Operator:
In Python, we can join (concatenate) two or more strings using the Concatenation Operator ( + ). The + operator creates a new string by joining the two operand strings.
Example-1:
print(‘wel’ + ‘come’)
print(‘5’ + ‘5’)
print(‘123’ + ‘abc’)
Output:
welcome
55
123abc
Example-2:
greet = “Hello, “
name = “Prince”
result = greet + name
print(result)
Output:
Hello, Prince
+ operator can work with numbers and strings separately for addition and concatenation respectively, but in the same expression, we cannot combine numbers and strings as operands with a + operator.
Example:
print(2+3)
print(‘5’ + ‘5’)
print(‘2’ + 3)
Output:
5
55
TypeError: can only concatenate str (not “int”) to str
Repetition (*) Operator:
In Python, string repetition is a common string operation to create a new string by repeating an existing string a specified number of times. This is achieved using the repetition operator ( * ). It is used to repeat a sequence (like a string or a list) a specified number of times.
Example-1:
print(‘Eliza ’ * 4)
print(5 * ‘5’)
Output:
Eliza Eliza Eliza Eliza
55555
Example-2:
greet = “Hello”
print(greet*3)
Output:
HelloHelloHello
Exercise:
str=”Assam is very beautiful place ”
print(str)
print(str[0])
print(str[2:5])
print(str[2:])
print(str*2)
print(str + “ in India”)
Output:
Assam is very beautiful place
A
sam
sam is very beautiful place
Assam is very beautiful place Assam is very beautiful place
Assam is very beautiful place in India
STRING FUNCTIONS AND METHODS:
Python offers many built-in functions and methods for string manipulations.
1. capitalize()
The capitalize() method returns a copy of the string with its first character capitalized and the rest in lowercase. It does not modify the original string in place. If the first character of the string is already capital or is a non-alphabetic character, it remains unchanged.
Example-1:
print(“eliza”.capitalize())
OR
string=”eliza”
print(string.capitalize())
OR
string=”eliza”
result=string.capitalize()
print(result)
Output:
Eliza
Example-2:
string = “PYTHON IS EASY”
result= string.capitalize()
print(result)
Output:
Python is easy
Example-3:
string=”123 example”
result=string.capitalize()
print(result)
Output:
123 example
2. center(width, fillchar):
The center() method is used to center-align a string within a specified width. By default, it uses spaces to fill the extra space but can also be used to any character we want.
Example:
name= “eliza”
x=name.center(20)
print(x)
Output:
eliza
OR
name= “eliza”
x=name.center(15, ‘*’)
print(x)
Output:
*****eliza*****
3. upper():
The upper() method returns a copy of the string converted to uppercase. It is used as per the syntax:
<string>.upper()
Example-1:
s = “hello students”
print(s.upper())
Output:
HELLO STUDENTS
Example-2:
print(“hello”.upper())
print(“HELLO”.upper())
print(“Welcome”.upper())
print(“pin: 786125”.upper())
Output:
HELLO
HELLO
WELCOME
PIN: 786125
4. lower():
The lower() method returns a copy of the string converted to lowercase. It is used as per the syntax:
<string>.lower()
Example-1:
s = “HELLO STUDENTS”
print(s.lower())
Output:
hello students
Example-2:
print(“hello”.lower())
print(“HELLO”.lower())
print(“Welcome”.lower())
print(“Roll No:12”.lower())
Output:
hello
hello
welcome
roll no:12
5. find():
The find() method finds the first occurrence of the specified value. Returns -1 if the specified value is not found.
Example:
s = “Hello, welcome to Assam.”
x = s.find(“welcome”)
print(x)
y=s.find(“hello”)
print(y)
Output:
7
-1
6. index():
The index() method returns the lowest index where the specified substring is found. It works like find(), but find() returns -1 if the substring is not found., but index() raises anexception (error) , if substring is not found.
Example-1
print(“Hello friends”.index(‘f’))
print(“how are you?”.index(‘?’))
Output:
6
11
Example-2
s=”Hello students, welcome to class”
x=s.index(“students”)
print(f”Index of ‘students’ is {x}”)
Output:
Index of ‘students’ is 6
Example-3:
s=”this is beautiful”
print(s.index(‘is’,4))
Output:
5
Example-4
s=”Python is easy, it is easy to learn”
x=s.index(“is”,5,15)
print(f”Index of ‘is’ is {x}”)
Output:
Index of ‘is’ is 7
7. count():
The count() method counts how many times the specified value appears in the string. It can also accept optional start and end parameters to specify a search range within the string.
Example-1:
print(‘welcome’.count(‘m’))
print(‘this is beautiful’.count(‘is’))
Output:
1
2
Example-2:
s = “I love Assam, Assam is my birthplace”
x = s.count(“Assam”)
print(x)
OR
s = “I love Assam, Assam is my birthplace”
print(s.count(“Assam”))
Output:
2
Example-3:
s = “I love Assam, Assam is my birthplace”
print(s.count(“m”,0,15))
Output:
1
Example-4:
s = “I love Assam, Assam is my birthplace”
print(s.count(“am”,10))
Output:
2
8. len()
The len() function returns the number of characters in the string, including spaces.
Example-1:
print(len(“eliza”))
OR
name= ”eliza”
print(len(name))
Output:
5
Example-2:
s = ”Hello Friend”
length_string = len(s)
print(f”Length: {length_string}”)
Output:
Length: 12
9. replace()
It returns a copy of the string with all occurrences of substring old replaced by new string. It is used as per the syntax:
<string>.replace(old,new)
Example:
print(“You are beautiful”.replace(‘You’,’U’)
print(“Hi Prince!”.replace(‘Hi’,’Hello’)
Output:
U are beautiful
Hello Prince!
10. isalpha()
The isalpha() method returns True if all the characters in the string are alphabet letters (a-z).
Example-1:
print(“hi”.isalpha())
print(“hello!!”.isalpha())
print(“roll123”.isalpha())
print(“555”.isalpha())
print(“hello students”.isalpha())
Output:
True
False
False
False
False
Example-2:
s = “Assam”
x = s.isalpha()
print(x)
Output:
True
Example-3:
a=”roll101”
b=a.isalpha()
print(b)
Output:
False
11. isalnum():
The isalnum() method returns True if the characters in the string are alphanumeric (alphabets or numbers).
Example-1:
print(“roll45”.isalnum())
print(“roll: 45”.isalnum())
print(“hello”.isalnum())
print(“12345”.isalnum())
print(“hello!!!”.isalnum())
print(“hello students”.isalnum())
Output:
True
False
True
True
False
False
Example-2:
s = “Assam123”
x = s.isalnum()
print(x)
OR
s = “pin786125”
print(s.isalnum())
Output:
True
Example-3:
a= “hello!!!”
b= a.isalnum()
print(b)
OR
s = “Hi…”
print(s.isalnum())
Output:
False
12. isdigit()
It returns True if all the characters in the string are digits.
Example:
print(“555”.isdigit())
print(“5-5-5”.isdigit())
print(“roll123”.isdigit())
print(“hi”.isdigit())
print(“hello!!”.isdigit())
Output:
True
False
False
False
False
False
13. islower()
It returns True if all characters in the string are lowercase. It is used as per the syntax:
<string>.islower()
Example:
s=’hello’
s1=’HI’
s2=’Welcome’
print(s.islower())
print(s1.islower())
print(s2.islower())
Output:
True
False
False
14. isupper()
It returns True if all characters in the string are uppercase.
Example:
s=’hello’
s1=’HI’
s2=’Welcome’
print(s.isupper())
print(s1.isupper())
print(s2.isupper())
Output:
False
True
False
15. isspace()
It returns True if there are only whitespace characters in the string.
Example:
s=” “
s1=””
print(s.isspace())
print(s1.isspace())
Output:
True
False
PYTHON – LISTS:
The list is a most versatile datatype available in Python used to store an ordered collection of items. Lists are sequence of values of any type. Values in the list are called elements or items. Important thing about a list is that, items in a list need not be of the same type. Lists are mutable and indexed or ordered. A list contains items separated by commas. The list is enclosed in square brackets [ ]. For example, [2, 6, 8, 3, 1] or ["Python", "Java", "C++"] are both lists.
The values stored in list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end –1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
Example:
list1 = [“hello”, “bye”, 101, 3.142, True]
Important points of List:
- A list is an ordered set of items.
- The first item of any non-empty list is always list1[0].
- The last item of five-item list is 1[4], because lists are always zero based.
- A negative index accesses items from the end of the list counting backwards. The last item of any non-empty list is always list1[-1].
Exercise-1:
list1 = [‘Assam’, ‘Delhi’, ‘Bihar’, 1205, 5042, 50.452]
list2 = [‘Bristee’, ‘Yashmin’]
print(list1)
print(list1[0])
print(list1[1:3])
print(list1[2:])
print(list2 *2)
print(list1 + list2)
Output:
[‘Assam’, ‘Delhi’, ‘Bihar’, 1205, 5042, 50.452]
Assam
[‘Delhi’, ‘Bihar’]
[‘Bihar’, 1205, 5042, 50.452]
[‘Bristee’, ‘Yashmin’, ‘Bristee’, ‘Yashmin’]
[‘Assam’, ‘Delhi’, ‘Bihar’, 1205, 5042, 50.452, ‘Bristee’, ‘Yashmin’]
Exercise-2:
list1 = [‘physics’, ‘chemistry’, ‘maths’, 90, 95, 98]
list2 = [1, 2, 3, 4, 5, 6, 7]
print(list1)
print(f”list1[0]: {list1[0]}”)
print(f”list2[1:5]: {list2[1:5]}”)
print(f”list2[0:3]: {list2[0:3]}”)
print(f”list2[:3]: {list2[:3]}”)
print(f”list1[-2]: {list1[-2]}”)
print(f“list2[0:-2]: {list1[0:-2]}”)
print(f“list1[-3:-1]: {list1[-3:-1]}”)
print(f”list1[-3:]: {list1[-3:]}”)
Output:
[‘physics’, ‘chemistry’, ‘maths’, 90, 95, 98]
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
list2[0:3]: [1, 2, 3]
list2[:3]: [1, 2, 3]
list1[-2]: 95
list2[0:-2]: [‘physics’, ‘chemistry’, ‘maths’, 90]
list1[-3:-1]: [90, 95]
list1[-3:]: [90, 95, 98]
Exercise-3:
print([1,2,3]+[4,5,6])
print([‘Bye!’]*4)
print(3 in [1,2,3])
for x in [1,2,3]:
print(x,end=’ ‘)
Output:
[1, 2, 3, 4, 5, 6]
[‘Bye!’, ‘Bye!’, ‘Bye!’, ‘Bye!’]
True
1 2 3
Adding Elements (Items) to a List:
In Python, elements can be added to a list using several methods, depending on whether a single element or multiple elements are being added, where the elements should be positioned.
append():
This method adds a single element to the end of the list.
Example-1
my_list = [1, 2, 3]
my_list.append(4)
print (my_list)
Output:
[1, 2, 3, 4]
Example-2:
L= [‘C’, ‘C++’, ‘Java’, ‘Python’]
L.append(‘HTML’)
print(L)
Output:
[‘C’, ‘C++’, ‘Java’, ‘Python’, ‘HTML’]
insert():
This method adds a single element at a specified index within the list. Existing elements from that index onward are shifted to the right.
Example-1
my_list = [1, 2, 3]
my_list.insert(1, 5)
print (my_list)
Output:
[1, 5, 2, 3]
extend():
This method adds all elements from an iterable (like another list, tuple, or string) to the end of the current list.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
Output:
[1, 2, 3, 4, 5,6]
Concatenation with + operator:
This method creates a new list by combining two or more existing lists. This does not modify the original lists in place.
Example-1:
L=[‘C’,’C++’,’HTML’]
L1=L+[‘Java’,’Python’]
print(L1)
Output:
[‘C’, ‘C++’, ‘HTML’,’Java’, ‘Python’]
Example-2:
list1 = [1, 2,3]
list2 = [4,5,6]
new_list = list1 + list2
print(new_list)
Output:
[1, 2, 3, 4, 5, 6]
Updating a List:
Updating elements in a Python list can be achieved in several ways, depending on whether a single element or a range of elements need to be updated.
Updating Individual Elements:
The most common way to update an element is by directly assign a new value to its specific index.
Example-1:
my_list = [10, 20, 30, 40]
my_list[1] = 25
print(my_list)
Output:
[10, 25, 30, 40]
Example-2:
List=[‘Red’, ‘Green’, ‘Blue’, ‘White’]
List[0]=’Black’
print(List)
Output:
[‘Black’, ‘Green’, ‘Blue’, ‘White’]
Updating Multiple Elements:
Multiple elements within a specific range can be updated by assigning a new list to a slice of the original list. The number of elements in the new list does not have to match the size of the slice.
Example-1
my_list = [10, 20, 30, 40, 50]
my_list[1:4] = [25, 35, 45]
print(my_list)
Output:
[10, 25, 35, 45, 50]
Example-2
List=[‘Red’, ‘Green’, ‘Blue’, ‘White’]
List[0:2]=’Purple’, ‘Orange’
print(List)
Output:
[‘Purple’, ‘Orange’, ‘Blue’, ‘White’]
Removing (Deleting) Elements from List:
In Python, elements can be removed from a list using several methods.
remove():
This method removes the first occurrence of the specified element from the list. Raises a ValueError if the value is not found.
Example-1:
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list)
Output:
[1, 3, 2]
Example-2:
List=[‘C’, ‘C++’, ‘Java’, ‘Python’, ‘HTML’]
List.remove(‘Java’)
print(List)
Output:
[‘C’, ‘C++’, ‘Python’, ‘HTML’]
pop():
This method removes the element at the specified index and returns its value. If no index is specified, it removes and returns the last element. Raises an IndexError if the index is out of range.
Example:
my_list = [10, 20, 30]
new_list= my_list.pop(1)
print(my_list)
print(new_list)
Output:
[10, 30]
20
del statement:
The del statement deletes an element at a specific index, a slice, or even the entire list.
Example-1
my_list = [10, 20, 30, 40]
del my_list[1]
print(my_list)
Output:
[10, 30, 40]
Example-2
List=[‘C’, ‘C++’, ‘Java’, ‘Python’, ‘HTML’]
del List[0]
print(List)
Output:
[‘C++’, ‘Java’, ‘Python’, ‘HTML’]
Example:3
my_list = [10, 20, 30, 40, 50]
del my_list[1:4]
print(my_list)
Output:
[10, 50]
clear():
Removes all elements from the list, making it empty.
Example:
my_list = [1, 2, 3]
my_list.clear()
print(my_list)
Output:
[]
TUPLE in Python
A tuple in Python is an ordered collection of items. A tuple cannot be changed in any way once it is created. Once a tuple is created, its elements cannot be changed, added, or removed. Tuples are pretty much like Lists, except that they are immutable, hence once we assign it some value, we cannot change it later. Tuples can store items of different data types within the same tuple (e.g., numbers, string, Booleans). Tuples are commonly used in Python for representing fixed collections of related data.
The main difference between tuples and lists is that the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating Tuples:
Creating a tuple is as simple as putting different comma-separated values. We can put these comma-separated values between parentheses also.
Example:
#A tuple with mixed data type
tup1 = (‘physics’, 98, True, 3.14)
tup2 = (1, 2, 3, 4, 5)
tup3 = “a”, “b”, “c”, “d”
print(tup1)
print(tup2)
print(tup3)
Output:
(‘physics’, 98, True, 3.14)
(1, 2, 3, 4, 5)
(‘a’, ‘b’, ‘c’, ‘d’)
Note: The empty tuple is written as two parentheses containing nothing-
Example:
tup1= ()
print(tup1)
Output:
()
To write a tuple containing a single value we have to include a comma, even though there is only one value.
Example:
tup1= (50,)
print(tup1)
Output:
(50,)
Accessing Tuple items:
Like string indices, tuple indices start at 0. Negative indices count from the end of the tuple, just like a list. Slicing works too, just like a list. When we slice a list, we get a new list; when we slice a tuple, we get a new tuple.
Example:
t=(“apple”, “mango”, “orange”, “grapes”)
print(t[0])
print(t[-2])
print(t[2:])
Output:
apple
orange
(‘orange’, ‘grapes’)
Basic tuple Operation:
While tuples are immutable, several operations can be performed on them.
Concatenation:
Tuples can be combined using the + operator.
Example:
tup1=(1, 2, 3)
tup2=(4, 5, 6)
print(tup1+tup2)
Output:
(1, 2, 3, 4, 5, 6)
Repetition:
Tuples can be repeated using the * operator.
Example:
color=(‘Red’, ‘Green’)
print(color*2)
Output:
(‘Red’, ‘Green’, ‘Red’, ‘Green’)
Slicing:
Subsets of a tuple can be extracted using slicing.
Example:
color=(‘Red’, ‘Green’, ‘Blue’)
print(color[1:3])
Output:
(‘Green’, ‘Blue’)
len()
len() function returns the number of items in a tuple.
Example:
color=(‘Red’, ‘Green’, ‘Blue’)
print(len(color))
Output:
3
max()
max() function returns item from the tuple with max value.
Example:
tup1=(1, 2, 3, 4)
print(max(tup1))
Output:
4
min()
min() function returns item from the tuple with min value.
Example:
tup1=(1, 2, 3, 4)
print(min(tup1))
Output:
1
count()
count() method returns the number of times a specified value appears in the tuple.
Example:
color=(‘Red’, ‘Green’, ‘Red’)
print(color.count(‘Red’))
Output:
2
index()
index() method returns the index of the first occurrence of a specified value.
Example:
color=(‘Red’, ‘Green’, ‘Blue’)
print(color.index(‘Green’))
Output:
1
Exercise:
tuple1=(“Assam”, 35, 3.73, “Arunachal”,28, 18.91)
tuple2=(“Manipur”, “Mizoram”)
print(tuple1)
print(tuple1[0])
print(tuple1[1:3])
print(tuple1[2:])
print(tuple2*2)
print(tuple1 + tuple2)
Output:
(‘Assam’, 35, 3.73, ‘Arunachal’, 28, 18.91)
Assam
(35, 3.73)
(3.73, ‘Arunachal’, 28, 18.91)
(‘Manipur’, ‘Mizoram’, ‘Manipur’, ‘Mizoram’)
(‘Manipur’, ‘Mizoram’, ‘Assam’, 35, 3.73, ‘Arunachal’, 28, 18.91)
DICTIONARY
A dictionary in Python is a built-in, mutable data structure that stores data in key-value pairs. It is an unordered collection of items, meaning the order in which items are added is not necessarily the order in which they are stored or retrieved (though from Python 3.7 onwards, dictionaries are officially ordered). A dictionary is an unordered set of key value pairs. When a add a key to a dictionary, we must also add a value for that key. Dictionaries are enclosed by curly brackets { } and values can be assigned and accessed using square brakets [ ]
Creating a dictionary
This is the most common and straightforward way to create a dictionary with initial key-value pairs. Each key is separated from its value by a colon ( : ), the items are separated by commas, and the whole thing is enclosed in curly brackets. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type.
Example:
my_dict={‘Name’ : ’Junal’, ‘Course’ : ‘BSC’, ‘Address’ : ‘Tinsukia’}
print(my_dict)
Output:
{‘Name’ : ’Junali’, ‘Course’ : ‘BSC’, ‘Address’ : ‘Tinsukia’}
Access Dictionary Keys
In a dictionary, keys are the unique identifiers associated with each value. We can access dictionary keys in Python using the keys() method. By iterating through keys using a for loop, we can access keys in the dictionary efficiently.
Example-1:
my_dict= {‘name’: ‘Raja’, ‘age’: 30}
print(my_dict.keys())
Output:
dict_keys([‘name’, ‘age’])
Example-2:
my_dict= {‘name’: ‘Raja’, ‘age’: 30}
print(‘–Keys–‘)
for x in my_dict.keys():
print(x)
Output:
–Keys–
name
age
Access Dictionary Values
In a dictionary, values are the data associated with each unique key. They represent the actual information stored in the dictionary and can be of any data type. Each key in a dictionary map to a specific value, forming a key-value pair.
Using Square Brackets []:
This method allows us to access a specific value by providing its corresponding key within square brackets. This is the most direct way to access a dictionary value. We provide the key within square brackets [] after the dictionary name. If the key does not exist in the dictionary, it will raise a KeyError.
Example-1:
my_dict = {‘Name’: ’Junali’, ‘Course’: ‘BSC’, ‘Address’: ‘Tinsukia’}
print(my_dict[‘Name’])
print(my_dict[‘Address’])
Output:
Junali
Tinsukia
Example-2:
my_dict = {‘Name’: ‘Junali’, ‘Course’: ‘BSC’, ‘Address’: ‘Tinsukia’}
print(my_dict[‘Roll’])
Output:
print(my_dict[‘Roll’])
~~~~~~~^^^^^^^^
KeyError: ‘Roll’
Using the get() Method:
The get() method is used to retrieve the value associated with a specified key. If the key is not found in the dictionary, it returns a default value (usually None) instead of raising a KeyError.
Example-1:
my_dict = {‘Name’: ‘Junali’, ‘Course’: ‘BSC’, ‘Address’: ‘Tinsukia’}
address=my_dict.get(‘Address’)
print(address)
Output:
Tinsukia
Example-2:
my_dict = {‘Name’: ‘Junali’, ‘Course’: ‘BSC’, ‘Address’: ‘Tinsukia’}
roll=my_dict.get(‘Roll’)
print(roll)
Output:
None
Using values() Method
In Python, we can access the values in a dictionary using the values() method. This method returns all values in the dictionary, allowing us to iterate through them using a for loop.
Example-1:
my_dict= {‘name’: ‘Raja’, ‘age’: 30}
print(my_dict.values())
Output:
dict_values([‘Raja’, 30])
Example-2:
my_dict= {‘name’: ‘Raja’, ‘age’: 30}
print(‘–Values–‘)
for x in my_dict.values():
print(x)
Output:
–Values–
Raja
30
Access key-value pair (items):
The items() method allows us to iterate over both keys and values simultaneously.
Example:
my_dict= {‘name’: ‘Raja’, ‘age’: 30}
print(‘–Items–‘)
for key,value in my_dict.items():
print(key,’:’,value)
Output:
–Items–
name: Raja
age: 30
Modifying a Dictionary:
Dictionaries do not have any predefined size limit. We can add new key-value pairs to a dictionary at any time, or we can modify the value of an existing key. Duplicate keys are not allowed in dictionary. Assigning a value to an existing key will update the old value.
Example:
favorite={‘Fruit’ : ‘Mango’, ‘Flower’ : ‘Rose’, ‘Bird’ :’Parrot’}
print(favorite)
# Adding a new key-value pair
favorite[‘Animal’]= ‘Dog’
print(favorite)
#Updating the value to an existing key
favorite[‘Fruit’]= ‘Orange’
print(favorite)
Output:
{‘Fruit’: ‘Mango’, ‘Flower’: ‘Rose’, ‘Bird’: ‘Parrot’}
{‘Fruit’: ‘Mango’, ‘Flower’: ‘Rose’, ‘Bird’: ‘Parrot’, ‘Animal’: ‘Dog’}
{‘Fruit’: ‘Orange’, ‘Flower’: ‘Rose’, ‘Bird’: ‘Parrot’, ‘Animal’: ‘Dog’}
Exercise
# Creating a dictionary
d= {‘name’: ‘Raja’, ‘age’: 30, ‘city’: ‘Mumbai’, ‘dept’: ‘Sales’}
print(d)
# Accessing values using keys
print(“Name:”, d[‘name’])
print(“Age:”, d[‘age’])
print(“City:”, d[‘city’])
print(“Dept:”, d[‘dept’])
# Adding a new key-value pair
d[‘occupation’] = ‘Engineer’
print(d)
# Iterating over keys
print(“\nKeys:”)
print(“————–“)
for key in d.keys():
print(key)
# Iterating over values
print(“\nValues:”)
print(“—————–“)
for value in d.values():
print(value)
# Iterating over items (key-value pairs)
print(“\nItems:”)
print(“———————“)
for key, value in d.items():
print(key, “:”, value)
# Checking if a key exists
key=’name’
if key in d:
print(f”\n{key} exists in the dictionary.”)
else:
print(f”\n{key} does not exists in the dictionary.”)
key=’address’
if key in d:
print(f”\n{key} exists in the dictionary.”)
else:
print(f”\n{key} does not exists in the dictionary.”)
# Removing a key-value pair
del d[‘age’]
print(d)
# Clearing the dictionary
d.clear()
print(d)
# Deleting the dictionary
del d
print(d)
Output:
{‘name’: ‘Raja’, ‘age’: 30, ‘city’: ‘Mumbai’, ‘dept’: ‘Sales’}
Name: Raja
Age: 30
City: Mumbai
Dept: Sales
{‘name’: ‘Raja’, ‘age’: 30, ‘city’: ‘Mumbai’, ‘dept’: ‘Sales’, ‘occupation’: ‘Engineer’}
Keys:
———————-
name age city dept occupation
Values:
—————————
Raja 30 Mumbai Sales Engineer
Items:
———————
name : Raja
age : 30
city : Mumbai
dept : Sales
occupation : Engineer
name exists in the dictionary.
address does not exists in the dictionary.
{‘name’: ‘Raja’, ‘city’: ‘Mumbai’, ‘dept’: ‘Sales’, ‘occupation’: ‘Engineer’}
{}
Traceback (most recent call last):
File “D:\Python\practice\dictionary.py”, line 57, in <module>
print(d)
^
NameError: name ‘d’ is not defined. Did you mean: ‘id’?
SETS in Python:
A set is an unordered collection of data with no duplicate elements. A set supports operations like union, intersection or difference. Sets are mutable, meaning their elements can be changed after the set is created.
A set is a collection of unique elements. Sets in Python are particularly useful when you need to store unique elements and perform operations like finding intersections, unions, etc.
Characteristics:
Unordered: Elements in a set do not maintain a specific order, and their order can change.
Unique Elements: Sets automatically handle duplicate values, ensuring each element is unique. If you add a duplicate, it will be ignored.
Mutable (but elements are immutable): We can add or remove elements from a set, but the elements themselves cannot be changed directly once inside the set.
Unindexed: Elements cannot be accessed using an index, unlike lists or tuples.
Creating a Set:
To create a set with one value, put the value in curly brackets. To create a set with multiple values, separate the values with commas and wrap it up with curly brackets.
Example:
set1 = {0}
print(set1)
set2 = {0, 1, 2, 3}
print(set2)
Output:
{0}
{0, 1, 2, 3}
It is possible to create a set out of list. To create a set from a list, we use set() function. A set can contain values of any data type and sets are unordered. This set does not remember the original order of the list that was used to create it. If we add items to this set, it would not remember the order in which we added them.
Example:
set1=set([1, 2, 3, 4])
print(set1)
Output:
{1, 2, 3, 4}
Adding Elements:
add(element):
We can add elements to a set using the add() method. add() method adds a single element to the set. Sets are collection of unique values. If we try to add a value that already exists in the set, it will do nothing.
Example:
set1 = {1, 2, 3, 4}
print(set1)
set1.add(5)
print(set1)
set1.add(2)
print(set1)
Output:
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
update(iterable):
Adds all elements from an iterable (e.g., list, tuple, another set) to the set.
Example:
set1={1,2,3,4}
set1.update([5,6,7])
print(set1)
Output:
{1, 2, 3, 4, 5, 6, 7}
Removing Elements:
There are four ways to remove individual element from a set. They are discard(), remove(), pop() and clear() method.
discard(element):
Removes a specified element if it exists; does nothing if the element is not found.
Example:
set1={1 ,2, 3, 4}
print(set1)
set1.discard(1)
print(set1)
set1.discard(6)
print(set1)
Output:
{1, 2, 3, 4}
{2, 3, 4}
{2, 3, 4}
remove(element):
Removes a specified element; raises a KeyError if the element is not found.
Example:
set1={1 ,2, 3, 4}
set1.remove(2)
print(set1)
set1.remove(7)
print(set1)
Output:
{1, 3, 4}
KeyError: 7
pop():
Removes and returns an arbitrary element from the set; raises a KeyError if the set is empty. The pop() method removes a single value from a set and returns the value. However, since set are unordered, there is no “last” value in a set, so there is no way to control which value gets removed. It is completely arbitrary.
Example:
set1={1, 2, 3, 4}
print(set1)
set1.pop()
print(set1)
Output:
{1, 2, 3, 4}
{2, 3, 4}
clear():
The clear() method removes all elements from the set, making it empty. Attempting to pop a value from an empty set will raise a KeyError.
Example:
set1={1, 2, 3, 4}
print(set1)
set1.clear()
print(set1)
Output:
{1, 2, 3, 4}
set()
Operations on Sets (Mathematical Set Operations):
Python’s set data structure support various operations like union, intersection, difference, and symmetric difference.
UNION
set1.union(set2) or set1 | set2 (combines all unique elements from both sets). The union() method returns a new set containing all unique elements from both sets.
Example-1:
set1={2, 4, 5, 12, 21, 25}
set2={ 1, 2, 3, 6, 8, 9, 12}
set3=set1.union(set2)
print(set3)
Output:
{1, 2, 3, 4, 5, 6, 8, 9, 12, 21, 25}
Example-2:
set1 = {1, 2, 3, 6, 8}
set2 = {3, 4, 5, 7}
print (set1 | set2)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
INTERSECTION:
set1. intersection(set2) or set1 & set2 (finds common elements). The intersection() method returns a new set containing only the common elements between the sets.
Example-1:
set1={2, 4, 5, 9, 12, 21, 30, 41}
set2={ 1, 2, 5, 8, 9, 12, 15, 21}
set3=set1.intersection(set2)
print(set3)
Output:
{2, 5, 9, 12, 21}
Example-2:
set1 = {1, 2, 3, 6, 7, 8}
set2 = {3, 4, 5, 6, 7}
print(set1 & set2)
Output:
{3, 6, 7}
DIFFERENCE:
set1. difference(set2) or set1 – set2 (finds elements in set1 but not in set2). The difference() method returns a new set containing elements present in the first set but not in the second.
Example-1
set1={2, 9, 12, 21, 30, 41, 66, 115, 185}
set2={3 , 5, 6, 8, 9, 12, 15, 17, 18, 21}
set3=set1.difference(set2)
print(set3)
Output:
{2, 66, 41, 115, 185, 30}
Example-2:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 – set2)
Output:
{1, 2}
SYMMETRIC DIFFERENCE:
set1.symmetric_difference(set2) or set1 ^ set2 (finds elements in either set but not in both). The symmetric_ difference() method returns a new set containing all the elements that are in exactly one of the sets. The symmetric difference of set1 from set2 looks different than the symmetric difference of set2 from set1.
Example-1:
set1={2, 4, 5, 6, 7, 9, 12, 30, 66, 115}
set2={1, 2, 3 , 5, 6, 9, 12, 15, 18, 21}
set3=set1.symmetric_difference(set2)
print(set3)
set3=set2.symmetric_difference(set1)
print(set3)
Output:
{1, 66, 3, 4, 7, 15, 18, 115, 21, 30}
{1, 66, 4, 7, 3, 15, 18, 115, 21, 30}
Example-2:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 ^ set2)
Output:
{1, 2, 4, 5}
Subset and Superset Checks:
set1. issubset(set2) or set1 <= set2:
Returns True if all elements of the first set are present in the second set.
Example-1:
set1={1, 2, 3}
set2={1, 2, 3, 4}
a=set1.issubset(set2)
b=set2.issubset(set1)
print(a)
print(b)
Output:
True
False
Example-2:
set1={1, 4, 3, 5, 2}
set2={1, 2, 3, 4}
a=set1<=set2
b=set2<=set1
print(a)
print(b)
Output:
False
True
issuperset(other_set) or set1 >= set2:
Returns True if all elements of the second set are present in the first set.
Example-1:
set1={1, 2, 3}
set2={1, 2, 3, 4}
a=set1.issuperset(set2)
b=set2.issuperset(set1)
print(a)
print(b)
Output:
False
True
Example-2:
set1={1, 4, 3, 5, 2}
set2={1, 2, 3, 4}
a=set1>=set2
b=set2>=set1
print(a)
print(b)
Output:
True
False
set1. isdisjoint(set2):
Returns True if the two sets have no common elements.
Example-1:
set1={6, 8, 10, 12}
set2={1, 2, 3, 4}
a=set1.isdisjoint(set2)
print(a)
Output:
True
Example-2:
set1={1, 2, 3}
set2={1, 2, 3, 4}
a=set1.isdisjoint(set2)
print(a)
Output:
False
Arrays in Python
An array is a collection of items stored at contiguous memory locations. Arrays are used to store multiple values in one single variable. An array is a special variable, which can hold more than one value at a time.
Unlike lists, which can hold items of different data types, arrays in Python are typically used to store items of the same data type. All elements of the array in Python must be of the same data type. Array in Python can be created by importing array module.
array( data_type , value_list ) syntax is used to create array in Python with data type and value list specified in its arguments.

Functions in Python
A function is a block of code that performs a specific task. Functions are made to execute a specific task and are reusable, which eliminates the need to write same line of code again and again.
We can make a function to put some commonly or repeatedly done tasks together and instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Functions enhance code organization, readability and reusability by allowing us to define a set of instructions once and execute them multiple times with different inputs.
Types of function-
Built in Library Function:
These are standard pre-defined functions provided by python that are available to use. Python has many built in functions such as print(), input(), sum(), max(), min() etc.

Output:
Total Marks: 369
Functions defined in Built-in Modules:
Functions available after importing specific modules from the standard library, like math.sqrt() from the math module.
Example:

Output:
Square Root:5.0
User-defined Function:
We can create our own functions based on our requirements, which are called user-defined function.
Defining a Function:
Functions are defined using the def keyword, followed by the function name, parentheses () which may contain parameters, and a colon : . The function body is then indented.

Calling a Function:
To execute the code within a function, we “call” it by using its name followed by parentheses, passing any required arguments.



Thanks for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our local library but I think I learned more clear from this post. I am very glad to see such fantastic info being shared freely out there.