0% found this document useful (0 votes)
2 views67 pages

Python Notes - SEC

Uploaded by

Dad's Princess
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views67 pages

Python Notes - SEC

Uploaded by

Dad's Princess
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction

• Python is a general purpose high level programming language.


• Python was developed by Guido Van Rossam in 1989 while working at National Research Institute
at Netherlands.
• But officially Python was made available to public in 1991. The official Date of Birth for Python is:
Feb 20th 1991.
• Python is recommended as first programming language for beginners.
Eg1: To print Helloworld
Java:
public class HelloWorld
{
psv main(String[] args)
{
SOP("Hello world");
}
}

C:
#include<stdio.h>
void main()
{
print("Hello world");
}

Python:
print("Hello World")

Eg2: To print the sum of 2 numbers


Java:
public class Add
{
public static void main(String[] args)
{
int a,b;
a =10; b=20;
}
[Link]("The Sum:"+(a+b));
}
C:
#include <stdio.h>
void main()
{
int a,b;
a =10;
b=20;
printf("The Sum: %d", (a+b));
}

Python:

a=10
b=20
print("The Sum:",(a+b))

The name Python was selected from the TV Show


"The Complete Monty Python's Circus", which was broadcasted in BBC from 1969 to 1974.
Guido developed Python language by taking almost all programming features from different
languages
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3
Most of syntax in Python Derived from C and ABC languages.

History of python:
Python was created in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands. The language was officially released in 1991 as
Python 0.9.0. Python's design philosophy emphasizes code readability and simplicity, which
has contributed to its widespread adoption.
Over the years, Python has evolved through multiple versions, with
 Python 2.0 released in 2000 and
 Python 3.0 in 2008.
 Python 3 introduced many improvements and is the current version being actively
developed and maintained.
Thrust Areas of Python:
We can use everywhere. The most common important application areas are

 For developing Desktop Applications


 For developing web Applications
 For developing database Applications
 For Network Programming
 For developing games
 For Data Analysis Applications
 For Machine Learning
 For developing Artificial Intelligence Applications
 For IoT
Note:
• Internally Google and YouTube use Python coding.
• NASA and Network Stock Exchange Applications developed by Python.
SOFTWARE SOLUTIONS:

• Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

Python Installation:
To download Python on your system, you can use the following steps
Step 1: Select Version to Install Python
Visit the official page for Python [Link] on the Windows operating
system. Locate a reliable version of Python 3, preferably version 3.10.11, which was used in testing
this tutorial. Choose the correct link for your device from the options provided: either Windows
installer (64-bit) or Windows installer (32-bit) and proceed to download the executable file.

Python Homepage
Step 2: Downloading the Python Installer
Once you have downloaded the installer, open the .exe file, such as [Link], by
double-clicking it to launch the Python installer. Choose the option to Install the launcher for all users
by checking the corresponding checkbox, so that all users of the computer can access the Python
launcher [Link] users to run Python from the command line by checking the Add
[Link] to PATH checkbox.

Python Installer
After Clicking the Install Now Button the setup will start installing Python on your Windows system.
You will see a window like this.

Python Setup
Step 3: Running the Executable Installer
After completing the setup. Python will be installed on your Windows system. You will see a
successful message.
Python Successfully installed
Step 4: Verify the Python Installation in Windows
Close the window after successful installation of Python. You can check if the installation of Python
was successful by using either the command line or the Integrated Development Environment
(IDLE), which you may have installed. To access the command line, click on the Start menu and type
“cmd” in the search bar. Then click on Command Prompt.
python --version

Python version
You can also check the version of Python by opening the IDLE application. Go to Start and enter
IDLE in the search bar and then click the IDLE app, for example, IDLE (Python 3.10.11 64-bit). If
you can see the Python IDLE window then you are successfully able to download and installed
Python on Windows.
Download and install Anaconda:
Open chrome and search for [Link] and install the latest version of Anaconda. Make
sure to download the “Python 3.7 Version” for the appropriate architecture.

Begin with the installation process:


 Getting Started:

 Getting through the License Agreement:


 Select Installation Type: Select Just Me if you want the software to be used by a
single User

 Choose Installation Location:


 Advanced Installation Option:

 Getting through the Installation Process:


 Recommendation to Install Pycharm:

 Finishing up the Installation:

Working with Anaconda:


Once the installation process is done, Anaconda can be used to perform multiple operations.
To begin using Anaconda, search for Anaconda Navigator from the Start Menu in Windows
Installing Jupyter Notebook on Windows
Jupyter Notebook can be installed by using either of the two ways described below:
Using Anaconda:
Install Python and Jupyter using the Anaconda Distribution, which includes Python, the
Jupyter Notebook, and other commonly used packages for scientific computing and data
science..
Using PIP:
Install Jupyter using the PIP package manager used to install and manage software
packages/libraries written in Python

Installing Jupyter Notebook using Anaconda


Anaconda is an open-source software that contains Jupyter, spyder, etc that are used for large
data processing, data analytics, heavy scientific computing. Anaconda works for R and
python programming language. Spyder(sub-application of Anaconda) is used for python.
Opencv for python will work in spyder. Package versions are managed by the package
management system called conda. To install Jupyter using Anaconda, just go through the
following instructions:
Step 1: First, Launch the Anaconda Navigator
Step 2: Click on the Install Jupyter Notebook
Button

The installation process is begin to


Start!

Loading Packages:
Finished Installation:

Step 3: Now, click on Launch button to Launch the Jupyter.


Installing Jupyter Notebook using pip
PIP is a package management system used to install and manage software packages/libraries
written in Python. These files are stored in a large “on-line repository” termed as Python
Package Index (PyPI). pip uses PyPI as the default source for packages and their
dependencies.
Step 1: To install Jupyter using pip, we need to first check if pip is updated in our system.
Use the following command to update pip:
python -m pip install --upgrade pip

Step 2: After updating the pip version, follow the instructions provided below to install
Jupyter:
Command to install Jupyter:
python -m pip install jupyter
Beginning Installation:
Downloading Files and Data:

Installing
Packages:
Finished
Installation:

Launching Jupyter:
Use the following command to launch Jupyter using command-line:
jupyter notebook
Features of Python:
1) Simple and easy to learn:
Python is a simple programming language. When we read Python program, we can feel like reading
English statements.
The syntaxes are very simple and only 30+ keywords are available.
• When compared with other languages, we can write programs with very less number of lines. Hence
more readability and simplicity.
• We can reduce development and cost of the project.

2) Freeware and Open Source:


