Python Notes - SEC
Python Notes - SEC
C:
#include<stdio.h>
void main()
{
print("Hello world");
}
Python:
print("Hello World")
Python:
a=10
b=20
print("The Sum:",(a+b))
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
• 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.
Loading Packages:
Finished Installation:
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.
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.
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
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 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
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
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}!")
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
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
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
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 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:
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'>
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:
if x > 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.
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
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}")
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!"
Output:
3
4. Write a program to check if the substring is present in a given string or
not
Code:
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()
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)))
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"
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
}
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:
[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
print("Original Array:")
print(arr)
# Basic Slicing
# Integer Indexing
indices = [0, 3, 5]
# Boolean Indexing
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
OUTPUT: