Why Learn Python?
If you're wondering why Python is an excellent choice for beginners and seasoned developers
alike, here are some of the reasons:
• Readability and Simplicity: Python's clean syntax enhances code readability, reducing
development time and making it beginner-friendly.
• Versatility: You can use Python to build a diverse range of applications, from web
development to data science and AI. It also has an extensive standard library and many helpful
third-party packages.
• Community and Documentation: Python has a robust community and comprehensive
documentation that provides ample support, fostering the language's popularity and growth.
• Cross-Platform Compatibility: Ensures seamless execution across Windows, macOS, and
Linux.
• Extensive Libraries and Frameworks: A rich ecosystem simplifies complex tasks, saving
time and effort for developers.
Key Characteristics of Python
Understanding the key characteristics of Python will give you insights into its strengths and
why it's a popular choice among developers:
• Interpreted Language: Your code is not directly translated by the target machine. Instead, a
special program called the interpreter reads and executes the code, allowing for cross platform
execution of your code.
• Dynamically Typed: Dynamic typing eliminates the need for explicit data type declarations,
enhancing simplicity and flexibility.
• Object-Oriented: Python supports object-oriented principles, promoting code modularity and
reusability. Indentation-based Syntax: Indentation-based syntax enforces code readability
and maintains a consistent coding style.
• Memory Management: Automatic memory management through garbage collection
simplifies memory handling for developers.
Practical Uses of Python
• Web Development: Python, with frameworks like Django and Flask, powers back-end
development for robust web applications.
• Data Science and Machine Learning: Widely used in data science, Python's libraries like
NumPy and Pandas support data analysis and machine learning.
• Automation and Scripting: Python excels in automating tasks and scripting, simplifying
repetitive operations.
• AI and NLP: Python, with libraries like TensorFlow, dominates in AI and natural language
processing applications.
• Game Development: Python, combined with Pygame, facilitates 2D game development for
hobbyists and indie developers.
• Scientific Computing: Python is a valuable tool in scientific computing, chosen by scientists
and researchers for its extensive libraries.
Python Variables and Data Types
The primary purpose of computers is to process data into useful information, for that to happen,
the data needs to be stored in its memory. This is achieved using a programming language's
variables and data types.
Data types in Python are particular kinds of data items, as defined by the value they can take.
Variables, on the other hand, are like labeled containers that store this data. They enable you to
manage and modify information using specific identifiers.
Data types are generally classified into two types:
❖ Primitive (Fundamental) Data Types:
Primitive data types represent simple values. These data types are the most basic and essential
units used to store and manipulate information in a program. They translate directly into low-
level machine code.
Primitive data types include:
• String (str): Represents sequences of characters. Should be enclosed in quotes.
Example: "Hello, Python!"
• Integer (int): Represents whole numbers without decimals. Example: 42
• Float (float): Represents numbers with decimals. Example: 3.14
• Boolean (bool): Represents either True or False.
Characteristics of Primitive Data Types:
• Immutability: Primitive data types are immutable, meaning their values cannot be changed
after they are created. Any operation that appears to modify a primitive value creates a new
value.
• Direct Representation: Each primitive data type directly corresponds to a specific low-level
machine code representation.
• Atomic Values: Primitive data types represent individual, atomic values. They are not
composed of other types or structures.
Use Cases for Primitive Data Types:
• Strings are used for text manipulation and representation.
• Integers and floats are essential for numerical calculations.
• Booleans are employed in logical operations and decision-making.
Let's see how these work by continuing to write some Python code.
In this snippet, you've introduced variables with different data types. Run the program and
observe how Python handles these data types.
❖ Non-Primitive (Composite) Data Types in Python
Non-primitive data types are structures that can hold multiple values and are composed of other
data types, including both primitive and other composite types. Unlike primitive data types,
non-primitive types allow for more complex and structured representations of data.
Non-primitive data types include:
• List (list): Represents an ordered and mutable collection of values. Example: fruits = ["apple",
"banana", "cherry"]
• Tuple (tuple): Represents an ordered and immutable collection of values.
Example: coordinates = (3, 7)
• Dictionary (dict): Represents an unordered collection of key-value pairs. Example: person =
{"name": "Alice", "age": 25, "is_student": True}
Characteristics of Non-Primitive Data Types:
• Mutability: Lists are mutable, meaning their elements can be modified after creation. Tuples,
on the other hand, are immutable – their elements cannot be changed. Dictionaries are mutable
– you can add, modify, or remove key-value pairs.
• Collection of Values: Non-primitive data types allow the grouping of multiple values into a
single structure, enabling the creation of more sophisticated data representations.
• Ordered (Lists and Tuples): Lists and tuples maintain the order of elements, allowing for
predictable indexing.
• Key-Value Mapping (Dictionary): Dictionaries map keys to values, providing a way to
organize and retrieve data based on specific identifiers.
Use Cases for Non-Primitive Data Types:
• Lists: Useful when you need a collection that can be altered during the program's execution,
such as maintaining a list of items that may change over time.
• Tuples: Suitable when you want to ensure that the data remains constant and cannot be
accidentally modified. Often used for representing fixed sets of values.
• Dictionaries: Ideal for scenarios where data needs to be associated with specific labels or keys.
They offer efficient data retrieval based on these identifiers.
Run the program to see how lists and tuples allow you to organize and store data. In this code
snippet:
• The fruits variable is a list containing strings representing different fruits.
• The coordinates variable is a tuple with two integers representing coordinates.
• The person variable is a dictionary associating keys ("name," "age," "is_student") with
corresponding values.
Data types are crucial for several reasons:
• Memory Allocation: Different data types require different amounts of memory. Knowing the
data type allows the computer to allocate the appropriate amount of memory for a variable.
• Operations: Each data type supports specific operations. For example, you can add
two integer numbers, concatenate two strings, or compare two boolean values.
• Error Prevention: Using the wrong data type in an operation can lead to errors. Data types
help prevent unintended consequences by enforcing rules on how different types can interact.
Operators in Python
Operators in Python are symbols that perform operations on variables and values.
An operand refers to the inputs or objects on which an operation is performed.
❖ Arithmetic Operators:
Arithmetic operators are fundamental components of any programming language, allowing
developers to perform basic mathematical operations on numerical values.
In Python, several arithmetic operators enable you to carry out calculations efficiently.
• Addition (+): Adds two operands.
• Subtraction (-): Subtracts the right operand from the left operand.
• Multiplication (*): Multiplies two operands.
• Division (/): Divides the left operand by the right operand (always returns a float).
• Modulus (%): Returns the remainder of the division of the left operand by the right
operand.
• Exponentiation (**): Raises the left operand to the power of the right operand.
The code above initializes two variables, num1 and num2, with the
values 10 and 3 respectively, representing two numerical operands.
Then, arithmetic operations are performed using these operands:
• add_result stores the result of adding num1 and num2.
• sub_result stores the result of subtracting num2 from num1.
• mul_result stores the result of multiplying num1 and num2.
• div_result stores the result of dividing num1 by num2.
• mod_result stores the remainder of dividing num1 by num2.
• exp_result stores the result of raising num1 to the power of num2.
Finally, the results of these arithmetic operations are printed using print() statements, each
labelled appropriately, such as "Addition:", "Subtraction:", and so on, followed by the
corresponding result.
❖ Comparison Operators
Comparison operators in Python are essential tools for evaluating and comparing values. They
enable you to express conditions and make decisions based on the relationship between
different values. They return either True or False based on the comparison result.
Here are the common comparison operators:
• Equal to (==): Checks if two operands are equal.
• Not equal to (!=): Checks if two operands are not equal.
• Greater than (>): Checks if the left operand is greater than the right operand.
• Less than (<): Checks if the left operand is less than the right operand.
• Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right
operand.
• Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.
The variable age is initialized with the value 25, representing a person's age.
Then, the comparison operator >= is used to evaluate whether age is greater than or equal to 18.
The result of this comparison determines the Boolean value stored in the variable is_adult. If
the age is 18 or older, is_adult will be True, indicating adulthood.
Then the logical operator and is utilized to combine two comparison operations. The first
comparison, age >= 13, checks if the age is 13 or older. The second comparison, age < 18,
ensures the age is less than 18. If both conditions are true, is_teenager will be True, signifying
teenage years.
Finally, the results are printed using print() statements, indicating whether the person is
classified as an adult (True or False) and whether they are identified as a teenager
(True or False).
Statements in Python
Statements instruct the interpreter to perform specific actions or operations. These actions can
range from simple assignments of values to variables to more complex control flow structures
and iterations.
Understanding different types of statements is essential for writing effective and expressive
Python code.
❖ Assignment Statements
Assignment statements are the most basic type of statement in Python. They are used to assign
values to variables, creating a named reference to data.
Here's an example:
In this snippet, x is assigned the integer value 10, and the name is assigned the string "Alice".
These assignments create variables that can be used throughout the program.
❖ Print Statement
The print statement is used to display output in the console. It is a crucial tool for debugging
and providing information to users. Example:
❖ Conditional Statements (if, elif, else)
Conditional statements are used when you want to execute different blocks of code based on
certain conditions.
Example: Python if Statement
a = 3 if a > 2:
print(a, "is greater") print("done")
a = -1 if a < 0:
print(a, "a is smaller") print("Finish")
Alternative if (If-Else):
An else statement can be combined with an if statement. An else statement contains the block
of code (false block) that executes if the conditional expression in the if statement resolves to
0 or a FALSE value.
The else statement is an optional statement and there could be at most only one else Statement
following if.
Syntax of if - else :
if test expression:
Body of if stmts else:
Body of else stmts
If - else Flowchart:
Example of if - else:
a=int(input('enter the number')) if a>5:
print("a is greater") else:
print("a is smaller than the input given")
Chained Conditional: (If-elif-else):
The elif statement allows us to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement
is optional. However, unlike else, for which there can be at most one statement, there can be
an arbitrary number of elif statements following an if.
Syntax of if – elif - else :
If test expression:
Body of if stmts elif test expression:
Body of elif stmts else:
Body of else stmts
Flowchart of if – elif - else:
Example of if - elif – else:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater") elif b>c:
print("b is greater") else:
print("c is greater")
var = 100 if var == 200:
print("1 - Got a true expression value") print(var)
elif var == 150:
print("2 - Got a true expression value") print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var) else:
print("4 - Got a false expression value")
print(var) print("Good bye!")
❖ The if statement checks if age is less than 18.
❖ The elif statement (shorthand for else if) checks if age is between 18 (inclusive) and 21
(exclusive).
❖ The else statement is executed if none of the above conditions are met.\
Loops (for and while): Loops are used to repeat a block of code multiple times. In Python
Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
❖ For Loop:
A for loop is used when you know the number of iterations in advance. Suppose you had a list
containing the names of fruits, and you wanted to print each fruit. In this case, a for loop is an
ideal choice for iterating over the elements of the list.
Python for loop is used for repeated execution of a group of statements for the desired number
of times. It iterates over the items of lists, tuples, strings, dictionaries and other iterable objects.
Sample Program:
numbers = [1, 2, 4, 6, 11, 20]
seq=0
for val in numbers:
seq=val*val
print(seq)
Flowchart:
Here's an example using Python:
In this example, the for loop iterates over each element in the fruits list and prints each fruit.
❖ While Loop:
A while statement is a control flow statement that allows you to execute a block of code
repeatedly as long as a specified condition is true.
• Loops are either infinite or conditional. Python while loop keeps reiterating a block of code
defined inside it until the desired condition is met.
• The while loop contains a Boolean expression and the code inside the loop is repeatedly
executed as long as the Boolean expression is true.
• The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
Flowchart:
Examples
i=1
while i<=6:
print("Mrcet college") i=i+1
i=1
while i<=3:
print("MRCET",end=" ") j=1
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print( )
In this scenario, the while loop continues executing as long as the count variable is less than 5.
The code inside the loop increments the count and prints the current count in each iteration.
Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence: for val in sequence:
statements statements
# Example 1 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
Break and Continue Statements
Break and continue statements are used within loops.
• Break: The break statement terminates the loop containing it and control of the
program flows to the statement immediately after the body of the loop. If break
statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Flowchart:
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
while test expression
# code inside while loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop
Example:
for val in "MRCET COLLEGE": if val == " ":
break print(val)
print("The end")
Program to display all the elements before number 88
for num in [11, 9, 88, 10, 90, 3, 19]:
print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
Terminating the loop
#------------------------------------- for letter in "Python": # First Example
if letter == "h": break
print("Current Letter :", letter )
• Continue: Skips the rest of the code inside the loop for the current iteration, then continues the
loop. The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Flowchart:
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop If condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
while test expression
# code inside while loop If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop
Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
# program to display only odd numbers
for num in [20, 11, 9, 66, 4, 89, 44]:
# Skipping the iteration when number is even
if num%2 == 0:
continue
# This statement will be skipped for all even numbers print(num)
Examples:
In the break example, the loop stops when i is equal to 3, and the numbers 0, 1, and 2 are
printed.
In the continue example, when i is equal to 2, the continue statement skips
the print(i) statement for that iteration, resulting in the omission of the number 2 from the
output.
Functions in Python
Functions are reusable blocks of code, enhancing modularity by enclosing functionality into
separate, organized units. This approach helps avoid code duplication and significantly
improves code readability.
The code above contains a simple Python function called greet(). When 'called' or 'invoked',
this function prints "Hello, World!" to the console. It's a basic example illustrating how
functions work in Python.
You can take this a step further by including parameters. Parameters serve as placeholders for
values passed to a function during its invocation, allowing functions to accept input and
perform operations based on that input.
Modify the previous example on if elif else statement to include functions:
In this example, the check_age function takes an age parameter and performs the same
conditional check as the original code. The function allows you to reuse this logic for different
age values by simply calling the function with the desired age.
You can call check_age function with any age value, and it will print the appropriate message
based on the age provided.
asically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool()………so on….
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20
2. User-defined functions - Functions defined by the users themselves.
def add_numbers(x,y):
sum = x + y return sum
print("The sum is", add_numbers(5, 20))
Output:
The sum is 25
Lists, Tuples, Dictionaries
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
comprehension; Dictionaries: operations and methods, comprehension;
Lists, Tuples, Dictionaries:
List:
• It is a general purpose most widely used in data structures
• List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable).
• To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
• We can construct / create list in many ways.
Ex: >>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
----------------------
>>> x=list()
>>> x
[]
--------------------------
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for membership
Basic List Operations:
Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.
List slices:
>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
Tuples:
A tuple is a collection that is ordered and unchangeable. In Python tuples are written with round
brackets.
• Supports all operations for sequences.
• Immutable, but member objects may be mutable.
• If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being
added, changed, or deleted.
• Tuples are more efficient than list due to python’s implementation
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3) X=tuple(list1) X=1,2,3,4
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-----------------------
>>> x=() >>> x ()
----------------------------
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
-----------------------------
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
Some of the operations of tuple are:
• Access tuple items
• Change tuple items
• Loop through a tuple
• Count()
• Index()
• Length()
Access tuple items: Access tuple items by referring to the index number, inside square brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples are
unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop >>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2) 4
Index (): Searches the tuple for a specified value and returns the position of where it was found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> [Link](2)
1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=[Link](2)
>>> print(y)
1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries
are written with curly brackets, and they have keys and values.
• Key-value pairs
• Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’} X=dict([(‘a’,3) (‘b’,4)] X=dict(‘A’=1,’B’ =2)
Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004} >>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}
Sets
Python also includes a data type for sets. A set is an unordered collection with no duplicate
elements. Basic uses include membership testing and eliminating duplicate entries. Set objects
also support mathematical operations like union, intersection, difference, and symmetric
difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you
have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss
in the next section. Here is a brief demonstration:
The range() Function
If you do need to iterate over a sequence of numbers, the built-in function range() comes in
handy. It generates arithmetic progressions:
The given end point is never part of the generated sequence; range(10) generates 10 values, the
legal indices for items of a sequence of length 10. It is possible to let the range start at another
number, or to specify a different increment (even negative; sometimes this is called the ‘step’):
Object-Oriented Programming (OOP) Meaning
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around objects, which are instances of classes. These objects
encapsulate data (attributes) and behaviour (methods), enabling modular, reusable, and
maintainable code.
Key Concepts of OOP
1. Classes and Objects: A class is a blueprint for creating objects, defining their attributes
and methods. For example, a Car class might define properties like colour and speed
and methods like drive() or brake(). An object is an instance of a class. For example,
myCar = Car() creates an object myCar with specific attributes and behaviours.
2. Encapsulation: Encapsulation involves bundling data and methods within an object
and restricting direct access to some components. This ensures data hiding and protects
the integrity of the object.
3. Inheritance: Inheritance allows a class (child) to derive properties and methods from
another class (parent). For instance, a SportsCar class can inherit from a Car class and
add unique features like turboBoost().
4. Polymorphism: Polymorphism enables objects to take on multiple forms. For example,
a draw() method might behave differently for Circle and Rectangle objects, even though
both inherit from a common Shape class.
5. Abstraction: Abstraction hides complex implementation details and exposes only
essential features. For example, a Car class might provide a start() method without
revealing the internal workings of the engine.
Benefits of OOP
• Code Reusability: Classes and objects can be reused across projects, reducing
redundancy.
• Modularity: Code is organized into manageable sections, making it easier to debug
and maintain.
• Scalability: OOP supports the creation of complex systems by breaking them into
smaller, reusable components.
• Security: Encapsulation and abstraction protect sensitive data and reduce the risk of
unintended modifications.
Examples of OOP Languages
Popular OOP languages include Python, Java, C++, C#, and Ruby. These languages support
OOP principles, enabling developers to create robust and scalable applications.
OOP is widely used in software development due to its ability to model real-world entities,
promote code reuse, and simplify complex systems.
Abstraction in Python
Abstraction is a fundamental concept in object-oriented programming (OOP) that focuses on
hiding the implementation details of a system while exposing only the essential features or
functionalities. In Python, abstraction is achieved using abstract classes and abstract
methods, which are provided by the abc (Abstract Base Classes) module.
Key Features of Abstraction in Python
1. Abstract Classes:
o An abstract class serves as a blueprint for other classes.
o It cannot be instantiated directly.
o It is defined using the ABC class from the abc module.
2. Abstract Methods:
o These are methods declared in an abstract class but do not have any
implementation.
o Subclasses inheriting the abstract class must implement all abstract methods.
3. Concrete Methods:
o Abstract classes can also have concrete (fully implemented) methods, which can
be inherited by subclasses.
Benefits of Abstraction
• Hides Complexity: Users interact with simpler interfaces without worrying about the
underlying implementation.
• Promotes Reusability: Abstract classes can define common behavior for multiple
subclasses.
• Improves Code Maintainability: Changes in implementation do not affect the
interface.
Types of Abstraction
1. Data Abstraction:
o Hides the internal representation of data.
o Achieved using encapsulation (e.g., private variables).
2. Process Abstraction:
o Hides the implementation details of processes or methods.
o Achieved using abstract methods and polymorphism.
By using abstraction effectively, Python developers can create robust, scalable, and user-
friendly applications.