We can use Python software without any licence and it is freeware.
Its source code is open, so that we can we can customize based on our requirement.
• Eg: python is customized version of Python to work with Java Applications.
3) High Level Programming language:
Python is high level programming language and hence it is programmer friendly language.
Being a programmer we are not required to concentrate low level activities like memory management
and security etc.
4) Platform Independent:
• Once we write a Python program, it can run on any platform without rewriting once again.
• Internally PVM(Python Virtual Machine) is responsible to convert into machine understandable
form.
5) Portability:
Python programs are portable. i.e., we can migrate from one platform to another platform very easily.
Python programs will provide same results on any platform.
6) Dynamically Typed:
In Python we are not required to declare type for variables. Whenever we are
assigning the value, based on value, type will be allocated automatically. Hence Python is considered
as dynamically typed language.
• But Java, C etc are Statically Typed Languages because we have to provide type at the beginning
only.
• This dynamic typing nature will provide more flexibility to the programmer.
7) Both Procedure Oriented and Object Oriented:
Python language supports both Procedure oriented (like C, pascal etc) and object oriented (like C++,
Java) features. Hence we can get benefits of both like security and reusability etc
8) Interpreted:
• We are not required to compile Python programs explicitly. Internally Python interpreter will take
care that compilation.
• If compilation fails interpreter raised syntax errors. Once compilation success then PVM (Python
Virtual Machine) is responsible to execute.
9) Extensible:
We can use other language programs in Python.
The main advantages of this approach are:
• We can use already existing legacy non-Python code
• We can improve performance of the application

11) Extensive Library:


Python has a rich inbuilt library.
Being a programmer we can use this library directly and we are not responsible to implement the
functionality. Etc.

Limitations of Python:
1) Performance wise not up to the mark because it is interpreted language.
2) Not using for mobile Applications.

IDENTIFIERS
A Name in Python Program is called Identifier.
It can be Class Name OR Function Name OR Module Name OR Variable Name.
Ex:a = 10
Rules to define Identifiers in Python:
1. The only allowed characters in Python are
 alphabet symbols (either lower case or upper case)
 digits (0 to 9)
 underscore symbol(_)
By mistake if we are using any other symbol like $ then we will get syntax error.
 cash = 10/
 ca$h =20 X
2. Identifier should not starts with digit
 123total X
 total123✔
3. Identifiers are case sensitive. Of course Python language is case sensitive language.
 total=10
 TOTAL=999
print(total) #10
print(TOTAL) #999
Identifier:
1) Alphabet Symbols (Either Upper case OR Lower case)
2) If Identifier is start with Underscore () then it indicates it is private.
3) Identifier should not start with Digits.
4) Identifiers are case sensitive.
5) We cannot use reserved words as identifiers
Eg: def = 10 X
6) There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.
7) Dollor ($) Symbol is not allowed in Python.
Q) Which of the following are valid Python identifiers?
1) 123total X
2) total123
3) java2share ✔
4) ca$h X
5) abc abc_
6) def X
7) if X
Note:
1) If identifier starts with _ symbol then it indicates that it is private
2) If identifier starts with _(Two Under Score Symbols) indicating that strongly private identifier.
3) If the identifier starts and ends with two underscore symbols then the identifier is language defined
special name, which is also known as magic methods.
Eg:___add_

RESERVED WORDS:
In Python some words are reserved to represent some meaning or functionality. Such types of
words are called reserved words.
Reserved words are also called as Keywords.
There are 35 reserved words available in Python.
Note:
 True, False, None
 and, or,not,is
 if, elif, else
 while, for, break, continue, return, in, yield
 try, except, finally, raise, assert
 import, from, as, class, def, pass, global, nonlocal, lambda, del, with
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 reserved words, all contain only lower case alphabet symbols.
 True
 False
 None
Eg: a= true (X)
a=True (✓)
>>> import keyword
>>> [Link]
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
Assert - In Python is a tool that evaluates the validity of a statement.
Example: x="hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, Assertion Error is raised:
assert x == "hi"
Await - await passes function control back to the event loop.

Statements and Expressions:


A statement is a unit of code that the Python interpreter can execute. There are
several types of statements in Python.
 Assignment Statements: Used to assign values to variables.
For example, x = 5.
 Conditional Statements: Used to execute code based on certain conditions.
For example, if, elif, and else.
 Loop Statements: Used to execute a block of code repeatedly.
For example, for and while loops.
 Import Statements: Used to import modules into a Python script.
For example, import math.
 Function Definition Statements: Used to define functions.
For example, def my_function():.
 Class Definition Statements: Used to define classes.
For example, class MyClass:

An Expression is a combination of values, variables, operators, and function calls that are
evaluated to produce a new value. Here are some examples of expressions in Python:
 Arithmetic Expressions: 3 + 5, 2 * (3 + 4), x - y
 Boolean Expressions: x > 10, y == 2, not is_valid
 Function Calls: sum([1, 2, 3]), len("Hello")
 List Comprehensions: [x ** 2 for x in range(10)]
Variables:
A variable is the name given to a memory location. A value-holding Python variable is
also known as an identifier.

In Python, you don't need to explicitly declare a variable's data type. The interpreter
automatically assigns a data type based on the value assigned to it.
Example:
# Creating variables
x = 10 # Integer
name = "Alice" # String
is_student = True # Boolean

Variable Naming Conventions


 Must start with a letter or underscore.
 Can contain letters, numbers, or underscores.
 Are case-sensitive (age, Age, and AGE are different).
 Should be descriptive and meaningful.

Avoid:
 Reserved keywords (e.g., if, else, for, while, etc.)
 Special characters (except underscore)

Operators:
Operators are special symbols in Python that perform operations on variables and values.
Python supports several types of operators, each serving a different purpose. Below is an
overview of the most commonly used operators.

1)Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations:
 Addition (+): Adds two values.
 Subtraction (``): Subtracts the right value from the left value.
 Multiplication (``): Multiplies two values.
 Division (/): Divides the left value by the right value.
 Modulus (%): Returns the remainder of a division.
 Exponentiation (*): Raises the left value to the power of the right value.
 Floor Division (//): Divides the left value by the right value and rounds down to the
nearest integer.

Example:

a = 10
b=3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333333333333335
print(a % b) # Output: 1
print(a ** b) # Output: 1000
print(a // b) # Output: 3
2) Comparison Operators/Relational Operators:
Comparison operators are used to compare two values and return a boolean result (True or
False):
 Equal (==): Checks if two values are equal.
 Not Equal (!=): Checks if two values are not equal.
 Greater Than (>): Checks if the left value is greater than the right value.
 Less Than (<): Checks if the left value is less than the right value.
 Greater Than or Equal (>=): Checks if the left value is greater than or equal to the
right value.
 Less Than or Equal (<=): Checks if the left value is less than or equal to the right
value.
Example:
x=5
y=8
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
print(x >= y) # Output: False
print(x <= y) # Output: True
3) Logical Operators
Logical operators are used to combine conditional statements:
 AND (and): Returns True if both statements are true.
 OR (or): Returns True if at least one statement is true.
 NOT (not): Reverses the result of a statement.
