Unit – 1
Python : Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-
level programming language. Python is dynamically-typed and garbage-collected programming
language It was created by Guido van Rossum in1991. Like Perl, Python source code is also available
under the GNU General Public License (GPL).
Why to use Python:
The following are the primary factors to use python in day-to-day life:
1. Python is object-oriented : Structure supports such concepts as polymorphism, operation
overloading and multiple inheritance.
2. Indentation : Indentation is one of the greatest feature in python.
3. It’s free (open source) Downloading python and installing python is free and easy
4. It’s Powerful
-in types and tools
Python Indentation : In Python, indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All statements with the same level of
indentation are considered part of the same block. Indentation is achieved using whitespace (spaces or
tabs) at the beginning of each line.
For Example
Output
The first two print statements are indented by 4 spaces, so they belong to the if block.
The third print statement is not indented, so it is outside the if block.
Prof. Neha Daharwal
Features of Python Programming
Easy to Learn and Read: Python's syntax is designed to be clean and readable, often
resembling everyday English, which makes it an excellent choice for beginners. It uses
indentation instead of curly braces to define code blocks, which enforces a clean and consistent
code style.
Interpreted Language: Python is an interpreted language, meaning code is executed line by
line at runtime. This facilitates faster testing and debugging, as errors are detected immediately,
without requiring the entire program to be compiled first.
Dynamically Typed: In Python, you do not need to explicitly declare the data type of a variable.
The interpreter determines the variable type at runtime based on the assigned value, offering
flexibility and reducing development time.
Free and Open Source: The Python language is free to use and distribute. Its source code is
publicly available and maintained by a global community, encouraging innovation and
continuous improvement.
Large Standard Library & Ecosystem: Python comes with an extensive standard library that
provides built-in modules for a wide array of tasks (e.g., file handling, internet protocols, regular
expressions). Beyond this, a massive ecosystem of third-party libraries (accessible via the
Python Package Index, or PyPI) supports specialized areas like data science (NumPy, Pandas,
TensorFlow) and web development (Django, Flask).
Object-Oriented Programming (OOP): Python fully supports OOP concepts such as classes,
objects, inheritance, and polymorphism, allowing for the creation of modular, reusable, and
scalable code. It also supports procedural and functional programming paradigms, offering
developers flexibility in coding styles.
Cross-Platform Compatibility: Python code can run on various operating systems, including
Windows, macOS, and Linux, without requiring major modifications. This portability makes it
ideal for developing cross-platform applications.
GUI Support: Libraries like Tkinter, PyQt, and Kivy allow for the creation of desktop
applications with graphical interfaces.
Prof. Neha Daharwal
Extensible and Embeddable: Python code can be integrated with code written in other
languages like C, C++, and Java. This allows performance-intensive parts of a program to be
written in a faster language while still leveraging Python's simplicity and features.
Large Community Support: Python has one of the largest and most active programming
communities in the world. This provides extensive documentation, tutorials, and forums,
ensuring that help is always accessible when encountering issues.
Python Variable
In Python, variables are used to store data that can be referenced and manipulated during program
execution. A variable is essentially a name that is assigned to a value.
Python variables are symbolic names (labels) that reference objects (values) stored in a computer's
memory.
Example
x=5 # An integer assignment
name = "Samantha" # An string assignment
print(x)
print(name)
This produces the following result –
5
Samantha
Rules for Naming Variable in Python :
Can include letters, numbers, and underscores (e.g., student_name1)
Cannot use Python reserved keywords (e.g., class, def, return)
Variable names are case-sensitive (score, Score, and SCORE are different)
Must begin with a letter (a–z, A–Z) or an underscore (_)
Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of
the program.
It enhance the readability of the code.
It can be used to identify functionality or structure the code-base.
Prof. Neha Daharwal
It can help understanding unusual or tricky scenarios handled by the code to prevent accidental
removal or changes.
It can be used to prevent executing any specific part of your code, while making changes or
testing.
There are two types of comments in python programming.
1. Single-line comments : Single-line comments begins with a hash(#) symbol and is useful in
mentioning that the whole line should be considered as a comment until the end of line.
2. A Multi line comment : It is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.
Data Types in Python
Data types determine the type of value a variable can store, including a number, text, or lists. They help
organize and process data effectively. They also ensure that the operations are performed correctly.
1. Numeric Data Types : Numeric data types in Python can hold numeric values such as integers,
decimal numbers(floating numbers), and complex numbers.
Integer: Integers are represented by the int class and it represent whole numbers. It can contain
positive and negative values. The size of an integer is not limited by a fixed maximum it can
grow as long as memory permits
Example
Prof. Neha Daharwal
x=5
print(x)
print(type(x))
Floating point: Floating-point numbers represent numbers with a decimal point or
fractions. Floating point variables are represented by the float class. It can only hold decimal
values.
Example
pi = 3.14.
print(x)
print(type(x))
Complex Numbers: Complex numbers are represented by complex classes Complex numbers
have a real and imaginary part.
Example
z = 2 + 3j, where j is the suffix for the imaginary unit.
print(type(x))
2. Sequence Data Types
A sequence is an ordered collection of items, which can be of similar or different data types. There are
several sequence data types of Python:
String : A string is a sequence of characters enclosed in single or double quotes. Strings are
immutable (cannot be changed) We can access individual characters with the help of an index. The str
class represents it.
Example
name = "Python"
print(name) # Python
print(name[0]) # P
Accessing Strings in Python:
Individual characters within a string can be accessed using an index. Python uses zero-based indexing,
meaning the first character is at index 0. Negative indexing can also be used to access the characters
from the end of the string.
Prof. Neha Daharwal
List : List in Python are created using a square bracket [ ]. They can hold various data types, such
as numbers, text, or even other lists. Each entry within a list is separated by a comma. Lists allow
you to combine multiple items into one collection and give easy access and modification as
required.
Example
Output
Access List Items in Python
We can access the list of items with the help of the index. In Python, negative indices are used for
reverse traversal, like: a[-1] represents the first element from the end, a[-2] represents the second
element from the end.
Prof. Neha Daharwal
Output:
Tuple
Tuple is an ordered collection of Python objects. Tuple data types are also the same as list data types in
Python. The only difference between them is that tuples are immutable, which means we can not change
the tuple elements after they are created under parentheses.
Creating a Tuple in Python. In Python, tuples are created using parentheses with different types of
values separated by commas.
Output
Access Tuple Items in Python
We can access tuple elements with the help of an index. With the help of the index and subscript
operators, we can access the tuple elements easily.
Prof. Neha Daharwal
Output
Set : A set in Python is an unsorted (unordered) collection of elements that contains unique
elements. They are unordered and do not allow duplicates. Sets are defined using curly brackets.
Creating a Set in Python
A set is created in Python with the set() function and an iterable object or list of objects separated
by commas. Sets can also contain different types of data.
Output:
Dictionary : The dictionary in Python uses data types to store elements in key-value pairs like
maps. An unordered collection of data values is stored in the dictionary in the form of key-value
pairs. In the key-value pair format, the key values are separated from each other by a colon.
Create a Dictionary in Python
In Python, a dictionary can be built using the built-in function dict(). Any object can be used to
take the values provided in the dictionary. Duplicates are allowed in a dictionary, but the keys
must be unique. The keys of the dictionary are case-sensitive.
Output
Prof. Neha Daharwal
Access Dictionary Values Using Keys in Python
The values in the dictionary can be accessed using their keys. The built-in function get() can be used to access the
values.
Boolean : Python also provides one built-in data type, Boolean, that gives us two values, True and
False. It can take the value of either True or False and is implemented by the class bool. The true
expressions will be returned as True by Python, while expressions that are not true will be returned as
False.
Output
Prof. Neha Daharwal
Difference between List & Array & Tuple & Set & Dictionary
List Tuple Set Dictionary
A list is a non- A Tuple is a non- The set data structure A dictionary is also a non-
homogeneous data homogeneous data is non-homogeneous homogeneous data structure
structure that stores structure that stores but stores the that stores key-value pairs.
the elements in elements in columns of elements in a single
columns of a single a single row or multiple row.
row or multiple rows. rows.
The list can be A tuple can be The set can be The dictionary can be
represented by [ ] represented by ( ) represented by { } represented by { }
The list allows Tuple allows duplicate The Set will not allow The dictionary doesn't
duplicate elements elements duplicate elements allow duplicate keys.
A list can be created Tuple can be created A set can be created A dictionary can be created
using using using using the dict() function.
the list() function the tuple() function. the set() function
The list can be nested A tuple can be nested The set can be nested The dictionary can be
among all among all among all nested among all
A list is mutable i.e A tuple is immutable i.e A set is mutable i.e A dictionary is mutable, its
we can make any we can not make any we can make any Keys are not duplicated.
changes in the list. changes in the tuple. changes in the set, its
elements are not
duplicated.
List is ordered Tuple is ordered Set is unordered Dictionary is ordered
(Python 3.7 and above)
Unit 2
Prof. Neha Daharwal
Conditional Statement :
Conditional statements in Python are used to execute certain blocks of code based on specific
conditions. These statements help control the flow of a program, making it behave differently in
different situations.
[Link] Conditional Statement
If statement is the simplest form of a conditional statement. It executes a block of code if the given
condition is true.
Syntax : Flow Chart for If statement
Example :
age = 20
if age >= 18:
print("Eligible to vote.")
Output
2. If else Conditional Statement
Prof. Neha Daharwal
If Else allows us to specify a block of code that will execute if the condition(s) associated with an if or
elif statement evaluates to False. Else block provides a way to handle all other cases that don't meet the
specified conditions.
Syntax Flowchart of the if – Else Statement
Syntax :
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output :
3. elif Statement : elif statement in Python stands for "else if." It allows us to check multiple
conditions, providing a way to execute different blocks of code based on which condition is true. Using
elif statements makes our code more readable and efficient by eliminating the need for multiple nested if
statements.
Syntax
Prof. Neha Daharwal
Example :
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
output
Prof. Neha Daharwal
4. Nested if..else : Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within conditions.
Nested if statements allow us to place one if statement inside another. This helps when we need to check
multiple conditions in a structured way.
We use conditional statements in Python to control the flow of code based on more than one condition.
Syntax Flowchart
Example :
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output
Prof. Neha Daharwal
Prof. Neha Daharwal