UNIT I
OVERVIEW OF PYTHON
What is Python?
Python is a high-level, interpreted, and general-purpose programming language known for its
simplicity, readability, and versatility. It was created by Guido van Rossum and released
in 1991.
Python supports multiple programming paradigms like:
• Procedural programming
• Object-oriented programming
• Functional programming
It is widely used in:
• Web Development
• Data Science
• Machine Learning
• Artificial Intelligence
• Automation/Scripting
• Software Development
• Cybersecurity
• Game Development
Philosophy: "Simple is better than complex." (Python follows a clean and minimalistic
design philosophy.)
Advantages of Python
Feature Description
Python's syntax is clear and readable, similar to English, making it easy
Simple Syntax
to learn.
Open Source Python is free to download and use, even for commercial purposes.
Large Community A vast community means lots of tutorials, forums, and libraries.
Cross-platform Works on Windows, Linux, and macOS without major changes.
1
Feature Description
Extensive Comes with powerful standard libraries and third-party packages (e.g.,
Libraries NumPy, Pandas, Flask, Django).
Versatile Can be used in almost every domain like AI, data analysis, web apps,
Applications games, etc.
Rapid
Perfect for prototyping and startups. Less code, faster results.
Development
Dynamic Typing No need to declare variable types—Python interprets automatically.
Disadvantages of Python
Limitation Description
Slower than compiled
Because it is interpreted, Python is slower than C/C++ or Java.
languages
Not ideal for mobile
Rarely used for developing mobile apps.
development
High memory
Not suitable for memory-intensive tasks.
consumption
Because Python is dynamically typed, type-related errors may
Runtime Errors
arise during execution.
Due to Global Interpreter Lock (GIL), true multi-threading can
Limited multi-threading
be restricted.
2
Data Types in Python
What is a Data Type?
A data type defines what kind of value a variable can hold.
Python is dynamically typed, meaning you don’t need to declare the data type; it’s decided
automatically.
Example:
x = 10 # Integer
name = "Sai" # String
pi = 3.14 # Float
Main Built-in Data Types in Python
1. Numeric Types
Used to store numbers.
Data Type Description Example
int Integer values (whole numbers) x=5
float Decimal numbers pi = 3.14
complex Complex numbers z = 2 + 3j
2. String Type
• A string is a sequence of characters enclosed in ' ' or " ".
• Used to store text.
Eg:-
name = "Tushar"
• Strings are immutable (can’t be changed after creation).
• Supports operations like slicing, concatenation, repetition, etc.
3. Boolean Type
• Represents True or False values.
3
• Used in decision-making and comparisons.
4. Sequence Types
Type Description Example
list Ordered, changeable, allows duplicates fruits = ["apple", "banana"]
tuple Ordered, unchangeable, allows duplicates colors = ("red", "blue")
range Represents a sequence of numbers range(5) gives 0 to 4
Ordered
• Means the items have a fixed position (index).
• The order in which you add items is remembered.
• Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
Changeable (Mutable)
• You can modify the contents (add, remove, or update elements) after creation.
• Example (List is changeable)
fruits[1] = "mango"
print(fruits) # Output: ['apple', 'mango', 'cherry']
Unchangeable (Immutable)
• You cannot modify the elements once it’s created.
• Example (Tuple is unchangeable):
colors = ("red", "green", "blue")
colors[0] = "yellow" # Error! Tuples are unchangeable
Allows Duplicates
• You can have the same value more than once.
• Example:
numbers = [1, 2, 2, 3]
4
5. Set Type
• A set is an unordered collection with no duplicate items.
Eg:-
nums = {1, 2, 3}
• Useful for membership testing and removing duplicates.
6. Dictionary Type
• A dictionary is a collection of key-value pairs.
Eg:-
student = {"name": "Kavya", "age": 19}
• Keys must be unique and immutable
Type Keyword Mutable Ordered Example
Integer int ✖ ✖ 10
Float float ✖ ✖ 3.14
Complex complex ✖ ✖ 2+3j
String str ✖ ✔ "Mee"
List list ✔ ✔ [1,2,3]
Tuple tuple ✖ ✔ (1,2,3)
Set set ✔ ✖ {1,2,3}
Dictionary dict ✔ ✔ (Python 3.7+) {"a":1}
Boolean bool ✖ ✖ True/False
5
1. Assignments in Python
Assignment means storing a value in a variable using the = operator.
Syntax:
variable_name = value
Examples:
x = 10 # Assigns 10 to x
name = "Minha" # Assigns string "Minha" to name
is_valid = True # Assigns boolean value
Multiple Assignments:
a=b=c=5 # All three variables get the value 5
x, y = 1, 2 # Assigns 1 to x and 2 to y
2. Expressions in Python
An expression is any combination of variables, values, operators, and function calls that
evaluates to a single result.
Examples:
a+b # Arithmetic expression
"Hi " + name # String expression
x > 10 # Boolean expression (returns True or False)
len(name) # Function call expression
Expression with Assignment:
x=3+4 # 3 + 4 is an expression
x = 7 is an assignment
Difference Between Assignment and Expression:
Feature Assignment Expression
Purpose Store a value in a variable Compute and return a value
Involves = operator Operators like +, -, *, /, etc.
Output Does not return a value Always returns a result
6
Feature Assignment Expression
Example x=5 3+2→5
Example Combining Both:
a = 10 # Assignment
b=5
c=a+b # Expression `a + b` is evaluated, result (15) is assigned to c
Control Flow Statements
Control Flow Statements are used to control the order in which code is executed in a
program. They help Python make decisions, repeat tasks, and skip parts of the code based on
certain conditions.
Types of Control Flow Statements in Python:
1. Conditional Statements (Decision Making)
Used to execute code only if a condition is true.
if Statement:
x = 10
if x > 5:
print("x is greater than 5")
if-else Statement:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
if-elif-else Statement:
x=0
if x > 0:
print("Positive")
7
elif x < 0:
print("Negative")
else:
print("Zero")
2. Looping Statements (Iteration)
Used to repeat a block of code.
for Loop:
while Loop:
3. Loop Control Statements
Used to control the flow within loops.
break — Exit the loop:
continue — Skip the current iteration:
pass — Do nothing (used as a placeholder):
Summary Table
Statement Type Keywords Use
Conditional if, elif, else Decision making
Looping for, while Repeating code
Loop Control break, continue, pass Managing loop execution
Loops in Python
Loops are used to execute a block of code repeatedly as long as a certain condition is true.
Types of Loops in Python
1. for Loop
Used when you want to iterate over a sequence (like a list, tuple, string, or range).
Syntax:
for variable in sequence:
# block of code
8
Example:
for i in range(5):
print(i) # prints 0 to 4
2. while Loop
Used when you want to repeat a block of code as long as a condition is true.
Syntax:
while condition:
# block of code
Example:
x=0
while x < 5:
print(x)
x += 1
3. Nested Loops
A loop inside another loop. Can be a for-in-for, while-in-while, or mixed.
Example:
for i in range(3):
for j in range(2):
print(i, j)
Summary Table
Loop Type Used For Example Syntax
for loop Iterating over a sequence for i in range(5):
while loop Looping based on a condition while x < 5:
Nested loop Loop inside another loop for i in range(3): for j in range(2):
9
break Statement in Python
The break statement is used to immediately exit a loop (either a for or while loop), even if
the loop condition is still true.
Syntax:
for item in sequence:
if condition:
break
or
while condition:
if condition_to_exit:
break
Example with for Loop:
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
Explanation: When i becomes 5, the loop breaks and exits.
Example with while Loop:
x=1
while x <= 10:
if x == 6:
break
10
print(x)
x += 1
Output:
1
2
3
4
5
Use Cases:
• Exiting a loop early when a condition is met
• Searching for an element and exiting once found
• Preventing unnecessary iterations
Summary Table
Feature Description
Purpose Immediately exits the loop
Used with for and while loops
Control Flow Jumps out of the loop
Common Use When a match or condition is found
1. continue Statement
The continue statement skips the current iteration of a loop and moves to the next
iteration.
Syntax:
for i in range(5):
if i == 2:
continue
print(i)
11
Output:
0
1
3
4
Explanation: When i is 2, the continue skips the print(i) and continues the loop with i = 3.
Use Cases:
• Skip specific conditions while continuing the loop
• Filtering out unwanted data during iteration
2. pass Statement
The pass statement is a placeholder. It does nothing and is used when a statement is
syntactically required but you don’t want any action.
Syntax:
for i in range(3):
pass
Common Use:
• Writing code structure before full implementation
• Placeholders for loops, functions, classes, or conditionals
Example:
def my_function():
pass # Function body will be added later
Summary Table
Statement Action Taken Common Use
continue Skips current loop iteration Skipping unwanted cases
pass Does nothing (placeholder) Structuring code before writing logic
12