Example:

a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
4) Bitwise Operators
Bitwise operators are used to perform bit-level operations on integers:
 AND (&): Performs a bitwise AND operation.
 OR (|): Performs a bitwise OR operation.
 XOR (^): Performs a bitwise XOR operation.
 NOT (~): Performs a bitwise NOT operation.
 Left Shift (<<): Shifts bits to the left.
 Right Shift (>>): Shifts bits to the right.
Example:
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
print(x | y) # Output: 7 (Binary: 0111)
print(x ^ y) # Output: 6 (Binary: 0110)
print(~x) # Output: -6
print(x << 1) # Output: 10 (Binary: 1010)
print(x >> 1) # Output: 2 (Binary: 0010)

5) Assignment Operators
Assignment operators are used to assign values to variables:
 Equals (=): Assigns the right value to the left variable.
 Add and Assign (+=): Adds the right value to the left variable and assigns the result
to the left variable.
 Subtract and Assign (=): Subtracts the right value from the left variable and assigns
the result to the left variable.
 Multiply and Assign (=): Multiplies the right value with the left variable and assigns
the result to the left variable.
 Divide and Assign (/=): Divides the left variable by the right value and assigns the
result to the left variable.
 Modulus and Assign (%=): Takes the modulus of the left variable by the right value
and assigns the result to the left variable.
 Exponent and Assign (*=): Raises the left variable to the power of the right value
and assigns the result to the left variable.
Floor Divide and Assign (//=): Floor divides the left variable by the right value and
assigns the result to the left variable.
Example:
a=5
a += 3 # Equivalent to a = a + 3
print(a) # Output: 8
b = 10
b *= 2 # Equivalent to b = b * 2
print(b) # Output: 20

6) Identity Operators
Used to check if two variables refer to the same object in memory.

Operator Description

is Returns True if both variables refer to the same object

is not Returns True if both variables do not refer to the same object

7) Membership Operators
Used to check if a value is present in a sequence.

Operator Description

in Returns True if a value is present in a sequence

not in Returns True if a value is not present in a sequence

Precedence and Associativity:


When writing expressions in Python, it's important to understand the concepts of
operator precedence and associativity. These rules determine the order in which operations
are performed in an expression.
Operator Precedence
Operator precedence defines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before operators with lower precedence. Here
is a list of some common operators in Python, ordered from highest to lowest precedence:
1. Parentheses (()): Used to group expressions and override default precedence.
2. Exponentiation (*): Raises a number to the power of another number.
3. Unary Plus and Minus (+, ``): Unary operators that indicate positive or negative
numbers.
4. Multiplication, Division, Modulus, and Floor Division (``, /, %, //): Perform
various arithmetic operations.
5. Addition and Subtraction (+, ``): Perform basic arithmetic operations.
6. Bitwise Shift Operators (<<, >>): Shift bits to the left or right.
7. Bitwise AND (&): Performs a bitwise AND operation.
8. Bitwise XOR (^): Performs a bitwise XOR operation.
9. Bitwise OR (|): Performs a bitwise OR operation.
10. Comparison Operators (==, !=, >, <, >=, <=): Compare values and return boolean
results.
11. Logical NOT (not): Reverses the result of a boolean expression.
12. Logical AND (and): Returns True if both conditions are true.
13. Logical OR (or): Returns True if at least one condition is true.
14. Assignment Operators (=, +=, =, =, /=, %=, *=, //=, &=, |=, ^=, >>=, <<=): Assign
values to variables.

Operator Associativity:
When operators of the same precedence appear in an expression, operator associativity
determines the order in which they are evaluated. Associativity can be either left-to-right or
right-to-left.
 Left-to-Right Associativity: Operators are evaluated from left to right. Most
arithmetic and bitwise operators follow this rule.
Example:
a = 10 - 3 + 2 # Equivalent to (10 - 3) + 2
print(a) # Output: 9
 Right-to-Left Associativity: Operators are evaluated from right to left.
Exponentiation and assignment operators follow this rule.
Example:
b = 2 ** 3 ** 2 # Equivalent to 2 ** (3 ** 2)
print(b) # Output: 512

DATA TYPES:
Data Type represents the type of data present inside a variable.
In Python we are not required to specify the type explicitly. Based on value
provided, the type will be assigned automatically. Hence Python is dynamically
Typed Language.
Python contains the following inbuilt data types
1) Int
2) Float
3) Complex
4) Bool
5) Str
6) Bytes
7) Bytearray
Note: Python contains several inbuilt functions
1) type(): to check the type of variable
2) id(): to get address of object
3) print(): to print the value
In Python everything is an Object.
1) int Data Type:
We can use int data type to represent whole numbers (integral values)
Eg: a = 10
type(a) #int
Note:
 In Python2 we have long data type to represent very large integral values.
 But in Python3 there is no long type explicitly and we can represent long values also
by using int type only.
We can represent int values in the following ways
1) Decimal form
2) Binary form
3) Octal form
4) Hexa decimal form
Decimal Form (Base-10):
 It is the default number system in Python
 The allowed digits are: 0 to 9
Eg: a=10
Binary Form (Base-2):
 The allowed digits are: 0 & 1
 Literal value should be prefixed with Ob or OB
Eg: a=0B1111
a = OB123
a=b111
Octal Form (Base-8):
 The allowed digits are: 0 to 7
 Literal value should be prefixed with 00 or 00.

Eg: a = 00123
a = 00786
Hexa Decimal Form (Base-16):
 The allowed digits are: 0 to 9, a-f (both lower and upper cases are allowed)
 Literal value should be prefixed with Ox or OX
Eg: a = OXFACE
a = OXBeef
a = OXBeer
Note: Being a programmer we can specify literal values in decimal, binary, octal and hexa
decimal forms. But PVM will always provide values only in decimal form.
a=10
b=0010
C=0X10
d=0B10
print(a)#10
print(b)#8
print(c)#16
print(d)#2
Base Conversions
Python provide the following in-built functions for base conversions
1) bin(): We can use bin() to convert from any base to binary
>>> bin(15)
'0b1111'
2) oct(): We can use oct() to convert from any base to octal
>>> oct(10)
'0012'
>>> oct(0B1111)
'0017'
>>> oct(0x123)
'00443'
3) hex(): We can use hex() to convert from any base to hexa decimal
>>> hex(100)
'Ox64"
>>> hex(0B111111)
'Ox3f'
2) Float Data Type: We can use float data type to represent floating point values (decimal
values)
Eg: f = 1.234
type(f) #float
We can also represent floating point values by using exponential form (Scientific Notation)
Eg: f= 1.2e3 instead of 'e' we can use 'E'
print(f) 1200.0
The main advantage of exponential form is we can represent big values in less memory.
Note:
We can represent int values in decimal, binary, octal and hexa decimal forms. But we can
represent float values only by using decimal form.
3) Complex Data Type:
• A complex number is of the form
a+bj

Real Part Imaginary Part


'a' and 'b' contain Integers OR Floating Point Values.
Eg: 3+5j
10 +5.5j
0.5 +0.1j
In the real part if we use int value then we can specify that either by decimal, octal, binary or
hexa decimal form.
Even we can perform operations on complex type values.
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c)
(30+4j)
>>> type(c)
<class 'complex'>
We can use complex type generally in scientific Applications and electrical engineering
Applications.

4) bool Data Type:


We can use this data type to represent boolean values.
The only allowed values for this data type are:
True and False
Internally Python represents True as 1 and False as 0
b = True
type(b) #bool
Eg: a = 10
b = 20
c=a<b
print(c) #True

5) str Data Type:


str represents String data type.
A String is a sequence of characters enclosed within single quotes or double quotes.
s1='durga'
s1="durga"
By using single quotes or double quotes we cannot represent multi line string literals.
s1="durga"
For this requirement we should go for triple single quotes(''') or triple double quotes(""")
s='''durga'''
We can also use triple quotes to use single quote or double quote in our String.
"This is" character""
*This i" Character'
We can embed one string in another string
"""This "Python class very helpful" for java students""

Slicing of Strings:
 slice means a piece
 [] operator is called slice operator, which can be used to retrieve parts of String. 3) In
Python Strings follows zero based index.
 The index can be either +ve or -ve.
 +ve index means forward direction from Left to Right
 -ve index means backward direction from Right to Left
-5 -4 -3 -2 -1
d u r g a
0 1 2 3 4

>>>s="durga"
>>> s[0]
'd'
>>> s[-1]
'a'
>>> s[1:4]
'urga'
>>> s[1:]
'urga'
>>> s[:]
'durga'
>>> s*3
'durgadurgadurga'
>>> len(s)
5
Note:
1) In Python the following data types are considered as Fundamental Data types
 int
 float
 complex
 bool
 str
2) In Python, we can represent char values also by using str type and explicitly char type is
not available.
>>> c='a'
>>> type(c)
<class 'str'>
 long Data Type is available in Python2 but not in Python3. In Python3 long values
also we can represent by using int type only.
 In Python we can present char Value also by using str Type and explicitly char Type is
not available.

Indentation:
Indentation is a crucial aspect of Python syntax. Unlike many other programming
languages that use braces {} to define code blocks, Python relies on indentation to indicate
the structure of your code.
Working of Indentation:
 Consistent Spacing: All statements within a code block must have the same
indentation level.
 Four Spaces: While you can use any number of spaces for indentation, it's highly
recommended to use four spaces for consistency and readability.
 Tabs: Avoid using tabs for indentation as they can lead to inconsistencies and errors.
 Code Blocks: Indentation is used to define code blocks like loops, conditional
statements, functions, and classes.
Example:
X=5
if x > 0:
print("x is positive")
else:
print("x is non-positive")
In this example, the print statements are indented to show that they belong to the respective if
and else blocks.
Importance of Indentation
 Readability: Proper indentation makes your code easier to understand and follow.
 Structure: It clearly defines the logical flow of your program.
 Errors: Incorrect indentation will lead to IndentationError exceptions.
Common Indentation Errors
 Inconsistent indentation: Using different numbers of spaces within a code block.
 Missing indentation: Forgetting to indent code blocks.
 Extra indentation: Indenting code that should be at the same level as the previous
line.

Comments in Python:
Comments are an essential part of writing clear and understandable code. They help explain
the purpose of code blocks and provide context for others (or yourself) who may read the
code in the future.
Types of Comments:
1. Single-line Comments: Use the hash symbol (#) to create a single-line comment.
Everything after the # on that line will be ignored by the Python interpreter.
Example:
# This is a single-line comment
x = 5 # This is an inline comment

2. Multi-line Comments: While Python doesn't have a specific syntax for multi-line
comments, you can achieve this by using multiple single-line comments or by using
triple-quoted strings (''' or """). Note that triple-quoted strings are actually multi-line
strings, but can be used as comments if not assigned to a variable.
Example:
# This is a multi-line comment
# using multiple single-line comments

"""
This is a multi-line comment
using a triple-quoted string.
"""

'''
Another multi-line comment
using single quotes.
'''
Reading Input in Python:

Reading input in Python can be done using the input() function. This function reads a
line of input from the user and returns it as a string. Here are some examples and common
use cases:

Basic Input
The simplest use of input() is to read a string from the user.
name = input("Enter your name: ")
print(f"Hello, {name}!")

Reading Numeric Input


Since input() returns a string, you need to convert the input to the desired type (e.g., int, float).

age = input("Enter your age: ")


age = int(age) # Convert the input to an integer
print(f"You are {age} years old.")

# Or directly convert in one line


age = int(input("Enter your age: "))
print(f"You are {age} years old.")

Handling Multiple Inputs


You can read multiple inputs on a single line by splitting the input string.

# Reading two space-separated numbers


num1, num2 = input("Enter two numbers separated by a
space: ").split()
num1 = int(num1)
num2 = int(num2)
print(f"The sum is: {num1 + num2}")
# Reading a list of numbers
numbers = input("Enter numbers separated by spaces:
").split()
numbers = [int(num) for num in numbers]
print(f"The sum is: {sum(numbers)}")
Using a Loop for Continuous Input
You can use a loop to continuously read input until a certain condition is met.

while True:
data = input("Enter something (or type 'exit' to quit): ")
if [Link]() == 'exit':
break
print(f"You entered: {data}")

print output:
Printing output in Python can be done using the print() function. This function writes
the specified message to the console or another standard output device.
Examples: Basic Usage
print("Hello, world!") # Prints a string
print(42) # Prints an integer
print(3.14) # Prints a float
Formatted output with calculations
import math
pi = [Link]
radius = 5
print(f" The area of a circle with radius {radius} is {pi * radius ** 2:.2f}")
Output:
The area of a circle with radius 5 is 78.54

TYPE CASTING:
We can convert one type value to another type. This conversion is called Typecasting or Type
conversion.
The following are various inbuilt functions for type casting.
1) int()
2) float()
3) complex()
4) bool()
5) str()

1)int(): We can use this function to convert values from other types to int
>>> int(123.987)
123
>>> int(10+5j)
TypeError: can't convert complex to int
>>> int(True)
1
>>> int(False)
0
11) >>> int("10.5")
ValueError: invalid literal for int() with base 10: '10.5' 13) >>> int("ten")
 We can convert from any type to int except complex type.
 If we want to convert str type to int type, compulsory str should contain only integral
value and should be specified in base-10.
2) float(): We can use float() function to convert other type values to float type.
>>> float(10)
10.0
>>> float(10+5j)
TypeError: can't convert complex to float
>>> float(True)
1.0
>>> float(False)
0.0
>>> float("10")
Note: ValueError: could not convert string to float: 'ten'
>>> float("10.5")
10.5

 We can convert any type value to float type except complex type.
 Whenever we are trying to convert str type to float type compulsary str should be
either integral or floating point literal and should be specified only in base-10.
3) complex():
We can use complex() function to convert other types to complex type.
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.
Eg:
complex(10)==>10+0j
complex(10.5)===>10.5+0j
complex(True)==>1+0j
complex(False)==>0j
complex("10")==>10+0j
complex("10.5")==>10.5+0j
complex("ten")
ValueError: complex() arg is a malformed string.

complex(x,y): We can use this method to convert x and y into complex number such that x
will be real part and y will be imaginary part.
Eg: complex(10,-2)→ 10-2j
complex(True, False) → 1+0j
 Python supports two types of type conversion, they are:
1. Implicit Type Conversion
 Automatic conversion by the Python interpreter.
 Primarily occurs with numeric types (int, float).
 Python tries to preserve data integrity.
Example:

num_int = 10
num_float = 20.5
# Implicit conversion to float
result = num_int + num_float
print(result) # Output: 30.5

2. Explicit Type Conversion (Type Casting)


 Manual conversion using built-in functions.
 Functions like int(), float(), str(), bool(), etc. are used.
 Potential for data loss if the conversion is not possible.
Example:

num_str = "10"
num_int = int(num_str)
print(num_int) # Output: 10
# Converting float to int might lose decimal part
num_float = 3.14
num_int = int(num_float)
print(num_int) # Output: 3

Common Type Conversion Functions:

Function Converts
to

int() Integer

float() Float

str() String

bool() Boolean

Important Notes:
 Not all data types can be converted to each other.
 Trying to convert incompatible types will raise a TypeError.
 Be cautious when converting numeric values to strings, as precision might be lost.
 When converting strings to numbers, the string must represent a valid number.
Example of TypeError:
text = "hello"
num = int(text) # Raises a TypeError

type() Function in Python:


The type() function in Python is used to determine the type of an object. This
function returns the type of the object passed as an argument.
To use the type() function, simply pass the object you want to check as an argument.
Example: # Check the type of an integer
print(type(10)) # Output: <class 'int'>
# Check the type of a string
print(type("Hello")) # Output: <class 'str'>
# Check the type of a list
print(type([1, 2, 3])) # Output: <class 'list'>

Using type() with Custom Classes


The type() function can also be used to check the type of instances of custom classes.
Example:
class MyClass:
pass

obj = MyClass()
print(type(obj)) # Output: <class '__main__.MyClass'>

is Operator:
 It is Used for identity comparison.
 It Checks if two variables refer to the same object in memory.
 It Uses the is keyword.

x = [1, 2, 3]
y=x
z = [1, 2, 3]
print(x is y) # Output: True
print(x is z) # Output: False

Dynamic and Strong Typing in Python


Python is both dynamically typed and strongly typed. Understanding these concepts is crucial
for writing effective Python code.

Dynamic Typing
In a dynamically typed language, the type of a variable is determined at runtime, not in
advance. This means you don't need to declare a variable's type before using it.
Example:

# Assign an integer to a variable


x = 10
print(type(x)) # Output: <class 'int'>

# Reassign a string to the same variable


x = "Hello"
print(type(x)) # Output: <class 'str'>

In the example above, the variable x is first assigned an integer value, and later it is
reassigned a string value. Python determines the type of x at runtime based on the value it
holds.

Strong Typing
In a strongly typed language, once a variable has a type, operations that are not appropriate
for that type are not allowed. Python does not implicitly convert types to make operations
work.
Example:
# Attempting to add a string to an integer will raise a TypeError
x = 10
y = "5"
print(x + y) # Raises TypeError: unsupported operand type(s) for +:
'int' and 'str'

In the example above, Python does not implicitly convert the string "5" to an integer before
adding it to x. Instead, it raises a TypeError because adding an integer and a string is not
allowed.
Example:
# Assign an integer to a variable
x = 10
print(type(x)) # Output: <class 'int'>
# Reassign a string to the same variable
x = "Hello"
print(type(x)) # Output: <class 'str'>

Control Flow Statements:


Control Flow Statements in Python are fundamental building blocks that dictate the
execution order of a program. They enable developers to create logical pathways and make
decisions in their code, using structures like if, for, and while.

Importance of Control Statements:


1. Control statements like if, elif, and else allow programs to execute different code
blocks based on certain conditions.
2. Loops, including for and while, enables the execution of a code block multiple times.
3. By using control flow statements, programmers can write cleaner, more organized
code.
4. Control flow in Python allows for creating efficient algorithms that can make
decisions and repeat tasks without human intervention.

Conditional statements:
1)If Statement:
The if statement is used to test a condition. If the condition evaluates to True, the
block of code inside the if statement is executed.
Example:
x = 10
if x > 5:
print("x is greater than 5")

2)If-else statement:
The if-else statement provides an alternative block of code to execute if the condition
is false.
Example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

3) Elif statement:
The if-elif-else statement allows you to check multiple conditions. The first block
whose condition is true will be executed.
Example:
x=7
if x > 10:
4)Nested If statement:
The nested-if statement in Python is a control flow structure that allows you to check
multiple conditions sequentially, within other if statements.

Example: x = 15

if x > 10:

print("x is greater than 10")

if x > 20:

print("x is also greater than 20")

else:

print("x is 10 to 20")

else:

print("x is 10 or less")

Looping statements:
In coding, loops are designed to execute a specified code block repeatedly

1)while loop:
The Python while loop iteration of a code block is executed as long as the given
Condition, i.e., conditional_expression, is true.

Example:
i=1
while i<=10:
print(i, end=' ')
i+=1
Output: 1 2 3 4 5 6 7 8 9 10
2) For Loop:
For loops in Python is designed to repeatedly execute the code block while iterating
over a sequence or an iterable object such as list, tuple, dictionary, sets.

Example: To print first 10 natural numbers


n=11

for i in range(1,n):

print(i)

Output: 1 2 3 4 5 6 7 8 9 10

Jumping statements:
1)break:
The break statement in Python is used to exit a loop prematurely. It can be used in both for
and while loops. When the break statement is encountered inside a loop, the loop is immediately
terminated, and the program control is transferred to the statement following the loop.

Example: In below code, the loop terminates when the value of i is equal to 3:

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

Output:
0
1
2
2) Continue :
Python continue keyword is used to skip the remaining statements of the current loop
and go to the next iteration.

Example:
for i in range(5):
if i == 3:
continue
print(i)

Output: 0
1
2
4
Catching Exceptions Using try and except Statement:
Catching exceptions in Python is done using the try and except statements. This
mechanism allows you to handle errors gracefully, preventing your program from crashing
when an error occurs. Here's a detailed explanation and some examples of how to use try and
except.
Basic Syntax:
The basic syntax of a try and except block is as follows:
try:
# Code that may raise an exception
risky_code()
except SomeException:
# Code that runs if the exception occurs
handle_exception()
Example: Handling a Division by Zero Error

try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
1. Write a program to define a function with multiple return values.
Code:
def calculate(a, b):
# Perform some calculations
sum_result = a + b
difference = a - b
product = a * b
quotient = a / b if b != 0 else None # Handle division by zero

# Return multiple values


return sum_result, difference, product, quotient
a=int(input("enter a number:"))
b=int(input("Enter a Number:"))
# Call the function and store the results
result_sum, result_difference, result_product, result_quotient =
calculate(a, b)
# Print the results
print("Sum:", result_sum)
print("Difference:", result_difference)
print("Product:", result_product)
print("Quotient:", result_quotient)

Output:

1
2. Write a program to define a function using default arguments

Code:
# creatin a Function to display student information with
default values for grade and age
def display_student_info(name, grade="A", age=18):
print(f"Name: {name}")
print(f"Grade: {grade}")
print(f"Age: {age}")

# Calling the function with and without default arguments


display_student_info("Raj") # Uses default values for
grade and age
print()
display_student_info("Ram", "B", 20) # Overwrites default values

Output:

2
3. Write a program to find the length of the string without using any
library functions.
Code:
# Function to find the length of a string without using library
functions
def string(input_string):
length = 0
for char in input_string:
length += 1
return length

# Input string
my_string = "Hello, students!"

# Find the length of the string


length_of_string = string(my_string)

# Output the result


print(f"The length of the string is: {length_of_string}")

Output:

3
4. Write a program to check if the substring is present in a given string or
not
Code:

def substring(main_string, sub_string):


if sub_string in main_string:
return True
else:
return False
# Example usage
main_string = "Hello, students! Welcome to python class.."
sub_string = "python"
result = substring(main_string, sub_string)
if result:
print(f"'{sub_string}' is present in '{main_string}'")

else:
print(f"'{sub_string}' is not present in '{main_string}'")

Output:

4
5. Write a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
Code:
# List operations: addition, insertion, and slicing
# Creating a list with 5 elements
my_list = [1, 2, 3, 4, 5]
# i. Addition - Adding an element to the list using append()
my_list.append(6)
print("After Addition:", my_list)
# ii. Insertion - Inserting an element at a specific index using insert()

my_list.insert(2, 10) # Inserting 10 at index 2


print("After Insertion:", my_list)
# iii. Slicing - Extracting a portion of the list
sliced_list = my_list[1:4] # Extract elements from index 1 to 3
print("Sliced List:", sliced_list)

Output:

5
6. Write a program to perform any 5 built-in functions by taking
any list.
Code:
# Creating a simple list with 6 elements
my_list = [10, 20, 30, 40, 50, 60]
# 1. append() - Adds an element to the end of the list
my_list.append(70)
print("After append(70):", my_list)
# 2. extend() - Extends the list by appending elements at
the end of the list
my_list.extend([80, 90])
print("After extend([80, 90]):", my_list)
# 3. insert() - Inserts an element at a specified index
my_list.insert(2, 25) # Inserting 25 at index 2
print("After insert(2, 25):", my_list)
# 4. remove() - Removes the first occurrence of a specified
value
my_list.remove(40)
print("After remove(40):", my_list)
# 5. pop() - Removes and returns the element at the
specified position (last element if no index is provided)
remove_element = my_list.pop() # Removes the last
element
print("After pop():", my_list)
print("Removed Element:", remove_element)
Output:

6
Unit-3 Programs
1. Write a program to create tuples (name, age, address, college) for at
least two members and concatenate the tuples and print the
concatenated tuples.

Code:
#creatin a tuple to fetch student details with tuples concept
student1=("rani",19,"etukuru","MLEW")
student2=("sita",20,"Guntur","KHITS")
#concatenating the above two tuples
details= student1 + student2
#now printing the concatenated tupe named details
print("the tuple after concatenation is:")
print(details)

OUTPUT:

1
2. Write a program to count the number of vowels in a string
(No control flow allowed)
Code:
# Input string
input_string = "This is a sample string with vowels."
# Use a lambda function with filter() to count vowels
vowels = "aeiouAEIOU"
count_vowels = len(list(filter(lambda char: char in vowels, input_string)))

# Print the result


print("Number of vowels in the string:", count_vowels)
filter(): This function filters elements from a sequence based on a condition. It
takes two arguments: a function (or lambda in this case) and the sequence to
filter.
lambda char: char in vowels: The lambda function checks if each character
(char) from the input_string is present in the vowels string. The lambda
expression returns True if the character is a vowel, and False otherwise.
Result of filter(): The filter() function returns an iterator containing only the
characters from the input_string that are vowels.
list(): The filter() iterator is converted to a list. This list will contain only the
vowels from the input_string.
len(): The length of this list (i.e., the number of vowels) is then calculated using
the len() function and stored in the variable count_vowels

OUTPUT:

2
3. Write a program to check if a given key exists in a dictionary or
not.

Code:
# Define a dictionary
mydict = {
"name": "shreshta",
"age": 22,
"city": "Guntur",
"college": "MLEW"
}
# Input: key to be checked
key = "name" # You can change this key to test
# Check if the key exists in the dictionary
if key in mydict:
print(f"Key '{key}' exists in the dictionary.")
else:
print(f"Key '{key}' does not exist in the dictionary.")

OUTPUT:

3
4. Write a program to add a new key-value pair to an
existing dictionary.

Code:
# creating a dictionary with key and value pair
sample_dict = {
"name": "shreshta",
"age": 22,
"city": "Guntur"
}
# New key-value pair to add
key = "college"
value = "MLEW"

# Add the new key-value pair to the dictionary


sample_dict[key] = value

# Print the updated dictionary


print("Updated Dictionary:")
print(sample_dict)

OUTPUT:

4
5. Write a program to sum all the items in a given
dictionary.

Code:
#creating a dictionary with numerical values
dict = {
1: 15,
2: 30,
3: 95,
4: 10
}

# Sum all the values in the dictionary


sums = sum([Link]())
sum1=sum([Link]())
# Print the result
print("The sum of all items in the dictionary is:", sums)
print("The sum of all keys in the dictionary is:", sum1)

OUTPUT:

5
UNIT-4 PROGRAMS
1. Write a program to sort words in a file and put them in another file. The output file should
have only lower-case words, so any upper-case words from source must be lowered.
AIM: To write a program [Link] sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper-case words from source must be lowered.
Program:
def sort_words_in_file(input_file, output_file):
try:
with open(input_file, 'r') as file:
words = [Link]().split()
lower_case_words = [[Link]() for word in words]
sorted_words = sorted(set(lower_case_words)) # Use set to avoid duplicates
with open(output_file, 'w') as file:
for word in sorted_words:
[Link](f"{word}\n")
print(f"Sorted words have been written to '{output_file}'.")
except FileNotFoundError:
print(f"The file '{input_file}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
input_file_name = '[Link]' # Source file with words
output_file_name = '[Link]' # Destination file for sorted words
sort_words_in_file(input_file_name, output_file_name)

[Link]:
shreshta
python lab
Skill Enhancement Course

[Link]:
course
enhancement
lab
python
shreshta
skill

Output:
2. Write a Python program to print each line of a file in reverse order.
AIM: To Write a python program to print each line of a file in reverse order.
Program:

with open("[Link]", "r") as file:


lines = [Link]()

for line in lines:


print([Link]()[::-1])
# Reverse the line and remove newline characters

[Link]:
Python is Fun
Learning to Code in Python
HELLO world
3. Write a Python program to compute the number of characters, words and lines in a file
AIM: To write a Python program to compute the number of characters, words and lines in a
file
Program:
with open("[Link]", "r") as file:
lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)
print(f"Lines: {num_lines}, Words: {num_words}, Characters:{num_chars}")

[Link]:
Python is Fun
Learning to Code in Python
HELLO world

OUTPUT:
4. Write a program to create, display, append, insert and reverse the order of the items
in the array.
AIM: To write a program to create, display, append, insert and reverse the order of the items
in the array.
Program:
from array import array
# Create an array of integers
arr = array('i', [1, 2, 3, 4, 5])
# Display array
print("Original array:", arr)
# Append a new item
[Link](6)
print("After appending:", arr)
# Insert an item at a specific position
[Link](2, 10)
print("After insertion:", arr)
# Reverse the array
[Link]()
print("Reversed array:", arr)

Output:
5. Write a program to add, transpose and multiply two matrices.
AIM: To write a program to add, transpose and multiply two matrices.
Program:
import numpy as np
# Create two matrices
A = [Link]([[1, 2], [3, 4]])
B = [Link]([[5, 6], [7, 8]])
# Add matrices
C=A+B
print("Addition:\n", C)
# Transpose a matrix
AT = A.T
print("Transpose of A:\n", AT)
# Multiply matrices
D = [Link](A, B)
print("Multiplication:\n", D)

Output:
6. Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
AIM: To write a Python program to create a class that represents a shape. Include methods
to calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
Program:
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2
def perimeter(self):
return 2 * 3.14 * [Link]
class Square(Shape):
def __init__(self, side):
[Link] = side
def area(self):
return [Link] ** 2
def perimeter(self):
return 4 * [Link]
# Example usage
circle = Circle(5)
square = Square(4)
print("Circle Area:", [Link]())
print("Circle Perimeter:", [Link]())
print("Square Area:", [Link]())
print("Square Perimeter:", [Link]())

OUTPUT:
UNIT-5
1) Write a python program to check whether a JSON string contains complex object or
not
AIM: To write a python program to check whether a JSON string contains complex object
or not
Program:
import json
def contains_complex_object(data):
if isinstance(data, dict):
for value in [Link]():
if isinstance(value, (dict, list)):
return True or contains_complex_object(value)
elif isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
return True or contains_complex_object(item)
return False
# Example JSON strings
json_str1 = '{"name": "Alice", "age": 25, "city": "New York"}'
json_str2 = '{"name": "Alice", "address": {"city": "New York", "zip": 12345}}'
# Convert to Python objects
data1 = [Link](json_str1)
data2 = [Link](json_str2)
# Check for complex objects
print("JSON 1 contains complex object:", contains_complex_object(data1))
print("JSON 2 contains complex object:", contains_complex_object(data2))

OUTPUT:
2) Write a Python Program to demonstrate NumPy arrays creation using array ()
function
AIM: To Write a Python Program to demonstrate NumPy arrays creation using array
() function
Program:
# Importing the NumPy library
import numpy as np
# Creating a 1D array
arr1 = [Link]([10, 20, 30, 40, 50])
print("1D Array:")
print(arr1)
# Creating a 2D array
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(arr2)
# Creating an array from a tuple
arr3 = [Link]((7, 8, 9, 10))
print("\nArray from Tuple:")
print(arr3)
# Creating an array with mixed data types
arr4 = [Link]([1, 2.5, 3, 4.7])
print("\nArray with Mixed Data Types:")
print(arr4)
# Displaying array data type and dimension
print("\nArray Properties:")
print("Type of arr1:", type(arr1))
print("Data Type of arr1 elements:", [Link])
print("Dimensions of arr2:", [Link])
print("Shape of arr2:", [Link])
OUTPUT:
3) Write a Python program to demonstrate use of ndim, shape, size, dtype.
4) AIM: To W Write a Python program to demonstrate use of ndim, shape, size,
dtype.
Program:
import numpy as np
# Create a NumPy array
arr = [Link]([[10, 20, 30], [40, 50, 60]])
# Display the array
print("Array:\n", arr)
# Number of dimensions (ndim)
print("\nNumber of dimensions (ndim):", [Link])
# Shape of the array (shape)
print("Shape of the array (shape):", [Link])
# Total number of elements (size)
print("Total number of elements (size):", [Link])
# Data type of each element (dtype)
print("Data type of elements (dtype):", [Link])

OUTPUT:
4)Write Python program to demonstrate basic slicing, integer and Boolean indexing.

AIM: To write a Python program to demonstrate basic slicing, integer and Boolean indexing

Program:

import numpy as np

# Create a sample NumPy array

arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80])

print("Original Array:")

print(arr)

# Basic Slicing

print("\n1. Basic Slicing:")

print("Elements from index 2 to 5:", arr[2:6])

print("Every second element:", arr[::2])

print("Reversed array:", arr[::-1])

# Integer Indexing

print("\n2. Integer Indexing:")

indices = [0, 3, 5]

print("Elements at indices 0, 3, and 5:", arr[indices])

# Boolean Indexing

print("\n3. Boolean Indexing:")

bool_mask = arr > 40

print("Boolean mask (arr > 40):", bool_mask)

print("Elements greater than 40:", arr[bool_mask])

OUTPUT:
5) Write a Python program to find min, max, sum, cumulative sum of array
AIM: To write a Python program to find min, max, sum, cumulative sum of array
Program:
import numpy as np
# Create a NumPy array
arr = [Link]([10, 20, 30, 40, 50])
print("Original Array:")
print(arr)
# Find minimum element
min_value = [Link](arr)
print("\nMinimum value:", min_value)
# Find maximum element
max_value = [Link](arr)
print("Maximum value:", max_value)
# Find sum of all elements
sum_value = [Link](arr)
print("Sum of all elements:", sum_value)
# Find cumulative sum of elements
cumsum_value = [Link](arr)
print("Cumulative sum of elements:", cumsum_value)

OUTPUT:
6) Write a python program to Create a dictionary with at least five keys and each key
represent value as a list where this list contains at least ten values and convert
this dictionary as a pandas data frame and explore the data through the data
frame as follows:
a) Apply head() function to the pandas data frame
b) Perform various data selection operations on Data Frame
AIM: To create a dictionary with at least five keys where each key represents a list
containing ten values, convert this dictionary into a Pandas DataFrame, and explore
the data by applying the head() function and performing various data selection
operations using Pandas.
Program:
import pandas as pd
# Step 1: Create a dictionary with 5 keys and 10 values in each list
student_data = {
'Student_ID': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
'Name': ['Arun', 'Bhavya', 'Chitra', 'Dinesh', 'Esha', 'Farhan', 'Gita', 'Hari', 'Indu',
'Jatin'],
'Age': [18, 19, 20, 21, 18, 22, 19, 20, 21, 22],
'Marks': [85, 78, 92, 66, 80, 75, 89, 90, 70, 88],
'City': ['Hyderabad', 'Chennai', 'Bangalore', 'Delhi', 'Mumbai', 'Pune', 'Kolkata',
'Chennai', 'Delhi', 'Hyderabad']
}
# Step 2: Convert dictionary to DataFrame
df = [Link](student_data)
print("Original DataFrame:")
print(df)
# Step 3: Apply head() function
print("\nFirst 5 rows using head():")
print([Link]())
# Step 4: Perform various data selection operations
# a) Selecting a single column
print("\nSelect 'Name' column:")
print(df['Name'])
# b) Selecting multiple columns
print("\nSelect 'Name' and 'Marks' columns:")
print(df[['Name', 'Marks']])
# c) Selecting specific rows using slicing
print("\nSelect rows from index 2 to 6:")
print(df[2:7])
# d) Selecting specific data using loc (label-based)
print("\nMarks of Student_ID 104:")
print([Link][3, 'Marks'])
# e) Selecting specific data using iloc (index-based)
print("\nCity of 6th student (index 5):")
print([Link][5, 4])
# f) Conditional selection (students with marks greater than 80)
print("\nStudents with Marks > 80:")
print(df[df['Marks'] > 80])
# g) Selecting rows and columns together
print("\nSelect 'Name' and 'City' of students with Age > 20:")
print([Link][df['Age'] > 20, ['Name', 'City']])

OUTPUT:

Original DataFrame:
Student_ID Name Age Marks City
0 101 Arun 18 85 Hyderabad
1 102 Bhavya 19 78 Chennai
2 103 Chitra 20 92 Bangalore
3 104 Dinesh 21 66 Delhi
4 105 Esha 18 80 Mumbai
5 106 Farhan 22 75 Pune
6 107 Gita 19 89 Kolkata
7 108 Hari 20 90 Chennai
8 109 Indu 21 70 Delhi
9 110 Jatin 22 88 Hyderabad

First 5 rows using head():


Student_ID Name Age Marks City
0 101 Arun 18 85 Hyderabad
1 102 Bhavya 19 78 Chennai
2 103 Chitra 20 92 Bangalore
3 104 Dinesh 21 66 Delhi
4 105 Esha 18 80 Mumbai

Select 'Name' column:


0 Arun
1 Bhavya
2 Chitra
3 Dinesh
4 Esha
5 Farhan
6 Gita
7 Hari
8 Indu
9 Jatin
Name: Name, dtype: object

Select 'Name' and 'Marks' columns:


Name Marks
0 Arun 85
1 Bhavya 78
2 Chitra 92
3 Dinesh 66
4 Esha 80
5 Farhan 75
6 Gita 89
7 Hari 90
8 Indu 70
9 Jatin 88

Select rows from index 2 to 6:


Student_ID Name Age Marks City
2 103 Chitra 20 92 Bangalore
3 104 Dinesh 21 66 Delhi
4 105 Esha 18 80 Mumbai
5 106 Farhan 22 75 Pune
6 107 Gita 19 89 Kolkata

Marks of Student_ID 104:


66

City of 6th student (index 5):


Pune

Students with Marks > 80:


Student_ID Name Age Marks City
0 101 Arun 18 85 Hyderabad
2 103 Chitra 20 92 Bangalore
6 107 Gita 19 89 Kolkata
7 108 Hari 20 90 Chennai
9 110 Jatin 22 88 Hyderabad

Select 'Name' and 'City' of students with Age > 20:


Name City
3 Dinesh Delhi
5 Farhan Pune
8 Indu Delhi
9 Jatin Hyderabad
[Link] a python program to Select any two columns from the above data frame, and observe the
change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib
AIM: To write a python program to observe the change in one attribute with respect to other
attribute with scatter and plot operations in matplotlib.
Program:
import pandas as pd
import [Link] as plt

# Step 1: Create a dictionary with 5 keys and 10 values in each list


student_data = {
'Student_ID': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
'Name': ['Arun', 'Bhavya', 'Chitra', 'Dinesh', 'Esha', 'Farhan', 'Gita', 'Hari', 'Indu', 'Jatin'],
'Age': [18, 19, 20, 21, 18, 22, 19, 20, 21, 22],
'Marks': [85, 78, 92, 66, 80, 75, 89, 90, 70, 88],
'City': ['Hyderabad', 'Chennai', 'Bangalore', 'Delhi', 'Mumbai', 'Pune', 'Kolkata', 'Chennai', 'Delhi',
'Hyderabad']
}

# Step 2: Convert dictionary to DataFrame


df = [Link](student_data)

# Display the DataFrame


print("Data Frame:")
print(df)

# Step 3: Select two columns: Age and Marks


x = df['Age']
y = df['Marks']

# Step 4: Scatter plot - to observe relation between Age and Marks


[Link](x, y, color='blue', marker='o')
[Link]('Scatter Plot - Age vs Marks')
[Link]('Age')
[Link]('Marks')
[Link](True)
[Link]()

# Step 5: Line plot - to observe trend between Age and Marks


[Link](x, y, color='green', marker='o')
[Link]('Line Plot - Age vs Marks')
[Link]('Age')
[Link]('Marks')
[Link](True)
[Link]()

OUTPUT:

You might also like