0% found this document useful (0 votes)
7 views44 pages

python all units

The document provides an overview of Python programming, highlighting its characteristics, advantages, and syntax. It discusses Python's ease of learning, readability, and versatility, as well as its support for various programming paradigms and data types. Additionally, it covers Python's operators, variable types, and examples of code execution.

Uploaded by

Pakiza Bano
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)
7 views44 pages

python all units

The document provides an overview of Python programming, highlighting its characteristics, advantages, and syntax. It discusses Python's ease of learning, readability, and versatility, as well as its support for various programming paradigms and data types. Additionally, it covers Python's operators, variable types, and examples of code execution.

Uploaded by

Pakiza Bano
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
You are on page 1/ 44

Vandana Rajput Vandana Rajput

 Easy-to-read − Python code is more clearly defined and visible to the eyes.
Python Programming 

Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows interactive testing and
UNIT-1 
debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level programming  Extendable − You can add low-level modules to the Python interpreter. These modules enable
language. Python is dynamically-typed and garbage-collected programming language. It was created by Guido programmers to add to or customize their tools to be more efficient.
Van Rossum during 1985- 1991.  Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported to many system
There are many other good reasons which make Python as the top choice of any programmer: calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of
Unix.
 Python is Open Source which means it’s available free of cost.  Scalable − Python provides a better structure and support for large programs than shell scripting.

 Python is simple and so easy to learn Characteristics of Python

 Python is versatile and can be used to create many different things. Following are important characteristics of Python Programming −

 Python has powerful development libraries include AI, ML etc.


 It supports functional and structured programming methods as well as OOP.
 It can be used as a scripting language or can be compiled to byte-code for building large applications.
 Python is much in demand and ensures high salary
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
The key advantages of learning Python:  It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile Python Syntax
your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − we can actually sit at a Python prompt and interact with the interpreter directly Python syntax can be executed by writing directly in the Command Line:
to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that >>> print("Hello, World!")
encapsulates code within objects.
Hello, World!
 Python is a Beginner's Language − Python is a great language for the beginner-level programmers
Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
C:\Users\Your Name>python myfile.py
Applications of Python Python Variables
Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare
 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows variables before using them or declare their type. A variable is created the moment we first assign a value to
the student to pick up the language quickly. it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain. Rules for Python variables
 A broad standard library − Python's bulk of the library is very portable and cross-platform  A Python variable name must start with a letter or the underscore character.
compatible on UNIX, Windows, and Macintosh.
 A Python variable name cannot start with a number.
 Interactive Mode − Python has support for an interactive mode which allows interactive testing and
 A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
debugging of snippets of code.
 Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
 Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
 The reserved words(keywords) in Python cannot be used to name the variable in Python.
platforms.
 Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
# An integer assignment
 Databases − Python provides interfaces to all major commercial databases. age = 45
 GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of # A floating point
Unix. salary = 1456.8
 Scalable − Python provides a better structure and support for large programs than shell scripting.
 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows # A string
the student to pick up the language quickly. name = "John"

1|Page 2|Page

Vandana Rajput Vandana Rajput

x = "awesome"
print(age)
print(salary) def myfunc():
print(name) print("Python is " + x)

45 myfunc()
1456.8
John Output:
Python is awesome
Python Assign Values to Multiple Variables
Python Data Types
Python allows assigning a single value to several variables simultaneously with “=” operators.
For example
a = b = c = 10 In programming, data type is an important concept. A data type represents a kind of value and determines what
operations can be done on it. Numeric, non-numeric and Boolean (true/false) data are the most obvious data
print(a) types
print(b)
print(c) Variables can store data of different types, and different types can do different things.
output
10 Python has the following data types built-in by default, in these categories:
10
10
Python allows adding different values in a single line with “,” operators. Text Type: str

Example Numeric Types: int, float, complex

a, b, c = 1, 20.2, "vandana" Sequence Types: list, tuple, range

print(a) Mapping Type: dict


print(b)
print(c) Set Types: set, frozenset
Output
1 Boolean Type: bool
20.2
Vandana Binary Types: bytes, bytearray, memoryview

None Type: NoneType


Types of variables

 Local Variables
 Global Variables Python Operators

Python operators are special symbols (sometimes called keywords) that are used to perform certain most
Local variables in Python are the ones that are defined and declared inside a function. We cannot call this commonly required operations on one or more operands (value, variables, or expressions).
variable outside the function.
Example Types of Operators in Python

def f(): Python language supports the following types of operators −


s = "Welcome”
print(s)
 Arithmetic Operators
f()  Comparison (Relational) Operators
Output:  Assignment Operators
 Logical Operators
Welcome  Bitwise Operators
 Membership Operators
Global variables in Python are the ones that are defined and declared outside a function, and we need to use  Identity Operators
them inside a function.

Example

3|Page 4|Page
Vandana Rajput Vandana Rajput

Python Arithmetic Operators print (" a is not equal to b")


Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, if ( a != b ):
multiplication, etc. Assume variable a holds 10 and variable b holds 20, then
print (" a is not equal to b")
else:
print ("a is equal to b")
Operator Name Example
if ( a < b ):
print ("a is less than b" )
+ Addition a + b = 30 else:
print ("a is not less than b")
if ( a > b ):
- Subtraction a – b = -10
print (" a is greater than b")
else:
* Multiplication a * b = 200 print (" a is not greater than b")

Python Assignment Operators


/ Division b/a=2
Assignment operators are used to assign values to variables.

% Modulus b%a=0
Operator Example Same As

** Exponent a**b =10**20 = a = 10 a = 10

+= a += 30 a = a + 30
// Floor Division 9//2 = 4
-= a -= 15 a = a - 15

Python Comparison Operators *= a *= 10 a = a * 10

Comparison operators (Relational operators) compare the values on either side of them and decide the relation /= a /= 5 a=a/5
among them.
%= a %= 5 a=a%5

**= a **= 4 a = a ** 4
Operator Name Example
//= a //= 5 a = a // 5
== Equal (a == b) is not true.
&= a &= 5 a=a&5
!= Not equal (a != b) is true.
|= a |= 5 a=a|5
> Greater than (a > b) is not true.
^= a ^= 5 a=a^5
< Less than (a < b) is true.
>>= a >>= 5 a = a >> 5
>= Greater than or equal to (a >= b) is not true.
<<= a <<= 5 a = a << 5
<= Less than or equal to (a <= b) is true.

Example: Example:
a = 21 a=10
b = 10 b=5
if ( a == b ): print ("Augmented addition of int and int")
print (" a is equal to b") a+=b # equivalent to a=a+b
else: print ("a=",a, "type(a):", type(a))

5|Page 6|Page

Vandana Rajput Vandana Rajput

a=10
b=5.5
Logical "AND" Operator-
print ("Augmented addition of int and float")
a+=b # equivalent to a=a+b
For the compound Boolean expression to be True, both the operands must be True. If any or both operands
print ("a=",a, "type(a):", type(a)) evaluate to False, the expression returns False.
a=10.50
b=5+6j
print ("Augmented addition of float and complex")
a+=b #equivalent to a=a+b
print ("a=",a, "type(a):", type(a))

Output:

Augmented addition of int and int


a= 15 type(a): <class 'int'>
Augmented addition of int and float AND Truth Table
a= 15.5 type(a): <class 'float'>
Augmented addition of float and complex A B A and B

a= (15.5+6j) type(a): <class 'complex'>


F F F

Python Logical Operators


F T F
Python logical operators are used to form compound Boolean expressions. Each operand for these logical
operators is itself a Boolean expression.
T F F

Example:
T T T
age > 16 and marks > 80

percentage< 50 or attendance < 75


Example:

x=5

Operator Description Example print(x > 3 and x <10)

Output: true

AND Returns True if both statements are true x < 5 and x < 10 Logical "OR" Operator

The OR operator returns True if any of the operands is True. For the compound Boolean expression to be False,
both the operands have to be False.
OR Returns True if one of the statements is true x < 5 or x < 4

NOT Reverse the result, returns False if the result is true not(x < 5 and x < 10)

7|Page 8|Page
Vandana Rajput Vandana Rajput

x=5

print(not(x > 3 and x < 10))

Output: false

Bitwise Operators

Bitwise operators are used to compare (binary) numbers. Python bitwise operators are normally used to
perform bitwise operations on integer-type objects. However, instead of treating the object as a whole, it is
treated as a string of bits.

A B A OR B
Operator Name Description Example
F F F

F T T
& AND Sets each bit to 1 if both bits are 1 x&y
T F T

T T T
| OR Sets each bit to 1 if one of two bits is 1 x|y
Example:

x=5
^ XOR Sets each bit to 1 if only one of two bits is 1 x^y
print(x > 3 or x < 4)

Output: false

Logical "NOT" Operator ~ NOT Inverts all the bits ~x

This is a unary operator. The state of Boolean operand that follows is reversed. As a result, not True becomes
False and not False becomes True.

Logical "not" Operator Truth Table << Zero fill Shift left by pushing zeros in from the right and let the x << 2
left shift leftmost bits fall off

A NOT(A)

>> Signed Shift right by pushing copies of the leftmost bit in from x >> 2
F T right shift the left, and let the rightmost bits fall off

T F

Bitwise AND Operator (&)

Example: Bitwise AND operator is somewhat similar to logical and operator. It returns True only if both the bit operands
are 1 (i.e. True). All the combinations are −

9|Page 10 | P a g e

Vandana Rajput Vandana Rajput

0 & 0 is 0 1 ^ 0 is 1
1 ^ 1 is 0
1 & 0 is 0
Example:
0 & 1 is 0 0011 1100 =60
1 & 1 is 1 ^
0000 1101 =13
-------------
0011 0001 =49

Example:
Bitwise NOT Operator (~)
a=60
b=13 This operator is the binary equivalent of logical NOT operator. It flips each bit so that 1 is replaced by 0, and 0
print ("a:",a, "b:",b, "a&b:",a&b) by 1, and returns the complement of the original number. Python uses 2's complement method.
Output –
Bitwise Left Shift Operator (<<)
a: 60 b: 13 a&b: 12
Left shift operator shifts most significant bits to right by the number on the right side of the "<<" symbol.

Example: Example:
0011 1100 =60
a=60
&
0000 1101 =13 print ("a:",a, "a<<2:", a<<2)
-------------
0011 1100 =60
0000 1100 =12
<<
Bitwise OR Operator (|) 2
-------------
1111 0000 =240
The "|" symbol (called pipe) is the bitwise OR operator. If any bit operand is 1, the result is 1 otherwise it is 0.
0 | 0 is 0 Bitwise Right Shift Operator (>>)
0 | 1 is 1
1 | 0 is 1 Right shift operator shifts least significant bits to left by the number on the right side of the ">>" symbol.

1 | 1 is 1 Example:
0011 1100 =60
Example:
>>
0011 1100 =60 2
| -------------
0000 1101 =13 0000 1111 =15

------------- Python Membership Operators


0011 1101 =61
The membership operators in Python help us determine whether an item is present in a given container type
Bitwise XOR Operator (^) object, or in other words, whether an item is a member of the given container type object.

The term XOR stands for exclusive OR. It means that the result of OR operation on two bits will be 1 if only
one of the bits is 1.
Operator Description Example
0 ^ 0 is 0
0 ^ 1 is 1

11 | P a g e 12 | P a g e
Vandana Rajput Vandana Rajput

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object,
with the same memory location
in Returns True if a sequence with the specified value is present in the object x in y

not in Returns True if a sequence with the specified value is not present in the x not in y
Operator Description Example
object

Example: is Returns True if both variables are the same object x is y

var = "Vandana Rajput"


a = "P"
b = "Van" is not Returns True if both variables are not the same object x is not y
c = "raj"
d = "d"
print (a, "in", var, ":", a in var)
print (b, "in", var, ":", b in var)
Python Comments
print (c, "in", var, ":", c in var)
print (d, "in", var, ":", d in var) Python comments make code easier to understand and they are completely ignored by the interpreter, which
means you can provide as many comments as you like in your program to make it more readable and
Output: explanatory.
P in Vandana Rajput: False
Van in Vandana Rajput: True
Python supports two types of comments:
raj in Vandana Rajput : False
d in Vandana Rajput : True
 Single-line comments
 Multi-line comments
The 'not in' Operator
Single Line Comments in Python
The "not in" operator is used to check a sequence with the given value is not present in the object like
string, list, tuple, etc. In a Python script, the symbol # marks the beginning of comment line. It is effective till the end of line in the
editor. If # is the first character of line, then entire line will be assumed as a comment and interpreter will ignore
Examplevar = "Vandana Rajput" it.

a = "P" Example:
b = "Van"
#This is a comment
c = "raj"
print("Hello, World!")
d = "d"
print (a, "in", var, ":", a in not var) Multiline Comments
print (b, "not in", var, ":", b in not var)
print (c, "not in", var, ":", c in not var) Python does not really have syntax for multiline comments. To add a multiline comment you could insert# for
each line:
print (d, "not in", var, ":", d in not var)

#This is a comment
Output: #written in
P in Vandana Rajput : False #more than just one line
Van not in Vandana Rajput : False print("Hello, World!")
raj not in Vandana Rajput : True
d not in Vandana Rajput : False
Python User Input Functions
Python Identity Operators
Python provides us with built-in functions to read the input from the keyboard.

13 | P a g e 14 | P a g e

Vandana Rajput Vandana Rajput

 The input () Function Disadvantages of Interpreted Languages

The input() Function  A program that is executed in an interpreted language is slower as compared to a language that is
directly compiled.
The input() function allows user input.  It happens because the line of codes passes through an interpretation run-time.
 The code has to be compiled, and after compilation, a byte code file is generated before interpretation
Example: which makes the execution time high. Therefore due to this problem, the run-time complexity of the
program increases.

name = input()
Q.2 What is Object-Oriented Programming in Python?
city = input() In Python object-oriented Programming (OOPs) is a programming paradigm that uses objects and classes in
programming. It aims to implement real-world entities like inheritance, polymorphisms, encapsulation, etc. in
print ("Hello My name is", name) the programming. The main concept of object-oriented Programming (OOPs) or oops concepts in Python is to
print ("I am from ", city) bind the data and the functions that work together as a single unit so that no other part of the code can access
this data.

example: Q.3 Explain the programming cycle for python in detail.


The programming cycle, also known as the software development life cycle (SDLC), refers to the various stages
width = input("Enter width : ") involved in creating, testing, and maintaining software applications. While there are different models for the
height = input("Enter height : ") SDLC, a commonly used one is the waterfall model, which consists of the following phases: requirements
gathering, design, implementation, testing, deployment, and maintenance.

area = width*height
1. Requirements Gathering: In this phase, you gather and analyze the requirements for your Python
print ("Area of rectangle = ", area)
application. This involves understanding the problem you’re trying to solve, identifying user needs, and
documenting the software specifications.
The print() Function:
 Example: Let’s say you’re building a simple calculator program. Your requirements might include basic
Python's print() function is a built-in function. It is the most frequently used function that displays value of
arithmetic operations such as addition, subtraction, multiplication, and division.
Python expression given in parenthesis, on Python's console, or standard output (sys.stdout).
2. Design: In the design phase, you create a high-level design for your Python program based on the
Example: requirements. This includes designing the architecture, data structures, algorithms, and user interface (if
applicable).
a = "Hello World"
print(a)  Example: For the calculator program, you might design a user interface with input fields for two
Output: hello world numbers and buttons for different operations. You would also outline the structure of your code, such as
defining functions for each arithmetic operation.

Q.1 How python is interpreted? 3. Implementation: In this phase, you start coding your Python program based on the design. You write the
Python is one of the most popular interpreted languages. Python is both compiled as well as actual source code, following best practices, coding standards, and using appropriate libraries or frameworks.
an interpreted language, which means when we run a python code, it is first compiled and then
interpreted line by line. The compile part gets deleted as soon as the code gets executed in Python so  Example: You would write Python code to handle user input, perform the desired arithmetic operation
that the programmer doesn’t get onto unnecessary complexity. The size of programs written in Python based on the user’s choice, and display the result.
is less, and it is easier to debug the code in the Python language. The program that is executed in
4. Testing: In the testing phase, you verify that your Python program functions correctly and meets the specified
an interpreted language is slower as compared to a language that is directly compiled because the line
requirements. This involves writing test cases, executing them, and fixing any issues that arise.
of codes passes through an interpretation run-time which increases the run-time complexity.

 Example: You would write test cases to cover different scenarios, such as testing addition, subtraction,
Advantages of Interpreted Languages
multiplication, and division with various inputs. You would then run the tests and fix any bugs or errors
discovered during testing.
An interpreted language gives some extra benefits and flexibility over compiled language.
5. Deployment: Once you have thoroughly tested your Python program, you are ready to deploy it to a
 Since the interpreter reads instructions line by line and generates output till the point the code is production environment or distribute it to users. This may involve packaging your program, creating an installer,
correct, the ease of debugging increases as it is easier to get information about the source point of error. or making it available for download.
 The size of programs written in Python is less as compared to other languages.
 As Python generates byte code before interpretation, this byte code can be used by any other platform  Example: You might create an executable file or a Python package that users can install on their systems
to generate output. to use the calculator program.

15 | P a g e 16 | P a g e
Vandana Rajput

UNIT -1
6. Maintenance: After deployment, your Python program may require updates, bug fixes, or enhancements
based on user feedback or changing requirements. Maintenance involves making these changes, and ensuring
the program remains functional and up-to-date.

 Example: You might release updates to the calculator program to add new features like square root Variable, Operator and Expression
calculation or to fix any reported issues.
1. Write a program that asks the user for his name and then welcomes him.
The output should look like this:

Enter your name: Saksham


Hello Saksham

name = input("Enter your name: ")


print("Hello", name)

2. Write a program that prompts the user to enter two integers and display
their sum on the screen.

num1 = int(input("Enter first integer: "))


num2 = int(input("Enter second integer: "))
sum = num1 + num2
print("The sum of", num1, "and", num2, "is", sum)

3. Write a program that prompts the user to input a Celsius temperature


and outputs the equivalent temperature in Fahrenheit. The formula to
convert the temperature is: F = 9/5 C + 32 where F is the Fahrenheit
temperature and C is the Celsius temperature.

celsius = float(input("Enter the temperature in Celsius: "))


fahrenheit = (9/5)*celsius + 32
print("The temperature in Fahrenheit is:", fahrenheit)

4. Write a program which accept principle, rate and time from user and
print the simple interest. The formula to calculate simple interest is: simple
interest = principle x rate x time / 100

principal = float(input("Enter the principal amount: "))


rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time in years: "))
simple_interest = (principal * rate * time) / 100
print("The simple interest is:", simple_interest)

17 | P a g e

5. Write a program that accepts seconds from keyboard as integer. Your num2 = int(input("Enter the second number: "))
program should convert seconds in hours, minutes and seconds. Your
output should like this: # print the original values
print("Before swapping, first number is", num1, "and second number is", num2)
Enter seconds: 13400
Hours: 3 # swap the values without using extra variable
Minutes: 43 num1 = num1 + num2
Seconds: 20 num2 = num1 - num2
seconds = int(input("Enter seconds: ")) num1 = num1 - num2
hours = seconds // 3600
seconds = seconds % 3600 # print the swapped values
minutes = seconds // 60 print("After swapping, first number is", num1,"and second number is", num2)
seconds = seconds % 60
print("Hours:", hours)
print("Minutes:", minutes) 8. Write a program that prompts the user to input the radius of a circle and
print("Seconds:", seconds) outputs the area and circumference of the circle. The formula is
Area = pi x radius2
6. Write a program that prompts the user to enter number in two variables Circumference = 2 x pi x radius
and swap the contents of the variables.
radius = float(input("Enter the radius of the circle: "))
# prompt user to enter two numbers area = 3.14 * radius ** 2
num1 = int(input("Enter the first number: ")) circumference = 2 * 3.14 * radius
num2 = int(input("Enter the second number: ")) print("The area of the circle is:", area)
print("The circumference of the circle is:", circumference)
# print the original values
print("Before swapping, first number is", num1,"and second number is", num2)
9. Write a program that prompts the user to input the length and the width
# swap the values of a rectangle and outputs the area and perimeter of the rectangle. The
temp = num1 formula is
num1 = num2 Area = Length x Width
num2 = temp Circumference = 2 x ( Length + Width)

# print the swapped values length = int(input("Enter the length of the rectangle: "))
print("After swapping, first number is", num1,"and second number is", num2) width = int(input("Enter the width of the rectangle: "))

area = length * width


7. Write a program that prompts the user to enter number in two variables perimeter = 2 * (length + width)
and swap the contents of the variables.
print("The area of the rectangle is:", area)
(Do not declare extra variable.) print("The perimeter of the rectangle is:", perimeter)

# prompt user to enter two numbers


num1 = int(input("Enter the first number: "))
Vandana Rajput

10. Suppose a, b, and c denote the lengths of the sides of a triangle. Then
the area of the triangle can be calculated using the formula: Python Programming
Unit 2
where Python Program Flow Control Conditional blocks
Write a program that asks the user to input the length of sides of the
triangle and print the area. Python program control flow is regulated by various types of conditional
statements, loops, and function calls.
a = int(input("Enter the length of side a: "))
Types of Control Flow in Python-
b = int(input("Enter the length of side b: "))
1. The if statement
c = int(input("Enter the length of side c: "))
2. The if-else statement
3. The nested-if statement
s = (a + b + c) / 2
4. The if-elif-else ladder
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
Python if statement
print("The area of the triangle is:", area)
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or
not.
11. Write a program which prompts the user to input principle, rate and
Syntax of If Statement in Python:
time and calculate compound interest.
#if syntax Python
The formula is :
CI = P(1+R/100)^T – P if condition:
# Statements to execute if
# condition is true
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: ")) Example
time = float(input("Enter the time in years: "))
compound_interest = principal * ((1 + rate/100) ** time) - principal If statement:
print("The compound interest is:", compound_interest)
a = 33
b = 200
if b > a:
print("b is greater than a")

# Python program to show how if statements control loops

1. n = 5
2. for i in range(n):
3. if i < 2:
4. i += 1

Vandana Rajput Vandana Rajput

5. if i > 2:
6. i -= 2 Nested-If Statement in Python
A nested if is an if statement that is the target of another if statement. Nested if
7. print(i)
statements mean an if statement inside another if statement.
Yes, Python allows us to nest if statements within if statements. i.e., we can
1 place an if statement inside another if statement.
2 Syntax:
2 if (condition1):
1 # Executes when condition1 is true
2
if (condition2):
# Executes when condition2 is true
Python If Else Statement # if Block is end here
The if statement alone tells us that if a condition is true it will execute a block # if Block is end here
of statements and if the condition is false it won’t. But if we want to do Example:
something else if the condition is false, we can use the else statement with the # python program to illustrate nested If statement
if statement Python to execute a block of code when the Python if condition is
false. i = 10
Syntax of If Else in Python if (i == 10):
if (condition):
# Executes this block if # First if statement
# condition is true if (i < 15):
else: print("i is smaller than 15")
# Executes this block if
# condition is false # Nested - if statement
Example # Will only be executed if statement above
i = 20 # it is true
if (i < 15): if (i < 12):
print("i is smaller than 15") print("i is smaller than 12 too")
print("i'm in if Block") else:
else: print("i is greater than 15")
print("i is greater than 15")
print("i'm in else Block") Output:
print("i'm not in if and not in else Block") i is smaller than 15
i is smaller than 12 too
Output
For Loops in Python
i is greater than 15 A for loop is used for iterating over a sequence (that is either a list, a tuple, a
i'm in else Block dictionary, a set, or a string).
i'm not in if and not in else Block
Syntax
for var in iterable:
Vandana Rajput Vandana Rajput

# statements

for i in range(0, 10, 2):


Example print(i)
Output :
Print each fruit in a fruit list: 0
2
fruits = ["Apple", "Banana", "Cherry"] 4
for x in fruits: 6
print(x) 8
Output:
Python For Loop with Tuple
Apple
This code iterates over a tuple of tuples using a for loop with tuple unpacking.
Banana In each iteration, the values from the inner tuple are assigned to variables a
Cherry and b, respectively, and then printed to the console using the print() function.

Python For Loop with String t = ((1, 2), (3, 4), (5, 6))
for a, b in t:
This code uses a for loop to iterate over a string and print each character on a
print(a, b)
new line.
Output :
12
# Iterating over a String
34
print("String Iteration")
56
s = "APPLE" Exercises
for i in s:
print(i) Q.1 Write a program which asks the user for a number. If number is
OUTPUT: even print ‘Even’, else print ‘Odd’.

A num = int(input("Enter number: "))

P if num % 2 == 0:
print("Even")
P else:
L print("Odd")

E Q.2 Write a program to print counting from 1 to 10.

Python For Loop with a step size for i in range(1,11):


This code uses a for loop in conjunction with the range() function to generate a print(i)
sequence of numbers starting from 0, up to (but not including) 10, and with a
step size of 2. For each number in the sequence, the loop prints its value using Q.3 Write a program which prints all the divisors of a number.
the print() function. The output will show the numbers 0, 2, 4, 6, and 8.

Vandana Rajput Vandana Rajput

1 num = int(input("Enter number: ")) temp = newList[0]


2 newList[0] = newList[size - 1]
3 for i in range(2, num): newList[size - 1] = temp
4 if num % i == 0:
5 print(i) return newList

Q.4 Write a program to check if input number is a prime number. # Driver code
newList = [12, 35, 9, 56, 24]
1 num = int(input("Enter number: "))
2 print(swapList(newList))
3 is_prime = True
4
5 for i in range(2, num): OUTPUT:
6 if num % i == 0:
7 is_prime = False [24, 35, 9, 56, 12]
8 break
9
10 if is_prime:
11 print("%d is prime number" % num)
12 else:
13 print("%d is not a prime number" % num) Python Lists
Lists are used to store multiple items in a single variable.
Q.5 Write a program to calculate factorial of a number.
 Lists are one of 4 built-in data types in Python used to store collections of
num = int(input("Enter number: "))
data.
result = 1
for i in range(1, num + 1):  A Python list is a sequence of comma separated items, enclosed in square
result = result * i brackets [ ].
 In List items are ordered, changeable, and allow duplicate values.
print(result)  List items are indexed, the first item has index [0], the second item has
index [1] etc.
Q.6 Write a program to print all the numbers between 1000 and 2000
which are divisible by 7 but are not a multiple of 5.  In list duplicates values are allow.
 Lists are mutable in nature that means we can change, add, and remove
for num in range(1000, 2000): items in a list after it has been created.
if num % 7 == 0 and num % 5 != 0:
print(num) Following are some examples of Python lists −
Q.7 write a Python program to swap first and last element of the list
list1 = ["Roman", "Physics", 21, 69.75]
# Swap function list2 = [1, 2, 3, 4, 5]
def swapList(newList): list3 = ["a", "b", "c", "d"]
size = len(newList) list4 = [25.50, True, -55, 1+2j]

# Swapping
Vandana Rajput Vandana Rajput

Accessing Values in Lists


Example: 2
In Python, a list is a sequence. Each object in the list is accessible with its index. print(list2[:4])
The index starts from 0. Index or the last item in the list is "length-1". To access
the values in a list, use the square brackets for slicing along with the index or [10, 'aman', True, 10.66]
indices to obtain value available at that index.
This example returns the items from the beginning to, but NOT including, 10 in
Example: list2.
list1 = ["Rohan", "Physics", 21, 69.75]
list2 = [1, 2, 3, 4, 5] Change Item Value
print ("Item at 0th index in list1: ", list1[0])
print ("Item at index 2 in list2: ", list2[2]) To change the value of a specific item, refer to the index number

Output – list = ["apple", "ajay", "cherry"]


list[1] = 1000
Item at 0th index in list1: Roman print(list)

Item at index 2 in list2: 3 Output:


['apple', 1000, 'cherry']
Negative Indexing
Change the second value by replacing it with two new values:
Negative indexing means start from the end -1 refers to the last item, -2 refers to
the second last item etc. list = ["apple", "ajay", "cherry"]
list[1:2] = [True,'jayant']
Example: print(list)

list = ["apple", "banana", "cherry",10, 12.30] Output:


print(list[-1])
['apple', True, 'jayant', 'cherry']
Output:
Add List Items
12.3
Range of Indexes To add an item to the end of the list, use the append() method:

You can specify a range of indexes by specifying where to start and where to Using the append() method to append an item:
end the range. When specifying a range, the return value will be a new list with
the specified items. list = [1765, "salu", True]
list.append("orange")
Example: 1 print(list)

list2=[10,'aman',True,10.66,10] Output:
print(list2[1:5]) [1765, 'salu', True, 'orange']
Output: Insert Items
['aman', True, 10.66, 10]

Vandana Rajput Vandana Rajput

To insert a list item at a specified index, use the insert() method.


The insert() method inserts an item at the specified index: clear() Removes all the elements from the list
list = [1765, "salu", True,23.45,'manav']
list.insert(1, "orange")
print(list) copy() Returns a copy of the list

Output:

[1765, 'orange', 'salu', True, 23.45, 'manav'] count() Returns the number of elements with the specified value
Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only be extend() Add the elements of a list (or any iterable), to the end of the current
a reference to list1, and changes made in list1 will automatically also be made list
in list2.

There are ways to make a copy, one way is to use the built-in List
method copy(). index() Returns the index of the first element with the specified value
list = [1765, "salu", True,23.45,'manav']
list2=list.copy()
print(list2) insert() Adds an element at the specified position

output:

[1765, 'salu', True, 23.45, 'manav'] pop() Removes the element at the specified position

List Methods

Python has a set of built-in methods that you can use on lists. remove() Removes the item with the specified value

reverse() Reverses the order of the list


Method Description

sort() Sorts the list


append() Adds an element at the end of the list
Vandana Rajput Vandana Rajput

Python Tuples jay Method Description


Range of
Tuples are used to store multiple items in a single variable. Tuple is one of 4 Indexes
built-in data types in Python used to store collections of data, the other 3
count() Returns the number of times a specified value
are List, Set, and Dictionary, all with different qualities and usage. You can
occurs in a tuple
specify a range
 A tuple is a collection which is ordered and unchangeable. of indexes
 Tuples are written with round brackets (). by
 Tuple allow duplicates index() Searches the tuple for a specified value and
returns the position of where it was found
Empty tuples
specifying where to start and where to end the range. When specifying a range,
var=() the return value will be a new tuple with the specified items.
print(type(var))
Output: tuple = (100, 100.34, 'jay', "cherry",'jay')
<class 'tuple'> print(tuple[2:4])

Example 2: output:
tuple = (100, 100.34, 'jay', "cherry")
print(tuple) ('jay', 'cherry')
Output:
Tuple Methods
(100, 100.34, 'jay', 'cherry')
Python has two built-in methods that you can use on tuples.
Example 3: Allows duplicates

tuple = (100, 100.34, 'jay', "cherry”, ‘jay')


print(tuple)

Output:

(100, 100.34, 'jay', 'cherry', 'jay')

Access Tuple Items

You can access tuple items by referring to the index number, inside square
brackets:

tuple = (100, 100.34, 'jay', "cherry”, ‘jay')


print(tuple[2]) Dictionary

Output: Dictionaries are used to store data values in key: value pairs.

Vandana Rajput Vandana Rajput

 A dictionary is a collection which is ordered*, changeable and do not Capital of Gujarat is: Gandhinagar
allow duplicates.
Capital of Karnataka is: Bengaluru
 Dictionaries are written with curly brackets {} and have keys and values:
 Dictionary items are presented in key: value pairs, and can be referred to  The get() method doesn't raise error if the key is not found; it return
by using the key name. None.

Accessing Items Example:


capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar",
You can access the items of a dictionary by referring to its key name, inside "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
square brackets: print ("Capital of Gujarat is: ", capitals.get('Gujarat'))
print ("Capital of Karnataka is: ", capitals.get('madhya pradesh'))
Empty Dictionary
update() Method
var={}
print(type(var)) The update() method's argument is another dictionary. Value of keys common
in both dictionaries is updated.
Example:
Syntax
var={"name":'jay','age':30,'marks':45} d1.update(d2)
x=var["marks"]
print(x) marks = {"jay":67, "Imtiaz":88, "Laxman":91, "David":49}
print ("marks dictionary before update: \n", marks)
Output: 45 marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89}
marks.update(marks1)
print ("marks dictionary after update: \n", marks)

get() Method output:

The get() method in Python's dict class returns the value mapped to the given marks dictionary before update:
key.
{'jay': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49}
Syntax
Val = dict.get("key") marks dictionary after update:

Example: {'jay': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}

Remove Dictionary Items


capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar",
"Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
Python's del keyword deletes any object from the memory.
print ("Capital of Gujarat is: ", capitals.get('Gujarat'))
print ("Capital of Karnataka is: ", capitals.get('Karnataka')) del dict['key']
Output: Example:
Vandana Rajput Vandana Rajput

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} The popitem() method in dict class doesn't take any argument. It pops out the
print ("numbers dictionary before delete operation: \n", numbers) last inserted key-value pair, and returns the same as a tuple.
del numbers[20]
print ("numbers dictionary before delete operation: \n", numbers) Syntax

output: val = dict.popitem()

numbers dictionary before delete operation: Example:


numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
print ("numbers dictionary before pop operation: \n", numbers)
numbers dictionary before delete operation: val = numbers.popitem()
print ("numbers dictionary after pop operation: \n", numbers)
{10: 'Ten', 30: 'Thirty', 40: 'Forty'} print ("Value popped: ", val)

pop() Method Output −

The pop() method of dict class causes an element with the specified key to be numbers dictionary before pop operation:
removed from the dictionary. {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
numbers dictionary after pop operation:
Syntax {10: 'Ten', 20: 'Twenty', 30: 'Thirty'}
Value popped: (40, 'Forty')
val = dict.pop(key)

 The pop() method returns the value of the specified key after removing
the key-value pair. clear() Method
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} The clear() method in dict class removes all the elements from the dictionary
print ("numbers dictionary before pop operation: \n", numbers) object and returns an empty object.
val = numbers.pop(20)
print ("numbers dictionary after pop operation: \n", numbers)
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
print ("Value popped: ", val)
print ("numbers dictionary before clear method: \n", numbers)
Output − numbers.clear()
print ("numbers dictionary after clear method: \n", numbers)
numbers dictionary before pop operation:
{10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
Output −
numbers dictionary after pop operation:
{10: 'Ten', 30: 'Thirty', 40: 'Forty'} numbers dictionary before clear method:
Value popped: Twenty {10: 'Ten', 20: 'Twenty', 30: 'Thirty', 40: 'Forty'}
numbers dictionary after clear method:
popitem() Method
{}

Vandana Rajput Vandana Rajput

Python - Strings zen = '''


Beautiful is better than ugly.
A string is an immutable sequence of Unicode characters. Each character has a Explicit is better than implicit.
unique numeric value as per the UNICODE standard. But, the sequence as a Simple is better than complex.
whole doesn't have any numeric value even if all the characters are digits. To Complex is better than complicated.
differentiate the string from numbers and other identifiers, the sequence of '''
characters is included within single, double or triple quotes in its literal for char in zen:
representation. Hence, 1234 is a number (integer) but '1234' is a string. if char not in 'aeiou':
print (char, end='')
Accessing Values in Strings
Output
var1 = 'Hello World!' Btfl s bttr thn gly.
var2 = "Python Programming" Explct s bttr thn mplct.
print ("var1[0]: ", var1[0]) Smpl s bttr thn cmplx.
print ("var2[1:5]: ", var2[1:5])
Cmplx s bttr thn cmplctd.
Output: Python for Loop with Tuples
var1[0]: H
var2[1:5]: ytho Python's tuple object is also an indexed sequence, and hence we can traverse its
items with a for loop.
Updating Strings
Example
You can "update" an existing string by (re)assigning a variable to another string. numbers = (34,54,67,21,78,97,45,44,80,19)
The new value can be related to its previous value or to a completely different. total = 0
.string altogether. for num in numbers:
total+=num
var1 = 'Hello World!' print ("Total =", total)
print ("Updated String :- ", var1[:6] + 'Python') Output
Output:
Total = 539
Updated String: - Hello Python

Python for Loop with Strings


Python for Loop with Lists
A string is a sequence of Unicode letters, each having a positional index. The
Python's list object is also an indexed sequence, and hence we can traverse its
following example compares each character and displays if it is not a vowel ('a',
items with a for loop.
'e', 'I', 'o' or 'u')
Example
Example
The for loop traverses a list containing integers and prints only those which are
divisible by 2.
Vandana Rajput Vandana Rajput

numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0 any number: 12
for num in numbers: number not found in list
if num%2 == 0:
print (num)
Python continue Statement
Output
54 Python continue statement is used to skip the execution of the program block
78 and returns the control to the beginning of the current loop to start the next
iteration. When encountered, the loop starts next iteration without executing the
44
remaining statements in the current iteration.
80
The continue statement can be used in both while and for loops.
Python break Statement
Syntax
Python break statement is used to terminate the current loop and resumes
execution at the next statement, just like the traditional break statement in C. continue

Syntax
Example of continue Statement
break for letter in 'Python': # First Example
if letter == 'h':
Example continue
print ('Current Letter :', letter)
for letter in 'Python':
if letter == 'h': Output:
break
print ('Current Letter :', letter) Current Letter : P
Current Letter : y
Output: Current Letter : t
Current Letter : o
Current Letter : P Current Letter : n
Current Letter : y
Current Letter : t
Python pass Statement
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13] Python pass statement is used when a statement is required syntactically but
for num in numbers: you do not want any command or code to execute.
if num==no:
print ('number found in list') It is a null operation; nothing happens when it executes. Python pass statement
break is also useful in places where your code will eventually go, but has not been
else: written yet, i.e., in stubs).
print ('number not found in list')
Output:

Vandana Rajput Vandana Rajput

Syntax
step Optional. An integer number specifying the incrementation.
pass Default is 1
Example
for letter in 'Python': Example 1
if letter == 'h':
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
pass
print ('This is pass block') x = range(3, 6)
print ('Current Letter :', letter) for n in x:
print ("Good bye!")
print(n)
Current Letter : P 3
Current Letter : y
4
Current Letter : t
This is pass block 5
Current Letter : h Example 2
Current Letter : o
Current Letter : n Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
Good bye!
x = range(3, 20, 2)
Range() Function for n in x:
print(n)
The range() function returns a sequence of numbers, starting from 0 by default,
and increments by 1 (by default), and stops before a specified number.

Syntax
range(start, stop, step)

Parameter Values

Parameter Description

start Optional. An integer number specifying at which position to


start. Default is 0
stop Required. An integer number specifying at which position to
stop (not included).
UNIT-2
if num1 > num2:
print("The largest integer is", num1)
Conditional Structures else:
1. Write a program that prompts the user to input a number and display if
print("The largest integer is", num2)
the number is even or odd.
4. Write a program that prompts the user to enter a number and
Sol. determines whether it is positive, negative, or zero. The program should
print "Positive" if the number is greater than 0, "Negative" if the
# Prompt the user to input a number number is less than 0, and "Zero" if the number is 0.
number = int(input("Enter a number: "))
Sol.
# Check if the number is even or odd
if number % 2 == 0: number = int(input("Enter a number: "))
print(number, "is even.")
else: if number > 0:
print(number, "is odd.") print("Positive")
elif number < 0:
print("Negative")
2. Write a Python program that takes an age as input and determines
else:
whether a person is eligible to vote. If the age is 18 or above, print "You print("Zero")
are eligible to vote." Otherwise, print "You are not eligible to vote yet.".

Sol. 5. Write a program that prompts the user to enter their age and prints the
corresponding age group. The program should use the following age
# Prompt the user to input their age groups:
age = int(input("Enter your age: "))
0-12: Child
# Check if the age is 18 or above 13-19: Teenager
if age >= 18: 20-59: Adult
print("You are eligible to vote.") 60 and above: Senior Citizen
else: Sol.
print("You are not eligible to vote yet.") age = int(input("Enter your age: "))

if age >= 0 and age <= 12:


3. Write a program that prompts the user to input two integers and
print("Your age group is Child")
outputs the largest. elif age >= 13 and age <= 19:
print("Your age group is Teenager")
Sol. elif age >= 20 and age <= 59:
print("Your age group is Adult")
num1= int(input("Enter the first integer: ")) else:
num2= int(input("Enter the second integer: ")) print("Your age group is Senior Citizen")

weight = float(input("Enter your weight in kilograms: "))


height = float(input("Enter your height in meters: "))
6. Write a program that prompts the user to input a number from 1 to 7.
The program should display the corresponding day for the given # Calculate the BMI
number. BMI = weight / (height * height)
For example, if the user types 1, the output should be Sunday. If the
user types 7, the output should be Saturday. If the number is not # Classify the BMI
between 1 to 7 user should get error message as shown in sample output. if BMI < 18.5:
print("Category: Underweight")
Sol.
elif BMI <= 24.9:
print("Category: Normal weight")
day = int(input("Enter a number from 1 to 7: ")) elif BMI <= 29.9:
print("Category: Overweight")
if day == 1: else:
print(day, "is Sunday") print("Category: Obesity")
elif day == 2:
print(day, "is Monday")
elif day == 3:
print(day, "is Tuesday")
8. The marks obtained by a student in 3 different subjects are input by the
elif day == 4:
user. Your program should calculate the average of subjects and display
print(day, "is Wednesday") the grade. The student gets a grade as per the following rules:
elif day == 5:
print(day, "is Thursday") Average Grade
elif day == 6: 90-100 A
print(day, "is Friday") 80-89 B
elif day == 7: 70-79 C
print(day, "is Saturday") 60-69 D
else: 0-59 F
print("Wrong input! Please enter a number from 1 to 7.")
Sol.
sub1 = int(input("Enter marks obtained in subject 1: "))
7. Write a program that prompts the user to enter their weight (in
sub2 = int(input("Enter marks obtained in subject 2: "))
kilograms) and height (in meters). The program should calculate the sub3 = int(input("Enter marks obtained in subject 3: "))
Body Mass Index (BMI) using the formula: BMI = weight / (height *
height). The program should then classify the BMI into one of the avg_marks = (sub1 + sub2 + sub3) / 3
following categories: print("Average marks:", format(avg_marks,'.2f'))
less than 18.5 - Underweight
if avg_marks >= 90:
BMI between 18.5 and 24.9 - Normal weight
print("Grade: A")
BMI between 25 and 29.9 - Overweight
elif avg_marks >= 80:
BMI 30 or greater – Obesity
print("Grade: B")
Sol.
elif avg_marks >= 70:
# Prompt the user to enter their weight and height print("Grade: C")
elif avg_marks >= 60: print('The roots are imaginary.')
print("Grade: D")
else:
print("Grade: F") 10. Write a program that prompts the user to enter three numbers and
sorts them in ascending order. The program should print the sorted
numbers.
2
9. The roots of the quadratic equation ax + bx + c = 0, a ≠ 0 are given by Sol.
the following formula:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
In this formula, the term b2 - 4ac is called the discriminant. If b2 - 4ac =
# Sort the numbers in ascending order
0, then the equation has two equal roots.
if num1 <= num2 and num1 <= num3:
If b2 - 4ac > 0, the equation has two real roots. If b2 - 4ac < 0, the
smallest = num1
equation has two complex roots.
if num2 <= num3:
Write a program that prompts the user to input the value of a (the middle = num2
coefficient of x2), b (the coefficient of x), and c (the constant term) and largest = num3
outputs the roots of the quadratic equation. else:
middle = num3
Sol. largest = num2
elif num2 <= num1 and num2 <= num3:
import math smallest = num2
if num1 <= num3:
a = int(input('Enter the value of a: ')) middle = num1
b = int(input('Enter the value of b: ')) largest = num3
c = int(input('Enter the value of c: ')) else:
middle = num3
d = b*b - 4*a*c largest = num1
else:
if d == 0: smallest = num3
root1 = (-b) / (2 * a) if num1 <= num2:
root2 = root1 middle = num1
print('The roots are real and equal: Root1 =', root1, ', Root2 =', root2) largest = num2
else:
elif d > 0: middle = num2
root1 = (-b + math.sqrt(d)) / (2 * a) largest = num1
root2 = (-b - math.sqrt(d)) / (2 * a)
print('The roots are real and distinct: Root1 =', root1, ', Root2 =', root2) # Print the sorted numbers in ascending order
print("Sorted numbers in ascending order:", smallest, middle, largest)
else:

11. Write a program that prompts the user to input three integers and 1900 NOT a Leap Year
outputs the largest. 1995 NOT a Leap Year
Sol.
Sol.
Prompt the user to input a year
num1 = int(input("Enter number 1: ")) year = int(input("Enter a year(yyyy): "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: ")) # Check if the year is a leap year and output the result
if year % 4 == 0:
if num1 >= num2 and num1 >= num3: if year % 100 != 0:
print(num1, "is the largest number.") print(year, "is a leap year.")
elif num2 > num3: elif year % 400 == 0:
print(num2, "is the largest number.") print(year, "is a leap year.")
else: else:
print(num3, "is the largest number.") print(year, "is not a leap year.")
12. Write a program that prompts the user to input a character and else:
determine the character is vowel or consonant. print(year, "is not a leap year.")

Sol. 14. Write a program that prompts the user to input number of calls and
calculate the monthly telephone bills as per the following rule:
letter = input("Enter a letter: ") Minimum Rs. 200 for up to 100 calls.
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u': Plus Rs. 0.60 per call for next 50 calls.
print(letter, "is a vowel.") Plus Rs. 0.50 per call for next 50 calls.
else: Plus Rs. 0.40 per call for any call beyond 200 calls.
print(letter, "is a consonant.")
Solution#2 Sol.

letter = input("Enter a letter: ") calls = int(input("Enter number of calls: "))


if letter in ('a','e','i','o','u'):
print(letter," is a vowel.") if calls <= 100:
else: bill = 200
print(letter,"is a consonant.") elif calls > 100 and calls <= 150:
calls = calls - 100
bill = 200 + (0.60 * calls)
13. Write a program that prompts the user to input a year and determine elif calls > 150 and calls <= 200:
whether the year is a leap year or not. calls = calls - 150
Leap Years are any year that can be evenly divided by 4. A year that is bill = 200 + (0.60 * 50) + (0.50 * calls)
evenly divisible by 100 is a leap year only if it is also evenly divisible by else:
400. calls = calls - 200
bill = 200 + (0.60 * 50) + (0.50 * 50) + (0.40 * calls)
Example :
1992 Leap Year print("Total bill amount is", bill)
2000 Leap Year
19. Write a program that prompts the user to enter a number n, and then
prints all the odd numbers between 1 and n.
Looping Structures
Sol.

n = int(input("Enter a number: "))


15. Write a Python program to print the numbers from 1 to 10 using a for
for num in range(1, n + 1, 2):
loop.
print(num)
Sol.
20. Write a program that prints 'Happy Birthday!' five times on screen.
for num in range(1, 11):
for i in range(5):
print(num)
print("Happy Birthday!")
16. Write a Python program to print the numbers from 20 to 1 using a while
loop. 21. Write a program that takes a number n as input from the user and
generates the first n terms of the series formed by squaring the natural
Sol.
numbers.
num = 20 Sample output
while num >= 1: Enter a number: 6
print(num) The first 6 terms of the series are:
num -= 1 1 4 9 16 25 36

17. Write a program to print even numbers from 1 to 10. Sol.

Sol. n = int(input("Enter a number: "))

for num in range(2, 11, 2): print("The first", n, "terms of the series are:")
print(num)
for i in range(1, n + 1):
18. Write a program that prompts the user to enter a number n and prints term = i ** 2
all the numbers from 1 to n.
print(term, end=" ")
Sol.
22. Write a program that prompts the user to input a number and prints its
n = int(input("Enter a number: ")) mulitiplication table.
for num in range(1, n + 1):
num = int(input("Enter a number: "))
print(num)
print("Multiplication table of", num)
for i in range(1, 11):
product = num * i

print(num, "x", i, "=", product) Sol.

n = int(input("Enter a positive integer: "))


23. Write a Python program to print the first 8 terms of an arithmetic sum = 0
progression starting with 3 and having a common difference of 4.
The program should output the following sequence: for i in range(1, n+1):
3 7 11 15 19 23 27 31 sum += i

start = 3 print("Sum of natural numbers up to", n, "is", sum)


26. Write a program that takes a positive integer N as input and calculates
difference = 4 the sum of the reciprocals of all numbers from 1 up to N. The program
should display the final sum. Output of the program should be like:
term = start Enter a positive integer: 5

Sol.
for i in range(8): The sum of reciprocals from 1 to 5 is: 2.28
print(term, end=" ") N = int(input("Enter a positive integer: "))
term += difference sum_reciprocals = 0.0
24. Write a Python program to print the first 6 terms of a geometric
sequence starting with 2 and having a common ratio of 3.
The program should output the following sequence: for num in range(1, N + 1):
2 6 18 54 162 486
sum_reciprocals += 1 / num
start = 2

ratio = 3
print("The sum of reciprocals from 1 to", N, "is:",
term = start "{:.2f}".format(sum_reciprocals))
for i in range(6): 27. Write a program that prompts the user to enter a number and repeats
this process 5 times. The program should accumulate the numbers
print(term, end=" ") entered and then display the final running total.
term *= ratio Sample Output:
Enter a number: 10
25. Write a program that asks the user for a positive integer value. The
Enter a number: 15
program should calculate the sum of all the integers from 1 up to the
Enter a number: 35
number entered.
Enter a number: 40
For example, if the user enters 20, the loop will find the sum of 1, 2, 3, 4,
Enter a number: 50
... 20.
The final running total is: 150
Sol. 29. Write a Python program that prompts the user to enter a base number
and an exponent, and then calculates the power of the base to the
total = 0 exponent. The program should not use the exponentiation operator (**)
or the math.pow() function. The program should handle both positive
for i in range(5): and negative exponents.
number = int(input("Enter a number: ")) Sol.
total += number
# Prompt the user to enter the base number and exponent
base = float(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
print("The final running total is:", total)
# Initialize the result variable
28. Write a program that prompts the user to enter a positive integer and result = 1
calculates its factorial. The factorial of a positive integer 'n' is denoted
as 'n!' and is calculated by multiplying all the integers from 1 to 'n' # Calculate the power
together. For example, the factorial of 5 (denoted as 5!) is calculated as 1 if exponent >= 0:
x 2 x 3 x 4 x 5. The program should display the factorial value if the for i in range(exponent):
input is a positive number, or display a message stating that the factorial result *= base
does not exist for negative numbers. Additionally, for an input of zero, else:
the program should output that the factorial of 0 is 1 for i in range(exponent,0):
result /= base
Sol.
# Print the result
num = int(input("Enter a number: ")) print(base, "raised to the power of", exponent, "is:", result)

factorial = 1
30. Write a Python program that prompts the user to enter a positive
for i in range(1, num + 1): integer. Your program should display all the factors of the number.
Additionally, calculate and display the sum of its factors.
factorial *= i
Sample output:
if num == 0: Enter a positive integer: 45
Factors: 1 3 5 9 15 45
print("Factorial of 0 is 1.") Sum of factors: 78

elif num < 0: Sol.

print("Factorial does not exist for negative numbers.") num = int(input("Enter a positive integer: "))

else: factor_sum = 0

print("Factorial of", num, "is", factorial)


print("Factors:", end=" ")

for i in range(1, num + 1): count += 1

if num % i == 0: if count == 0:
print("No numbers were entered.")
print(i, end=" ") else:
average = sum / count
factor_sum += i print("Average of entered numbers:", average)

33. Write a program to enter the numbers till the user wants and at the end
print("\nSum of factors:", factor_sum) it should display the count of positive, negative and zeros entered.
Sol.
31. Write a program that uses a loop to repeatedly ask the user to enter
positive numbers. The loop will come to an end when a negative number positive_count = 0
is entered. After collecting all the positive numbers, the program will negative_count = 0
compute their sum and display the result to the user. zero_count = 0
Sol.
sum = 0 choice = 'Y'
while choice == 'Y' or choice == 'y':
while True: num = int(input("Enter a number: "))
num = int(input("Enter a positive number (negative number to stop): ")) if num == 0:
zero_count += 1
if num < 0: elif num > 0:
break positive_count += 1
else: else:
sum += num negative_count += 1

print("Sum of positive numbers:", sum) choice = input("Do you wish to continue (y/n)?: ")
32. Write a program that uses a loop to repeatedly ask the user to enter
integers. The loop will come to an end when zero is entered. After print("Positive numbers:", positive_count, ", Negative numbers:",
collecting all the integers, the program will compute and display the negative_count, ", Zeros:", zero_count)
average of all the entered numbers.
Sol. 34. Write a program to enter the numbers till the user wants and at the end
sum = 0 the program should display the largest and smallest numbers entered.
count = 0 Sol.

while True: min_num = 99999


num = int(input("Enter an integer (enter 0 to stop): ")) max_num = 0
choice = 'y'
if num == 0:
break while choice == 'y' or choice == 'Y':
else: num = int(input("Enter a number: "))
sum += num if num > max_num:
max_num = num
if num < min_num: print(original_number, "is not an Armstrong number.")
min_num = num
choice = input("Do you wish to continue (y/n)?: ") 37. Write a program that prompts the user to input a number and reverse
its digits. For example, the reverse of 12345 is 54321; reverse of 5600 is
print("Maximum number:", max_num) 65.
print("Minimum number:", min_num) Sol.

35. Write a program that asks the user to input a positive integer. Your num = int(input("Enter a positive integer: "))
program should find and display the sum of digits of number. For temp = num
example, sum of digits of number 32518 is 3+2+5+1+8 = 19. rev_no=0
Sol. while temp>0:
sum = 0 digit = temp%10
number = int(input("Enter a positive integer: ")) rev_no= digit + rev_no*10
temp = number temp= int(temp/10)
print("Reverse of",num,"is",rev_no)
while number > 0:
digit = number % 10 38. A palindromic number is a number that remains the same when its
sum += digit digits are reversed. For example, 16461. Write a program that prompts
number //= 10 the user to input a number and determine whether the number is
palindrome or not.
print('The sum of digits of',temp,'is',sum) Sol.

36. An Armstrong number of three digits is an integer in which the sum of num = int(input("Enter a positive integer: "))
the cubes of its digits is equal to the number itself. For example, 371 is temp = num
an Armstrong number since 33 + 73 + 13 = 371. Write a program to rev_no=0
check whether a number is an Armstrong number or not. while temp>0:
Sol. digit = temp%10
rev_no= digit + rev_no*10
number = int(input("Enter a number: ")) temp= int(temp/10)
original_number = number # Save the original number for display if num==rev_no:
print(num,"is a palindrome")
# Calculate the sum of cubes of digits else:
sum_of_cubes = 0 print(num,"is not a palindrome")
while number > 0:
digit = number % 10 39. Write a program that prompts the user to input a decimal integer and
sum_of_cubes += digit ** 3 display its binary equivalent.
number = number // 10 Sol.
# Check if the number is an Armstrong number number = int(input("Enter a positive number: "))
if original_number == sum_of_cubes: binary = 0
print(original_number, "is an Armstrong number.") place = 1
else: n = number

while n > 0: 42. Write a program to obtain the first 25 numbers of a Fibonacci sequence.
remainder = n % 2 In a Fibonacci sequence the sum of two successive terms gives the third
binary = binary + remainder * place term. Following are the first few terms of the Fibonacci sequence:
place = place * 10 0 1 1 2 3 5 8 13 21 34 55 89...
n = n // 2 Sol.
print("Binary representation of", number, "is", binary)
n = int(input("Enter number of terms required: "))
first=third=0
40. Write a program that prompts the user to input a binary number and second=1
display its decimal equivalent. print(first,second,end=' ')
Sol. for i in range(3,n+1):
third=first+second
binary = input("Enter a binary number: ") print(third,end=' ')
decimal=0 first=second
place=0 second=third
for i in reversed(binary):
decimal = decimal + int(i)*pow(2,place) 43. Write a program that prompts the user to input two numbers and
place=place+1 display its HCF. The Highest Common Factor (HCF) also called the
print("Decimal representation of binary",binary,"is",decimal) Greatest Common Divisor (GCD) of two whole numbers, is the largest
whole number that's a factor of both of them.
41. Write a program that prompts the user to input a positive integer. It Sol.
should then output a message indicating whether the number is a prime
number. A prime number is a number that is evenly divisible only by divisor = int(input("Enter first number: "))
itself and 1. For example, the number 5 is prime because it can be evenly dividend = int(input("Enter second number: "))
divided only by 1 and 5. The number 6, however, is not prime because it rem = 1
can be divided evenly by I, 2, 3, and 6.
Sol. while rem!=0:
rem = dividend % divisor
num = int(input("Enter a positive integer: ")) if rem == 0:
flag = False hcf = divisor
for i in range(2,num): else:
rem = num % i dividend = divisor
if rem == 0: divisor = rem
flag=True
break print("HCF is", hcf)

if flag==True or num <=1: 44. Write a program to add first seven terms of the following series using a
print(num,"is not a prime number") for loop:
else:
print(num,"is a prime number")

Sol.
sum = 0 4.
fact = 1 *
for i in range(1,8): ***
fact= fact*i *****
sum= sum + i/fact *******
print("Sum of series is",sum) *********
5.
1
45. Compute the sum up to n terms in the series 222
1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n 33333
where n is a positive integer and input by user. 4444444
Sol. 555555555
6.
n = int(input("Enter the value of n: ")) 1
sum = 0 212
sign = -1 32123
for i in range(1,n+1): 4321234
sign = sign * -1 543212345
sum = sum + sign * 1/i
print("Sum of series for first",n,"terms is",sum)
Sol.

46. Write programs to print following patterns : print("first pattern")


for i in range(4):
1. for j in range(10):
********** print("*",end='')
********** print()
**********
**********
print("second pattern")
2. for i in range(1,6):
* for j in range(1,i+1):
** print("*",end='')
*** print()
****
*****
3. print("third pattern")
* for i in range(1,6):
** for j in range(5,i,-1):
*** print(" ",end='')
**** for k in range(1,i+1):
***** print("*",end='')

print() Sol.

k=1
print("fourth pattern") for i in range(1,6):
for i in range(1,6): for j in range(1,i+1):
for j in range(5,i,-1): print(k,end=' ')
print(" ",end='') k=k+1
for k in range(1,2*i): print()
print("*",end='')
print()
47. Write a program to compute sin x for given x. The user should supply x
and a positive integer n. We compute the sine of x using the series and
print("fifth pattern") the computation should use all terms in the series up through the term
for i in range(1,6): involving xn
for j in range(5,i,-1): sin x = x - x3/3! + x5/5! - x7/7! + x9/9! ........
print(" ",end='') Sol.
for k in range(1,2*i):
print(i,end='') x = int(input("Enter the value of x: "))
print() n = int(input("Enter the value of n: "))
sign = -1
fact = i =1
print("sixth pattern") sum = 0
for i in range(1,6): while i<=n:
for j in range(5,i,-1): p=1
print(" ",end='') fact = 1
for k in range(i,0,-1): for j in range(1,i+1):
print(k,end='') p = p*x
for l in range(2,i+1): fact = fact*j
print(l,end='') sign = -1*sign
print() sum = sum + sign* p/fact
i = i+2
print("sin(",x,") =",sum)
46. Floyd's triangle is a right-angled triangular array of natural numbers as
shown below: 48. Write a program to compute cosine of x. The user should supply x and a
positive integer n. We compute the cosine of x using the series and the
computation should use all terms in the series up through the term
involving xn
cos x = 1 - x2/2! + x4/4! - x6/6! .....
Sol.

x = int(input("Enter the value of x: "))


Write a program to print the Floy'd triangle. n = int(input("Enter the value of n: "))
sign=-1
fact=1 50. Write a Python program that asks the user to enter the number of rows
i=2 and columns for a pattern to be displayed. For example, if the user
sum=0 enters 3 for the number of rows and 5 for the number of columns, the
while i<=n: output should be as follows:
p=1 12345
fact=1 12345
for j in range(1,i+1): 12345
p = p*x
fact = fact*j Sol.
sum= sum + sign* p/fact rows = int(input("Enter the number of rows: "))
sign = -1*sign cols = int(input("Enter the number of columns: "))
i = i+2 for i in range(rows):
print("cos(",x,") =",1+sum) for j in range(1, cols+1):
print(j, end='')
49. Write a program that generates a random number and asks the user to guess print()
what the number is. If the user's guess is higher than the random number, the
program should display "Too high, try again." If the user's guess is lower 51. Write a program that asks the user to enter a positive integer n and
than the random number, the program should display "Too low, try again." prints a triangle pattern of numbers. For, example, if user enters 4,
The program should use a loop that repeats until the user correctly guesses following pattern should be displayed.
the random number. Program should count and display number of tries to 1
win the game. 12
Sol. 123
1234
import random
Sol.
computer = random.randint(1,100) n = int(input("Enter a positive integer: "))
player = 0 for i in range(1, n+1):
tries=0 for j in range(1, i+1):
print(j, end='')
print("Guess My Number Game") print()

while(player != computer): 52. Write a program that asks the user to enter a positive integer n and
player = int(input('Enter your guess: ')) prints a right-angled triangle. For, example, if user enters 4, following
tries = tries + 1 pattern should be displayed.
1
if player < computer: 12
print('Too low, try again.') 123
elif player > computer: 1234
print('Too high, try again.')
else: Sol.
print("Correct!,you got it in",tries,"tries") n = int(input("Enter a positive integer: "))
for i in range(1, n+1):
print(' '*(n-i), end='')

for j in range(1, i+1): sample output:


print(j, end='') Enter the number of rows: 4
print() 1
23
53. Write a program that asks the user to enter a positive integer n and 456
prints a reverse pyramid pattern: 7 8 9 10
1234
123 Sol.
12 rows = int(input("Enter the number of rows: "))
1 num = 1
for i in range(1, rows+1):
Sol. for j in range(i):
n = int(input("Enter a positive integer: ")) print(num, end=' ')
for i in range(n, 0, -1): num += 1
print(' '*(n-i), end='') print()
for j in range(1, i+1):
print(j, end='') 56. Write a program that takes an integer input n and prints a pattern
print() using the multiplication table from 1 to n. Each cell in the pattern
should contain the product of its row and column numbers. Here is a
54. Write a program that prints the following diamond pattern: sample output: Enter a number: 5
1
123 1 2 3 4 5
12345
123 2 4 6 8 10
1 3 6 9 12 15
Sol. 4 8 12 16 20
n = int(input("Enter a positive odd integer: ")) 5 10 15 20 25
for i in range(1, n+1, 2):
print(' ' * ((n - i) // 2), end='')
for j in range(1, i+1):
print(j, end='') Sol.
print()
n = int(input("Enter a number: "))
for i in range(n-2, 0, -2):
print(' ' * ((n - i) // 2), end='') for i in range(1, n+1):
for j in range(1, i+1):
print(j, end='') for j in range(1, n+1):
print()
print(i*j, end='\t')
55. Floyd's Triangle is a right-angled triangular pattern of consecutive
print()
natural numbers. Each row in the triangle contains one more number
than the previous row. Write a program that takes a positive integer
input n and prints Floyd's Triangle pattern of numbers. Here is a
UNIT - 3 print("mul:",a*b)
print("div:",a/b)
Python Functions cal(8,9)

Calling a Function in Python


Python Functions is a block of statements that return the specific task. The
idea is to put some commonly or repeatedly done tasks together and make a After creating a function in Python we can call it by using the name of the
function so that instead of writing the same code again and again for different functions Python followed by parenthesis containing parameters of that
inputs, we can do the function calls to reuse code contained in it over and over particular function. Below is the example for calling def function Python.
again.
Some Benefits of Using Functions Ex.
 Increase Code Readability
 Increase Code Reusability def greet():
print("good morning")
Python Function Declaration greet()
The syntax to declare a function is:

Python Function with Parameters

Ex.
def cal(a,b):
print("addition :",a+b)
print("subtraction:",a-b)
print("mul:",a*b)
print("div:",a/b)
cal(8,9)
Types of Functions in Python
Types of Python Function Arguments
 Pre-defined function: These are Standard functions in Python that are Python supports various types of arguments that can be passed at the time of
available to use. the function call. In Python, we have the following function argument types in
Ex- len(), print(), int() Python:
 User-defined function: We can create our own functions based on our
requirements. 1. Positional arguments
Ex. Add(), mul() 2. Keyword arguments (named arguments)
3. Default argument
4. variable-length arguments
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any Positional arguments-
type of functionalities and properties to it as we require  Order should be maintained
 No. of parameter=no of arguments
def cal(a,b): Ex.
print("addition :",a+b) #positional argument
print("subtraction:",a-b)

def greet(firstname,lastname): print(my_list[:3]) # Output: [0, 1, 2]


print("good morning",firstname,lastname) print(my_list[5:]) # Output: [5, 6, 7, 8, 9]
greet("ankit","kumar") print(my_list[1:7:2]) # Output: [1, 3, 5]
print(my_list[::2]) # Output: [0, 2, 4, 6, 8]
print(my_list[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Keyword arguments (named arguments)-

 Order not important


String slicing
 No. of parameter=no of arguments
 Keyword arguments follow positions arguments String slicing in Python is a technique used to extract a substring (a portion of a
string) from a larger string. It involves specifying a range of indices to define
#keyword argument the portion to be extracted. The syntax for string slicing is string[start:stop:step].
def greet(firstname,lastname):
print("good evening", firstname,lastname)  start
greet("aman",lastname="rajput") (optional): The index where the slice begins (inclusive). If omitted, it defaults
to 0 (the beginning of the string).
Default argument  stop
 Order important (optional): The index where the slice ends (exclusive). If omitted, it defaults to
the length of the string, meaning the slice goes to the end.
#default argument
 step
def greet(firstname="hello"):
(optional): The increment between indices. If omitted, it defaults to 1, meaning
print("janvi",firstname)
consecutive characters are included. A negative step value allows slicing in
greet()
reverse.

List slicing EXAMPLE:

text = "Hello, World!"


List slicing in Python is a technique used to access a specific portion of a list. It
print(text[7:]) # Output: World!
involves specifying a range of indices to extract a sublist. The syntax for list
print(text[:5]) # Output: Hello
slicing is list [start:stop:step]. print(text[7:12]) # Output: World
print(text[::2]) # Output: Hlo ol!
 start: The index at which the slice begins (inclusive). If omitted, it defaults to 0.
print(text[::-1]) # Output: !dlroW ,olleH
 stop: The index at which the slice ends (exclusive). If omitted, it defaults to the
end of the list.
String Concatenation
 step: The increment between indices for the slice. If omitted, it defaults to 1.
To concatenate, or combine, two strings you can use the + operator.
EXAMPLE :
Example
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Merge variable a with variable b into variable c:
print(my_list[2:5]) # Output: [2, 3, 4]
a = "Hello" age = 36
b = "World" txt = f"My name is John, I am {age}"
c=a+b print(txt)
print(c)
OUTPUT:
Output:
My name is John, I am 36
HelloWorld

Example
String Methods
To add a space between them, add a " ":

a = "Hello"
b = "World"
Method Description
c=a+""+b
print(c)

Hello World capitalize() Converts the first character to upper case


String Format

we can combine strings and numbers by using f-strings or the format() method.
center() Returns a centered string
Example
age = 36
txt = "My name is John, I am " + age count() Returns the number of times a specified value occurs in a string
print(txt)

OUTPUT:
endswith() Returns true if the string ends with the specified value
Traceback (most recent call last):

File "c:\Users\HP\Desktop\a.py", line 62, in <module>

txt = "My name is John, I am " + age expandtabs() Sets the tab size of the string

~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~

TypeError: can only concatenate str (not "int") to str find() Searches the string for a specified value and returns the position of where
it was found
Example

Create an f-string:

format() Formats specified values in a string isupper() Returns True if all characters in the string are upper case

index() Searches the string for a specified value and returns the position of where join() Joins the elements of an iterable to the end of the string
it was found

ljust() Returns a left justified version of the string


isalnum() Returns True if all characters in the string are alphanumeric

lower() Converts a string into lower case


isalpha() Returns True if all characters in the string are in the alphabet

lstrip() Returns a left trim version of the string


isdecimal() Returns True if all characters in the string are decimals

partition() Returns a tuple where the string is parted into three parts
isdigit() Returns True if all characters in the string are digits

replace() Returns a string where a specified value is replaced with a specified


islower() Returns True if all characters in the string are lower case value

isnumeric() Returns True if all characters in the string are numeric rfind() Searches the string for a specified value and returns the last position of
where it was found

isprintable() Returns True if all characters in the string are printable


rindex() Searches the string for a specified value and returns the last position of
where it was found
isspace() Returns True if all characters in the string are whitespaces

rjust() Returns a right justified version of the string


istitle() Returns True if the string follows the rules of a title
1. String capitalize() Method
rpartition() Returns a tuple where the string is parted into three parts Example

Upper case the first letter in this sentence:

rsplit() Splits the string at the specified separator, and returns a list txt = "hello, and welcome to my world."

x = txt.capitalize()
rstrip() Returns a right trim version of the string
print (x)

Hello, and welcome to my world.


split() Splits the string at the specified separator, and returns a list
2. String center() Method

Example
splitlines() Splits the string at line breaks and returns a list
Print the word "banana", taking up the space of 20 characters, with "banana"
in the middle:

txt = "banana"
startswith() Returns true if the string starts with the specified value
x = txt.center(20)

print(x)
strip() Returns a trimmed version of the string
banana

3. String count() Method


swapcase() Swaps cases, lower case becomes upper case and vice versa
Example

Return the number of times the value "apple" appears in the string:
title() Converts the first character of each word to upper case
txt = "I love apple, apple are my favorite fruit"

x = txt.count("apple")
translate() Returns a translated string
print(x)

upper() Converts a string into upper case 2

4. String endswith() Method

Example Example

Check if the string ends with punctuation sign (.): Remove spaces to the left of the string:

txt = "Hello, welcome to my world." txt = " banana "


x = txt.lstrip()
x = txt.endswith(".") print("of all fruits", x, "is my favorite")

of all fruits banana is my favourite


print(x)
8. String split() Method
True
Example 1
5. String index() Method

Example Split a string into a list where each word is a list item:

txt = "welcome to the jungle"


Where in the text is the word "welcome"?:
txt = "Hello, welcome to my world." x = txt.split()

x = txt.index("welcome") print(x)

['welcome', 'to', 'the', 'jungle']


print(x)

7
Example 2
6. String join() Method
Split the string, using comma, followed by a space, as a separator:
Example
txt = "hello, my name is Peter, I am 26 years old"
Join all items in a tuple into a string, using a hash character as separator:
x = txt.split(", ")
myTuple = ("John", "Peter", "Vicky")
print(x)
x = "#".join(myTuple)
['hello', 'my name is Peter', 'I am 26 years old']
print(x)

John#Peter#Vicky Example 3
7. String lstrip() Method Use a hash character as a separator:

txt = "apple#banana#cherry#orange"
x = txt.split("#") ['Thank you for the music', 'Welcome to the jungle']

print(x)

['apple', 'banana', 'cherry', 'orange']


Example 2
Example 4
Split the string, but keep the line breaks:
Split the string into a list with max 2 items:

txt = "apple#banana#cherry#orange"
txt = "Thank you for the music\nWelcome to the jungle"
# setting the maxsplit parameter to 1, will return a list with 2 elements! x = txt.splitlines(True)
x = txt.split("#", 1)
print(x)
print(x) Output:
['apple', 'banana#cherry#orange'] ['Thank you for the music\n', 'Welcome to the jungle']

9. String rsplit() Method 11. String format() Method


The rsplit() method splits a string into a list, starting from the right.
The format() method formats the specified value(s) and insert them inside the
Example string's placeholder.
Split a string into a list, using comma, followed by a space (, ) as the separator: The placeholder is defined using curly brackets: {}
txt = "apple, banana, cherry"
Example 1

x = txt.rsplit(", ") Insert the price inside the placeholder, the price should be in fixed point, two-
decimal format:
print(x)
txt = "For only {price:.2f} dollars!"
10. String splitlines() Method print(txt.format(price = 49))

Output:
Example For only 49.00 dollars!

Split a string into a list where each line is a list item: The Placeholders

7777 The placeholders can be identified using named indexes {price}, numbered
indexes {0}, or even empty placeholders {}.
Output:

Example 2 x = txt.find("welcome")

Using different placeholder values:


print(x)
#named indexes:
Output
txt1 = "My name is {fname}, I'm {age}".format(fname = "aman", age = 27)
7
#numbered indexes:
Example 2
txt2 = "My name is {0}, I'm {1}".format("aman",27)
If the value is not found, the find() method returns -1, but the index() method
#empty placeholders: will raise an exception:

txt3 = "My name is {}, I'm {}".format("aman",27) txt = "Hello, welcome to my world."

print(txt1) print(txt.find("q"))
print(txt.index("q"))
print(txt2)
Output:
print(txt3)
Output: -1

My name is aman, I'm 27 Traceback (most recent call last):

My name is aman, I'm 27 File "demo_ref_string_find_vs_index.py", line 4 in <module>

My name is aman, I'm 27 print(txt.index("q"))

ValueError: substring not found


12.String find() Method

The find() method finds the first occurrence of the specified value. Example 3
The find() method returns -1 if the value is not found. This method is
Where in the text is the first occurrence of the letter "e"?:
almost the same as the index() method, the only difference is that
the index() method raises an exception if the value is not found. txt = "Hello, welcome to my world."

x = txt.find("e")
Example 1
print(x)
Where in the text is the word "welcome"?:
Output:
txt = "Hello, welcome to my world."
1
Example 4

Where in the text is the first occurrence of the letter "e" when you only search
between position 5 and 10?:

txt = "Hello, welcome to my world."

x = txt.find("e", 5, 10)
Function Examples
print(x) 1. Write a function find_max that accepts three numbers as arguments and
returns the largest number among three. Write another function main, in
main() function accept three numbers from user and call find_max.
Output:
def find_max(x, y, z):
8 if x >= y and x >= z:
13.String isalnum() Method return x
elif y >= z:
The isalnum() method returns True if all the characters are alphanumeric, return y
meaning alphabet letter (a-z) and numbers (0-9). else:
Example of characters that are not alphanumeric: (space)! #%&? Etc. return z

Example def main():


a = int(input('Enter the first number: '))
Check if all the characters in the text are alphanumeric: b = int(input('Enter the second number: '))
c = int(input('Enter the third number: '))
txt = "united college 12" largest = find_max(a, b, c)
print('The largest number is', largest)
x = txt.isalnum()
main()
print(x) Output

output: Enter the first number: 23


Enter the second number: 78
false Enter the third number: 34
The largest number is 78

2. Write a function, is_vowel that returns the value true if a given character is a main()
vowel, and otherwise returns false. Write another function main, in main() Output
function accept a string from user and count number of vowels in that string.
def is_vowel(letter): 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101
if letter in 'aeiouAEIOU': 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191
return True 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281
else: 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389
return False 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491
499
def main():
count = 0 4. Write a function in python to find the sum of the cube of elements in a list.
string = input('Enter a text: ') The list is received as an argument to the function, in turn, the function must
for ch in string: return the sum. Write the main function which invokes the above function.
if(is_vowel(ch)): def sum(numbers):
count += 1 total = 0
for number in numbers:
print('Number of vowels are', count) total += number**3
return total
main()
def main():
numbers = [3,6,4,8,9]
Output s = sum(numbers)
print(s)
Enter a text: India is great
Number of vowels are 6 main()
Output
3. Write a function named is_prime, which takes an integer as an argument and
returns true if the argument is a prime number, or false otherwise. Also, 1548
write the main function that displays prime numbers between 1 to 500.
def is_prime(number): 5. Write the definition of a function zero_ending(scores) to add all those values
if number < 2: in the list of scores, which –– ending with zero and display the sum.
return False
for i in range(2,number): For example: If the scores contain [200, 456, 300, 100, 234, 678] The sum
if number%i == 0: should be displayed as 600.
return False
return True def zero_ending(scores):
total = 0
def main(): for number in scores:
for num in range(2,501): if number%10 == 0:
if is_prime(num): total += number
print(num, end=" ") return total
scores = [200, 456, 300, 100, 234, 678] print(value*3)
s = zero_ending(scores) else:
print(s) print(value+'#')
Output
mylist = ['41','DROND','GIRIRAJ', '13','ZARA']
600 fun(mylist)
6. Write a definition of a method count_now(places) to find and display those
place names, in which there are more than 5 characters.
8. For a given list of values in descending order, write a method in python to
For example : search for a value with the help of Binary Search method. The method should
If the list places contains return position of the value and should return -1 if the value not present in the
["DELHI","LONDON","PARIS","NEW YORK","DUBAI"] list.
The following should get displayed : def binary_search(L, data):
LONDON first = 0
NEW YORK last = len(L)-1
while(first<=last):
def count_now(places): mid = (first+last)//2
for place in places: if L[mid]==data:
if len(place) > 5: return mid
print(place) elif L[mid]>data:
first=mid+1
places = ["DELHI","LONDON","PARIS","NEW YORK","DUBAI"] else:
count_now(places) last=mid-1
Output return -1

LONDON
NEW YORK L = [90,78,25,13,9,2]
print(L)
7. Write a method in python to display the elements of list thrice if it is a index = binary_search(L,2)
number and display the element terminated with ‘#’ if it is not a number. if index == -1:
For example, if the content of list is as follows : print('Element not found')
ThisList=[‘41’,‘DROND’,‘GIRIRAJ’, ‘13’,‘ZARA’] else:
The output should be print('Elemenent found at position',index+1)
414141 Output
DROND#
GIRIRAJ# [90, 78, 25, 13, 9, 2]
131313 Elemenent found at position 6
ZARA#
9. Write a function half_and_half that takes in a list and change the list such that
def fun(mylist): the elements of the second half are now in the first half.
for value in mylist:
if value.isdigit():

For example, if the size of list is even and content of list is as follows :
my_liist = [10,20,30,40,50,60]
The output should be Enter a string: I know you know this but
[40,50,60,10,20,30]
if the size of list is odd and content of list is as follows : 2. Write a program to print all elements in a list those have only single
my_liist = [10,20,30,40,50,60,70] occurrence.
The output should be Example: if contents of list is [7, 5, 5, 1, 6, 7, 8, 7, 6].
[50,60,70,40,10,20,30] Your output should be:
18
def half_and_half(my_list):
if len(my_list)%2 == 0: you do not know everything
start = 0 i know you this but do not everything
else:z t = [7, 5, 5, 1, 6, 7, 8, 7, 6]
start = 1
d={}
L = len(my_list)//2
for value in t:
for i in range(L): if not value in d:
temp = my_list[i] d[value]=1
my_list[i] = my_list[i+L+start] else:
my_list[i+L+start] = temp d[value]+=1

my_list = [10,20,30,40,50,60,70] for k in d:


half_and_half(my_list) if d[k] == 1:
print(my_list) print(k, end=" ")
Output Output

[50, 60, 70, 40, 10, 20, 30] 18

3. Write a program to read 6 numbers and create a dictionary having keys


Dictionary Examples EVEN and ODD. Dictionary's value should be stored in list. Your dictionary
1. Write a program that reads a string from keyboard and prints the unique should be like:
words. Your program should convert input string to lower case. {'EVEN':[8,10,64], 'ODD':[1,5,9]}

text = input('Enter a string: ').lower() even=[]


words = text.split() odd=[]
for i in range(6):
d = {} n = int(input('Enter any number: '))
for word in words: if n%2 == 0:
if not word in d: even.append(n)
d[word]=0 else:
print(word, end=" ") odd.append(n)
Output
d = {} print('Enter student details')
d['Even']=even while True:
d['Odd']=odd roll_number = int(input('Enter your 6 digit roll number: '))
print(d) if roll_number in student:
print('Roll Number Already Exists')
4. Write a program that reads string from user. Your program should create a else:
dictionary having key as word length and value is count of words of that name = input('Enter name: ')
length. For example, if user enters 'A fat cat is on the mat'. student[roll_number] = name
print('Record added')
Word Word length ans = input('Do you want to continue(y/n)? ')
A 1 if ans in 'nN':
fat 3 break
cat 3
#######################################################
is 2
# a) Display the Roll numbers and name for all students
on 2
#######################################################
the 3
mat 3 print('\nRoll Number','Name')
The content of dictionary should be {1:1, 3:4, 2:2} for roll_number in student:
print(roll_number,'\t\t',student[roll_number])
text = input('Enter a sentence: ')
words = text.split() #############################################################
d = {} # b) Add a new key-value pair in this dictionary and display
for word in words: #############################################################
if len(word) in d:
d[len(word)] += 1 print('\nEnter a new record ')
else: roll_number = int(input('Enter your 6 digit roll number: '))
d[len(word)]=1 if roll_number in student:
print('Roll Number Already Exists')
print(d) else:
name = input('Enter name: ')
student[roll_number] = name
5. Write a program to input roll numbers and their names of students of your print('Record added\n')
class and store them in the dictionary as the key-value pair. Perform the
following operations on the dictionary: for roll_number in student:
a) Display the Roll numbers and name for all students. print(roll_number,'\t',student[roll_number])
b) Add a new key-value pair in this dictionary and display the modified
dictionary #############################################################
c) Delete a particular student's record from the dictionary # c) Delete a particular student's record from the dictionary
d) Modify the name of an existing students. #############################################################

student = {} print('\nDelete a record ')


roll_number = int(input('Enter roll number: '))

if roll_number in student:
del student[roll_number] Delete a record
print('Record deleted') Enter roll number: 123457
else: Record deleted
print('Record not found')
Modify a record
############################################# Enter new 6 digit roll number: 123456
# d) Modify the name of an existing students. Modify name Imran
############################################# Record updated

print('\nModify a record') 6. Find the sum of each row of matrix of size m x n. For example for the
roll_number = int(input('Enter new 6 digit roll number: ')) following matrix output will be like this :

if roll_number in student:
name=input('Modify name ')
student[roll_number] = name
print('Record updated')
else: Sum of row 1 = 32
print('Record not found') Sum of row 2 = 31
Output Sum of row 3 = 63

Enter student details n = int(input("Enter the number of rows:"))


Enter your 6 digit roll number: 123456 m = int(input("Enter the number of columns:"))
Enter name: Deepak
Record added matrix = []
Do you want to continue(y/n)? y
Enter your 6 digit roll number: 123457 print("Enter values in matrix :")
Enter name: Nisha
Record added # For user input
Do you want to continue(y/n)? n for i in range(n):
data =[]
Roll Number Name for j in range(m):
123456 Deepak data.append(int(input()))
123457 Nisha matrix.append(data)

Enter a new record # For printing the matrix


Enter your 6 digit roll number: 123458 for i in range(n):
Enter name: Irfan for j in range(m):
Record added print(matrix[i][j], end = " ")
print()
123456 Deepak
123457 Nisha
123458 Irfan
Vandana Rajput

# For printing row wise sum


for i in range(n):
Python Programming
sum = 0
for j in range(m):
sum = sum + matrix[i][j]
Unit 4
print('Sum of row',i+1,':',sum)

Python File Operations


File handling in Python is a powerful and versatile tool that can be used to perform a wide
7. Write a program that accepts a list from user. Your program should reverse
range of operations. Python supports file handling and allows users to handle files i.e., to
the content of list and display it. Do not use reverse() method.
read and write files, along with many other file handling options, to operate on files.
mylist = [] Advantages of File Handling in Python
size = int(input('How many elements you want to enter? '))  Versatility: File handling in Python allows you to perform a wide range of operations,
such as creating, reading, and writing, appending, renaming, and deleting files.
print('Enter',str(size),'elements')  Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform different
operations on files (e.g. read, write, append, etc.).
for i in range(size):  User–friendly: Python provides a user-friendly interface for file handling, making it
data = int(input()) easy to create, read, and manipulate files.
mylist.append(data)  Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
#reverse the list Disadvantages of File Handling in Python
for i in range(size//2):  Error: File handling operations in Python can be prone to errors, especially if the code
#swapping elements is not carefully written or if there are issues with the file system (e.g. file permissions,
file locks, etc.).
mylist[i],mylist[len(mylist)-1-i] = mylist[len(mylist)-1-i], mylist[i]  Security risks: File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on the
print('Reverse list:', mylist) system.
 Complexity: File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code to
ensure that files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.

Reading and Writing to text files in Python

Python provides built-in functions for creating, writing, and reading files. Two types of
files can be handled in Python, normal text files and binary files (written in binary
language, 0s, and 1s).
 Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in Python by default.
 Binary files: In this type of file, there is no terminator for a line, and the data is stored
after converting it into machine-understandable binary language.

1|Page

Vandana Rajput Vandana Rajput

File Access Modes f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","x")


Access modes govern the type of operations possible in the opened file. It refers to how the
file will be used once its opened. These modes also define the location of the File
Handle in the file. The file handle is like a cursor, which defines from where the data has to print("data create sucessfully ")
be read or written in the file and we can get Python output in text file.
There are 6 access modes in Python: Closing a Text File in Python
 Read Only (‘r’) close() function closes the file and frees the memory space acquired by that file. It is used
 Read and Write (‘r+’) at the time when the file is no longer needed or if it is to be opened in a different file mode.
 Write Only (‘w’) File_object.close()
 Write and Read (‘w+’)
 Append Only (‘a’) f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\b.txt","x")
 Append and Read (‘a+’)
 Read Only (‘r’) : Open text file for reading. The handle is positioned at the print("data create sucessfully ")
beginning of the file. If the file does not exist, raises the I/O error. This is also the f.close()
default mode in which a file is opened. print("data closed sucessfully ")
 Read and Write (‘r+’): Open the file for reading and writing. The handle is
positioned at the beginning of the file. Raises I/O error if the file does not exist.
 Write Only (‘w’) : Open the file for writing. For the existing files, the data is
truncated and over-written. The handle is positioned at the beginning of the file. Writing to a file in Python
Creates the file if the file does not exist. Open an existing file for a write operation. If the file already contains some data, then it
 Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, will be overridden but if the file is not present then it creates the file as well.
data is truncated and over-written. The handle is positioned at the beginning of the
file. There are two ways to write in a file:
 Append Only (‘a’): Open the file for writing. The file is created if it does not exist.  Using write()
The handle is positioned at the end of the file. The data being written will be  Using writelines()
inserted at the end, after the existing data.
 Append and Read (‘a+’) : Open the file for reading and writing. The file is created
if it does not exist. The handle is positioned at the end of the file. The data being write()-Inserts the string str1 in a single line in the text file.
written will be inserted at the end, after the existing data.
Syntax
Python File Open File_object.write(str1, mode)
Example

The key function for working with files in Python is the open() function. f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","w")

Syntax f.write("hello manav")


print("data write sucessfully ")
f = open(filename, mode)
writelines()

The open() function takes two parameters; filename, and mode. There are four different For a list of string elements, each string is inserted in the text file.Used to insert multiple
methods (modes) for opening a file: strings at a single time.

"x" - Create - Creates the specified file, returns an error if the file exists Syntax
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist File_object.writelines(L) for L = [str1, str2, str3]
"w" - Write - Opens a file for writing, creates the file if it does not exist

2|Page 3|Page
Vandana Rajput Vandana Rajput

Example

f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","w") readlines() :


f.writelines(["See you soon!", "Over and out."]) Reads all the lines and return them as each line a string element in a list.
f.close() Syntax

#open and read the file after the appending: File_object.readlines()


f = open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt", "r")
print(f.read()) Example
f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","w")
f.writelines(["hi manav ", "how are you ", "see you soon "])
See you soon! Over and out. f.close()
f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","r")
Reading from a file in Python
print(f.readlines())
There are three ways to read data from a text file:
 Using read()
Appending To a File in Python
 Using readline()
 Using readlines() Open the file for writing. The file is created if it does not exist. The handle is positioned at
the end of the file. The data being written will be inserted at the end, after the existing data.
Example
Read(): f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","a")
f.write("jay how are you?")
Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","r")
file. print(f.read())

Syntax seek() method


In Python, seek() function is used to change the position of the File Handle to a given
File_object.read() specific position. File handle is like a cursor, which defines from where the data has to be
read or written in the file.
Example Syntax: f.seek(offset, from_what), where f is file pointer
f=open("C:\\Users\\HP\\Desktop\\2nd year\\PYTHON PROGRAM\\a.txt","r") Parameters:
Offset: Number of positions to move forward
print(f.read()) from_what: It defines point of reference.
Returns: Return the new absolute position.
Readline(): The reference point is selected by the from_what argument. It accepts three values:

 0: sets the reference point at the beginning of the file


Reads a line of the file and returns in form of a string. For specified n, reads at most n
bytes. However, does not reads more than one line, even if n exceeds the length of the line.
 1: sets the reference point at the current file position
Syntax  2: sets the reference point at the end of the file
File_object.readline()
Example:
f=open("d.txt","x")
Example
f=open("d.txt","w+")
text="CSV (Comma Separated Values) is a simple file format used to
f=open("a.txt","r")
store tabular data,such as a spreadsheet or database. \nCSV file stores
print(f.readline())
tabular data (numbers and text) in plain text. \nEach line of the file
is a data record. "

4|Page 5|Page

Vandana Rajput Vandana Rajput

f.write(text) File Handling - Text File


f.seek(0) 1. Write a program that writes 10 random numbers to a file 'numbers.txt'. Each random number should
print(f.read()) be in the range of 1 through 100.

import random
CSV files in Python
# Open the file in write mode
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as file = open("numbers.txt", "w")
a spread sheet or database. A CSV file stores tabular data (numbers and text) in plain text.
Each line of the file is a data record. Each record consists of one or more fields, separated # Generate and write random numbers to the file
by commas. The use of the comma as a field separator is the source of the name for this file for i in range(10):
format. For working CSV files in Python, there is an inbuilt module called CSV. number = random.randint(1, 100)
file.write(str(number) + "\n")

# Close the file after writing


file.close()

2. Write a program that reads and display all of the numbers stored in the file numbers.txt and
calculates their total.

file = open("numbers.txt", "r")

total = 0

# read and display all numbers from the file


for line in file:
Reading a CSV file
number = int(line.strip())
Reading from a CSV file is done using the reader object. The CSV file is opened as a text
total += number
file with Python’s built-in open() function, which returns a file object. In this example, we
print(number)
first open the CSV file in READ mode, file object is converted to csv.reader() object and
further operation takes place.
# close the file after reading
#reading csv file file.close()
with open(filename, 'r') as csvfile:
print("Total:", total)
# creating a csv reader object
csvreader = csv.reader(csvfile)
3. Write a function, digit_count() in Python that counts and displays the number of digits in the text
file named 'sample.txt'. For example, if the content of 'sample.txt' is as follows :
Writing CSV files in Python
The team achieved a milestone in 2023. They completed a multi-million-dollar project ahead of
csv.writer() class is used to insert data to the CSV file. This class returns a writer object schedule. Stakeholders were impressed with a 98% success rate.
which is responsible for converting the user’s data into a delimited string. A csvfile object
should be opened with newline='' otherwise, newline characters inside the quoted fields will The function should display the output as 6
not be interpreted correctly.
def digit_count():
file = open('sample.txt', 'r')
with open("emp.csv", "w", newline='') as file: content = file.read()
writer = csv.writer(file) count = 0

6|Page 7|Page
Vandana Rajput Vandana Rajput

# Display words with length more than seven characters


for char in content: print("Words with length more than seven:")
if char.isdigit(): for word in words:
count += 1 if len(word) > 7:
print(word)
print(count)
# close the file
file.close() file.close()

# Call the function


digit_count() 6. Write a function last_digit_words() in Python to count the words ending with a digit in a text file
"notes.txt". For example, if the file content is as follows :

4. Write a function lines_count() that reads lines from a text file named 'zen.txt' and displays the lines The Computer6 hums softly as I sit with a Book3 in hand, diving into a world of imagination. Outside,
that begin with any vowel. Assume the file contains the following text and already exists on the my friends gather at House9 and I quickly grab my Pen2 to jot down the address.
computer's disk:
The expected output should be:
Beautiful is better than ugly. Number of words ending with a digit are 4
Explicit is better than implicit.
Simple is better than complex. def last_digit_words():
Complex is better than complicated.
file = open("notes1.txt", 'r')
The lines_count() function should display the output as: content = file.read()
Explicit is better than implicit.
words = content.split()
count = 0
def lines_count():
for word in words:
vowels = ['a', 'e', 'i', 'o', 'u']
if word[-1].isdigit():
file = open('zen.txt', 'r')
count += 1
for line in file:
# remove trailing newline character
print("Number of words ending with a digit are", count)
line = line.rstrip()
file.close()
# Check if the line starts with any vowel
if line[0].lower() in vowels:
last_digit_words()
print(line)

file.close()
# Call the function
lines_count() 7. Assume that a file 'names.txt' containing a series of names (as strings) exists on the computer’s
5. Assume that the file 'notes.txt' containing some text and exists on the computer’s disk. Write a disk. Write a function, first_five() that displays only the first five lines of the file’s contents. If the file
program that display only those words from 'notes.txt' file whose length is more than seven. Keep in contains less than five lines, it should display the file’s entire contents.
mind that any punctuation marks at the beginning or end of a word should also be considered as part
of the word's length.
def first_five():
# Read the content of the file
file = open("notes.txt", "r")
file = open("names.txt", "r")
content = file.read()
lines = file.readlines()

# Split the content into words


# Display the first five lines or the entire content if the file
words = content.split()
print("First five lines of the file's contents:")
for line in lines[:5]:

8|Page 9|Page

Vandana Rajput Vandana Rajput

print(line.rstrip())
file = open('feedback.txt', 'r')
# close the file for line in file:
file.close() total += 1
if line.startswith('Positive'):
# Call the function positive += 1
first_five() elif line.startswith('Negative'):
8. Write a Python program that reads a text file and prints its contents in reverse order (from the last negative += 1
line to the first line).
file.close()
file = open("zen.txt", 'r')
lines = file.readlines() print("Total feedbacks stored in the file:", total)
rlines = reversed(lines) print("Count of positive feedbacks:", positive)
for line in rlines: print("Count of negative feedbacks:", negative)
print(line.rstrip())
file.close() # Calling function
feedback_analysis()

9. Write the definition of a Python function named long_lines( ) which reads the contents of a text file
named 'lines.txt' and displays those lines from the file which have at least 8 words in it. For example, 11. Create a Python function make_copy() that reads a text file 'input.txt' and writes its contents to a
if the content of 'lines.txt' is as follows : new file 'output.txt', capitalizing the first letter of each word. For example, if 'input.txt' contains the
following content:
Flat is better than nested.
Sparse is better than dense. "In the world of programming, there are no limits to what you can achieve. Aim high!"
Readability counts. The 'output.txt' should contain:
Special cases aren't special enough to break the rules.
OUTPUT:
def long_lines(): "In The World Of Programming, There Are No Limits To What You Can Achieve. Aim High!"
file = open("line.txt", 'r')
for line in file: 12. Construct a program to change the contents of the file by reversing each character
words = line.split()
if len(words) >= 8: Separated by comma:
print(line.strip())
file.close() Hello!!

# call the function Output: !,!,o,l,l,e,H


long_lines()
ff=open("res.txt","r")

10. Assume that a file named 'feedback.txt' contains student feedback in the following format: data=f.read()
f.close()
Positive: Saksham improved grades, more confident now. f=open("res.txt","w")
Negative: Arav needs better time management for coursework. data_1=",".join(data)
Negative: Samar should work on communication in group activities. data_1 = data_1[::-1]
Negative: Soham could benefit from asking more questions in class. f.write(data_1)
Positive: Sakshi excels academically, a great team player. # f.write(s)
f.close()
def feedback_analysis():
total = 0
positive = 0
negative = 0

10 | P a g e 11 | P a g e
Vandana Rajput Vandana Rajput

1. Write a function in python to count the number of lines from a text file "story.txt" which data = file.read()
is not starting with an alphabet "T".Example: If the file "story.txt" contains the following words = data.split()
lines: A boy is playing there. for word in words:
There is a playground. if len(word) < 4:
print(word, end=" ")
An aeroplane is in the sky.
file.close()
The sky is pink.

def line_count(): display_words()


# file=open("story.txt","x")
file=open("story.txt","w") 4. Write a function in python to read the content from a text file "poem.txt" line by line and
file.writelines(["A boy is playing there. \n" display the same on screen.
"There is a playground.\n"
def read_file():
"An aeroplane is in the sky.\n""The sky is pink"])
file = open("poem.txt","r")
file = open("story.txt","r")
for line in file:
count=0
print(line, end="")
for line in file:
file.close()
if line[0] not in 'T':
count+= 1
read_file()
file.close()

print("No of lines not starting with 'T'=",count) 5. Write a function in Python to read lines from a text file "notes.txt". Your function should
find and display the occurrence of the word "the”. For example: If the content of the file
line_count() is:
"India is the fastest-growing economy. India is looking for more investments around the
globe. The whole world is looking at India as a great market. Most of the Indians can
2. Write a function in Python to count and display the total number of words in a text file. foresee the heights that India is capable of reaching."
def count_words():
The output should be 5.
file = open("story.txt","r")
count = 0
def count_words():
data = file.read()
file = open("notes.txt","r")
words = data.split()
count = 0
for word in words:
data = file.read()
count += 1
words = data.split()
print("Total words are",count)
for word in words:
file.close()
if word =="the" or word =="The":
count += 1
count_words()
print(count)
file.close()

count_words()

6. Write a function in Python to count the words "that" and "their" present in a text file
3. Write a function display_words() in python to read lines from a text file "story.txt", and "article.txt". [Note that the words "that" and "their" are complete words]
display those words, which are less than 4 characters.
def count_words():
def display_words():
file = open("story.txt","r") file = open("article.txt","r")

12 | P a g e 13 | P a g e

Vandana Rajput Vandana Rajput

count = 0 If the file matter.txt has the following content stored in it :


data = file.read() THE WORLD IS ROUND
words = data.split()
for word in words: The function hash_display() should display the following content :
if word == 'that' or word =='their':
T#H#E# #W#O#R#L#D# #I#S# #R#O#U#N#D#
count+=1
print(count) def count_hash():
file.close()
file = open("matter.txt","r")
count_words() data = file.read()
for letter in data:
print(letter, end="#")
7. Write a function in Python to count words in a text file those are ending with alphabet
"e". file.close()

def count_words(): count_hash()


file = open("article.txt","r")
count = 0 10. Aditi has used a text editing software to type some text. After saving the article as
data = file.read() WORDS.TXT, she realised that she has wrongly typed alphabet J in place of alphabet I
words = data.split() everywhere in the article.
for word in words:
if word[-1] == 'e': Write a function definition for JTOI() in Python that would display the corrected version
count+=1 of entire content of the file WORDS.TXT with all the alphabets "J" to be displayed as an
print(count) alphabet "I" on screen. Note: Assuming that WORD.TXT does not contain any J alphabet
file.close() otherwise.

count_words() Example:
If Aditi has stored the following content in the file WORDS.TXT:
8. Write a function in Python to count uppercase character in a text file. WELL, THJS JS A WORD BY JTSELF. YOU COULD STRETCH THJS TO BE A
SENTENCE
def count_letter(): The function JTOI() should display the following content:
file = open("article.txt","r") WELL, THIS IS A WORD BY ITSELF. YOU COULD STRETCH THIS TO BE A
data = file.read() SENTENCE
count = 0
for letter in data: def JTOI():
if letter.isupper(): file = open("words.txt","r")
count+=1 data = file.read()
print(count) for letter in data:
file.close() if letter == 'J':
print("I",end="")
count_letter() else:
print(letter,end="")

9. A text file named "matter.txt" contains some text, which needs to be displayed such that file.close()
every next character is separated by a symbol "#". Write a function definition for
hash_display() in Python that would display the entire content of the file matter.txt in the JTOI()
desired format.
Example :

14 | P a g e 15 | P a g e
Vandana Rajput Vandana Rajput

11. Construct a program that accepts a comma separated sequence of words as input and else:
prints the words in a comma-separated sequence after sorting them alphabetically. value.append(p)
Suppose the following input is supplied to the program: print (" , ".join(value))
without, hello, bag, world
Then, the output should be: 13. Construct a program which accepts a sequence of words separated by whitespace as file
bag, hello, without, world input. Print the words composed of digits only.
(AKTU FEB 2024 III SEM)
(AKTU FEB 2024 III SEM)
y=input("Enter comma separated sequence of words : ")
y=sorted(y.split(",")) def digit_count():
print(",".join(y))
file = open('sample.txt', 'r')
content = file.read()
12. A website requires the users to input username and password to register. Construct a count = 0
program to check the validity of password input by users. Following are the criteria for
checking the password: for char in content:
1. At least 1 letter between [a-z] if char.isdigit():
count += 1
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z] print(count)
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6 file.close()
6. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check # Call the function
them according to the above criteria. Passwords that match the criteria are to be printed, digit_count()
each separated by a comma.
(AKTU FEB 2024 III SEM)

import re
value = []
items=[x for x in input("enter the password ").split(',')]
print (items)
for p in items:

if len(p)<6 or len(p)>12:
continue
if not re.search("[a-z]",p):
print (" a-z characters not in the password")
continue
elif not re.search("[0-9]",p):
print( "0-9 letters are not in password")
continue
elif not re.search("[A-Z]",p):
print ("A-Z alphabets are not in password")
continue
elif not re.search("[$#@]",p):
print ("symbols are not in password")
continue

16 | P a g e 17 | P a g e

Vandana Rajput Vandana Rajput

UNIT-5 Python Modules

Python packages A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
Python Packages are a way to organize and structure your Python code into runnable code. Grouping related code into a module makes the code easier to
reusable components. Think of it like a folder that contains related Python files understand and use. It also makes the code logically organized.
(modules) that work together to provide certain functionality. Packages help
keep your code organized, make it easier to manage and maintain, and allow Create a Python Module
you to share your code with others. To create a Python module, write the desired code and save that in a file with
How to Create Package in Python? .py extension.
Creating packages in Python allows you to organize your code into reusable Example:
and manageable modules. Here‘s a brief overview of how to create packages: Let‘s create a simple calc.py in which we define two functions, one add and
 Create a Directory: Start by creating a directory (folder) for your package. another subtract.
This directory will serve as the root of your package structure.
 Add Modules: Within the package directory, you can add Python files # A simple module, calc.py
(modules) containing your code. Each module should represent a distinct def add(x, y):
functionality or component of your package. return (x+y)
 Init File: Include an __init__.py file in the package directory. This file can
be empty or can contain an initialization code for your package. It signals def subtract(x, y):
to Python that the directory should be treated as a package. return (x-y)
 Subpackages: You can create sub-packages within your package by adding
additional directories containing modules, along with their own __init__.py Import module in Python
files. We can import the functions, and classes defined in a module to another module
 Importing: To use modules from your package, import them into your using the import statement in some other Python source file.
Python scripts using dot notation. For example, if you have a module Syntax to Import Module in Python
named module1.py inside a package named mypackage, you would import import module
its function like this: from mypackage.module1 import greet.
 Distribution: If you want to distribute your package for others to use, you import calc
can create a setup.py file using Python‘s setuptools library. This file defines
metadata about your package and specifies how it should be installed. print(calc.add(10, 2))

Import Specific Attributes from a Python module


from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))

1|Page 2|Page
Vandana Rajput Vandana Rajput

Import all Names Python Library


The * symbol used with the import statement is used to import all the names A Python library is a collection of related modules. It contains bundles of code
from a module to a current namespace. that can be used repeatedly in different programs. It makes Python
Syntax: Programming simpler and convenient for the programmer. As we don‘t need
from module_name import * to write the same code again and again for different programs. Python libraries
from math import * play a very vital role in fields of Machine Learning, Data Science, Data
Visualization, etc.
# if we simply do "import math", then
# math.sqrt(16) and math.factorial() Python standard library
# are required.
print(sqrt(16)) The Python Standard Library contains the exact syntax, semantics, and tokens
print(factorial(6)) of Python. It contains built-in modules that provide access to basic system
functionality like I/O and some other core modules. Most of the Python
Calendar in Python Libraries are written in the C programming language. The Python standard
Python has a built-in Python Calendar module to work with date-related tasks. library consists of more than 200 core modules. All these work together to
Using the module, we can display a particular month as well as the whole make Python a high-level programming language. Python Standard Library
calendar of a year. plays a very important role. There are several other libraries in Python that
make a programmer‘s life easier.
Displaying a Calendar for a Month in Python
In the program below, we import the Python calendar module. The built-in
function month() inside the module takes in the year and the month and displays 1. Matplotlib: This library is responsible for plotting numerical data. And
the calendar for that month of the year. that‘s why it is used in data analysis. It is also an open-source library and
plots high-defined figures like pie charts, histograms, scatterplots, graphs,
import calendar etc.
2. Pandas: Pandas are an important library for data scientists. It is an open-
yy = 2023 source machine learning library that provides flexible high-level data
mm = 4 structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting,
# display the calendar Re-indexing, Iteration, Concatenation, Conversion of data, Visualizations,
print(calendar.month(yy, mm)) Aggregations, etc.
3. Numpy: The name ―Numpy‖ stands for ―Numerical Python‖. It is the
Displaying Calendar of a given Year in Python commonly used library. It is a popular machine learning library that
The built-in Python calendar() function inside the module takes in the year and supports large matrices and multi-dimensional data. It consists of in-built
displays the calendar for that year. mathematical functions for easy computations. Even libraries like
TensorFlow use Numpy internally to perform several operations on tensors.
import calendar Array Interface is one of the key features of this library.
yy = 2017 4. TensorFlow: This library was developed by Google in collaboration with
the Brain Team. It is an open-source library used for high-level
# display the calendar computations. It is also used in machine learning and deep learning
print(calendar.calendar(yy)) algorithms. It contains a large number of tensor operations. Researchers
also use this Python library to solve complex computations in Mathematics
and Physics.

3|Page 4|Page

Vandana Rajput Vandana Rajput

5. SciPy: The name ―SciPy‖ stands for ―Scientific Python‖. It is an open- 0-D Arrays
source library used for high-level scientific computations. This library is
built over an extension of Numpy. It works with Numpy to handle complex import numpy as np
computations. While Numpy allows sorting and indexing of array data, the
numerical data code is stored in SciPy. It is also widely used by application arr = np.array(42)
developers and engineers.
print(arr)
NumPy
1-D Arrays

NumPy stands for Numerical Python, is an open-source Python library that An array that has 0-D arrays as its elements is called uni-dimensional or 1-D
provides support for large, multi-dimensional arrays and matrices. It also have array.
a collection of high-level mathematical functions to operate on arrays. It was
created by Travis Oliphant in 2005. NumPy is a general-purpose array- import numpy as np
processing package.
It provides a high-performance multidimensional array object and tools for arr = np.array([1, 2, 3, 4, 5])
working with these arrays. It is the fundamental package for scientific
computing with Python. print(arr)
Features of NumPy
2-D Arrays
NumPy has various features which make them popular over lists.
Some of these important features include:
An array that has 1-D arrays as its elements is called a 2-D array.
 A powerful N-dimensional array object
 Sophisticated (broadcasting) functions
These are often used to represent matrix or 2nd order tensors.
 Tools for integrating C/C++ and Fortran code
 Useful linear algebra, Fourier transform, and random number capabilities
Example:
we are creating a two-dimensional array that has the rank of 2 as it has
2 axes.
Why Use NumPy? The first axis(dimension) is of length 2, i.e., the number of rows, and the
second axis(dimension) is of length 3, i.e., the number of columns. The
In Python we have lists that serve the purpose of arrays, but they are slow to overall shape of the array can be represented as (2, 3)
process.NumPy aims to provide an array object that is up to 50x faster than import numpy as np
traditional Python lists.The array object in NumPy is called ndarray, it provides
a lot of supporting functions that make working with ndarray very easy.Arrays # Creating array object
are very frequently used in data science, where speed and resources are very arr = np.array( [[ 1, 2, 3],
important. [ 4, 2, 5]] )
Arrays in NumPy # Printing type of arr object
print("Array is of type: ", type(arr))
NumPy is used to work with arrays. The array object in NumPy is
called ndarray. We can create a NumPy ndarray object by using # Printing array dimensions (axes)
the array() function. It is a table of elements (usually numbers), all of the same print("No. of dimensions: ", arr.ndim)
type, indexed by a tuple of positive integers.In NumPy, dimensions are
called axes. The number of axes is rank.
5|Page 6|Page
Vandana Rajput Vandana Rajput

# Printing shape of array Create Array of Fixed Size


print("Shape of array: ", arr.shape) The element is of an array is originally unknown, but its size is known.
Hence, NumPy offers several functions to create arrays with initial
# Printing size (total number of elements) of array placeholder content. This minimize the necessity of growing arrays, an
print("Size of array: ", arr.size) expensive operation.
For example: np.zeros, np.ones, np.full, np.empty, etc.
# Printing type of elements in array
print("Array stores elements of type: ", arr.dtype) import numpy as np
c = np.zeros((3, 4))
output print ("An array initialized with all zeros:\n", c)
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2 # Create a constant value array of complex type
Shape of array: (2, 3) d = np.full((3, 3), 6, dtype = 'complex')
Size of array: 6 print ("An array initialized with all 6s."
Array stores elements of type: int "Array type is complex:\n", d)

Create NumPy Array with List and Tuple # Create an array with random values
We can create an array from a regular Python list or tuple using the array() e = np.random.random((2, 2))
function. The type of the resulting array is deduced from the type of the print ("A random array:\n", e)
elements in the sequences.
Output:
import numpy as np An array initialized with all zeros:
[[0. 0. 0. 0.]
# Creating array from list with type float [0. 0. 0. 0.]
[0. 0. 0. 0.]]
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float') An array initialized with all 6s.Array type is complex:
print ("Array created using passed list:\n", a) [[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
# Creating array from tuple [6.+0.j 6.+0.j 6.+0.j]]
b = np.array((1 , 3, 2)) A random array:
print ("\nArray created using passed tuple:\n", b) [[0.01476511 0.25828159]
[0.01282863 0.23971051]]
output
Array created using passed list:
[[1. 2. 4.] Access Array Elements
[5. 8. 7.]]
Array indexing is the same as accessing an array element. We can access an
Array created using passed tuple: array element by referring to its index number. The indexes in NumPy arrays
[1 3 2] start with 0, meaning that the first element has index 0, and the second has
index 1 etc.

7|Page 8|Page

Vandana Rajput Vandana Rajput

Example print(arr[0:4])
Get the first element from the following array: Example

import numpy as np Slice elements from index 4 to the end of the array:

arr = np.array([1, 2, 3, 4]) import numpy as np


arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[0]) print(arr[4:])

Example Example

Get the second element from the following array. Slice elements from the beginning to index 4 (not included):

import numpy as np import numpy as np

arr = np.array([1, 2, 3, 4]) arr = np.array([1, 2, 3, 4, 5, 6, 7])


print(arr[:4])
print(arr[1])
Example

Get third and fourth elements from the following array and add them.

import numpy as np
NumPy Array Copy vs View

arr = np.array([1, 2, 3, 4]) The Difference Between Copy and View

The main difference between a copy and a view of an array is that the copy is a
print(arr[2] + arr[3]) new array, and the view is just a view of the original array.
Slicing arrays
The copy owns the data and any changes made to the copy will not affect
original array, and any changes made to the original array will not affect the
Slicing in python means taking elements from one given index to another given
copy.
index.We pass slice instead of index like this: [start:end].We can also define the
step, like this: [start:end:step]. If we don't pass start its considered 0. If we don't The view does not own the data and any changes made to the view will affect
pass end its considered length of array in that dimension. If we don't pass step the original array, and any changes made to the original array will affect the
its considered 1 view.
Example Example
Slice elements from index 0 to index 4 from the following array: Make a copy, change the original array, and display both arrays:
import numpy as np import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7]) arr = np.array([1, 2, 3, 4, 5])

9|Page 10 | P a g e
Vandana Rajput Vandana Rajput

x = arr.copy() 6. Cross-Platform: It is platform-independent and can run on various


arr[0] = 42 operating systems, including Windows, macOS, and Linux.
print(arr) 7. Interactive Plots: Matplotlib supports interactive plotting through the use
of widgets and event handling, enabling users to explore data dynamically.
print(x)
Basic Components or Parts of Matplotlib Figure
Example The parts of a Matplotlib figure include (as shown in the figure above):
1. Figures in Matplotlib: The Figure object is the top-level container for all
Make a view, change the original array, and display both arrays: elements of the plot. It serves as the canvas on which the plot is drawn.
You can think of it as the blank sheet of paper on which you‘ll create your
import numpy as np visualization.
2. Axes in Matplotlib: Axes are the rectangular areas within the figure where
arr = np.array([1, 2, 3, 4, 5]) data is plotted. Each figure can contain one or more axes, arranged in rows
x = arr.view() and columns if necessary. Axes provide the coordinate system and are
arr[0] = 42 where most of the plotting occurs.
3. Axis in Matplotlib: Axis objects represent the x-axis and y-axis of the
plot. They define the data limits, tick locations, tick labels, and axis labels.
print(arr) Each axis has a scale and a locator that determine how the tick marks are
print(x) spaced.
4. Marker in Matplotlib: Markers are symbols used to denote individual data
Matplotlib
points on a plot. They can be shapes such as circles, squares, triangles, or
custom symbols. Markers are often used in scatter plots to visually
Matplotlib is a powerful plotting library in Python used for creating static, distinguish between different data points.
5. Adding lines to Figures: Lines connect data points on a plot and are
animated, and interactive visualizations. Matplotlib‘s primary purpose is to
commonly used in line plots, scatter plots with connected points, and other
provide users with the tools and functionality to represent data graphically, types of plots. They represent the relationship or trend between data points
making it easier to analyze and understand. It was originally developed by and can be styled with different colors, widths, and styles to convey
John D. Hunter in 2003 and is now maintained by a large community of additional information.
developers. 6. Matplotlib Title: The title is a text element that provides a descriptive title
for the plot. It typically appears at the top of the figure and provides context
Key Features of Matplotlib: or information about the data being visualized.
1. Versatility: Matplotlib can generate a wide range of plots, including line 7. Axis Labels in Matplotlib: Labels are text elements that provide
plots, scatter plots, bar plots, histograms, pie charts, and more. descriptions for the x-axis and y-axis. They help identify the data being
2. Customization: It offers extensive customization options to control every plotted and provide units or other relevant information.
aspect of the plot, such as line styles, colors, markers, labels, and 8. Ticks: Tick marks are small marks along the axis that indicate specific data
annotations. points or intervals. They help users interpret the scale of the plot and locate
3. Integration with NumPy: Matplotlib integrates seamlessly with NumPy, specific data values.
making it easy to plot data arrays directly. 9. Tick Labels: Tick labels are text elements that provide labels for the tick
4. Publication Quality: Matplotlib produces high-quality plots suitable for marks. They usually display the data values corresponding to each tick
publication with fine-grained control over the plot aesthetics. mark and can be customized to show specific formatting or units.
5. Extensible: Matplotlib is highly extensible, with a large ecosystem of add- 10.Matplotlib Legend: Legends provide a key to the symbols or colors used
on toolkits and extensions like Seaborn, Pandas plotting functions, and in the plot to represent different data series or categories. They help users
Basemap for geographical plotting. interpret the plot and understand the meaning of each element.

11 | P a g e 12 | P a g e

Vandana Rajput Vandana Rajput

11.Matplotlib Grid Lines: Grid lines are horizontal and vertical lines that 10.Rich Documentation and Community Support: Matplotlib has
extend across the plot, corresponding to specific data intervals or divisions. comprehensive documentation and a large community of users and
They provide a visual guide to the data and help users identify patterns or developers, making it easy to find help, tutorials, and examples.
trends. Disadvantages of Matplotlib
12.Spines of Matplotlib Figures: Spines are the lines that form the borders of While Matplotlib is a powerful and versatile plotting library, it also has some
the plot area. They separate the plot from the surrounding whitespace and disadvantages that users might encounter:
can be customized to change the appearance of the plot borders. 1. Steep Learning Curve: For beginners, Matplotlib can have a steep
Different Types of Plots in Matplotlib learning curve due to its extensive customization options and sometimes
Matplotlib offers a wide range of plot types to suit various data visualization complex syntax.
needs. Here are some of the most commonly used types of plots in Matplotlib: 2. Verbose Syntax: Matplotlib‘s syntax can be verbose and less intuitive
 Line Graph compared to other plotting libraries like Seaborn or Plotly, making it more
 Bar chart time-consuming to create and customize plots.
 Histograms 3. Default Aesthetics: The default plot aesthetics in Matplotlib are often
 Scatter Plot considered less visually appealing compared to other libraries, requiring
 Box Plot more effort to make plots visually attractive.
 Pie Chart 4. Limited Interactivity: While Matplotlib does support interactive plotting
to some extent, it does not offer as many interactive features and options as
Advantages of Matplotlib other libraries like Plotly.
Matplotlib is a widely used plotting library in Python that provides a variety of 5. Limited 3D Plotting Capabilities: Matplotlib‘s 3D plotting capabilities
plotting tools and capabilities. Here are some of the advantages of using are not as advanced and user-friendly as some other specialized 3D plotting
Matplotlib: libraries.
1. Versatility: Matplotlib can create a wide range of plots, including line 6. Performance Issues with Large Datasets: Matplotlib can sometimes be
plots, scatter plots, bar plots, histograms, pie charts, and more. slower and less efficient when plotting large datasets, especially compared
2. Customization: It offers extensive customization options to control every to more optimized plotting libraries.
aspect of the plot, such as line styles, colors, markers, labels, and 7. Documentation and Error Messages: Although Matplotlib has
annotations. comprehensive documentation, some users find it challenging to navigate,
3. Integration with NumPy: Matplotlib integrates seamlessly with NumPy, and error messages can sometimes be cryptic and hard to debug.
making it easy to plot data arrays directly. 8. Dependency on External Libraries: Matplotlib relies on other libraries
4. Publication Quality: Matplotlib produces high-quality plots suitable for like NumPy and SciPy for many of its functionalities, which can sometimes
publication with fine-grained control over the plot aesthetics. lead to compatibility issues and dependency management issues.
5. Wide Adoption: Due to its maturity and flexibility, Matplotlib is widely 9. Limited Native Support for Statistical Plotting: While Matplotlib can
adopted in the scientific and engineering communities. create basic statistical plots, it lacks some advanced statistical plotting
6. Extensible: Matplotlib is highly extensible, with a large ecosystem of add- capabilities that are available in specialized libraries like Seaborn.
on toolkits and extensions like Seaborn, Pandas plotting functions, and 10.Less Modern Features: Matplotlib has been around for a long time, and
Basemap for geographical plotting. some users find that it lacks some of the modern plotting features and
7. Cross-Platform: It is platform-independent and can run on various interactive visualization capabilities found in newer libraries.
operating systems, including Windows, macOS, and Linux.
8. Interactive Plots: Matplotlib supports interactive plotting through the use Pyplot in Matplotlib Syntax
of widgets and event handling, enabling users to explore data dynamically.
9. Integration with Jupyter Notebooks: Matplotlib works seamlessly with
Jupyter Notebooks, allowing for interactive plotting and inline display of Syntax: matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None,
plots. **kwargs)
Parameters:
13 | P a g e 14 | P a g e
Vandana Rajput Vandana Rajput

This function accepts parameters that enable us to set axes scales and format
the graphs. These parameters are mentioned below :-
 plot(x, y): plot x and y using default line style and color.
 plot.axis([xmin, xmax, ymin, ymax]): scales the x-axis and y-axis from
minimum to maximum values
 plot.(x, y, color=’green’, marker=’o’, linestyle=’dashed’, linewidth=2,
markersize=12):
x and y co-ordinates are marked using circular markers of size 12 and
green color line with — style of width 2
 plot.xlabel(‘X-axis’): names x-axis
 plot.ylabel(‘Y-axis’): names y-axis
 plot(x, y, label = ‘Sample line ‘): plotted Sample Line will be displayed as Matplotlib Pyplot Examples
a legend There are various ways to create Matplotlib Pyplot . here we are discussing
some generally used methods for create Matplotlib Pyplot those are following.
What is Pyplot in Matplotlib?  Linear Plot using matplotlib.pyplot
Pyplot is a Matplotlib module that provides a MATLAB-like interface.  Linear Plot with Line Formatting
Matplotlib is designed to be as usable as MATLAB, with the ability to use  Scatter Plot with Color Mapping
Python and the advantage of being free and open-source. Each pyplot function
makes some changes to a figure: e.g., creates a figure, creates a plotting area in Linear Plot using matplotlib.pyplot
a figure, plots some lines in a plotting area, decorates the plot with labels, etc. In this example code uses Matplotlib to plot the per capita electricity
The various plots we can utilize using Pyplot are Line consumption of India and Bangladesh from 1972 to 2012. Two lines represent
Plot, Histogram, Scatter, 3D Plot, Image, Contour, and Polar the countries, with different colors. The plot includes axis labels, a title, and a
legend for clarity.
Plotting in Matplotlib
We will import the matplotlib library and then plot some example data points. # Python Program to illustrate Linear Plotting
The plot function marks the x-coordinates( import matplotlib.pyplot as plt
to show plot function
# year contains the x-axis values
import matplotlib.pyplot as plt # and e-india & e-bangladesh
# are the y-axis values for plotting
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.axis([0, 6, 0, 20]) year = [1972, 1982, 1992, 2002, 2012]
plt.show() e_india = [100.6, 158.61, 305.54, 394.96, 724.79]
e_bangladesh = [10.5, 25.21, 58.65, 119.27, 274.87]

# plotting of x-axis(year) and


# y-axis(power consumption)
with different colored labels of two countries

plt.plot(year, e_india, color ='orange',


label ='India')

15 | P a g e 16 | P a g e

Vandana Rajput Vandana Rajput

plt.plot(year, e_bangladesh, color ='g', plt.plot(year, e_india, color ='orange',


label ='Bangladesh') marker ='o', markersize = 12,
label ='India')
# naming of x-axis and y-axis
plt.xlabel('Years') plt.plot(year, e_bangladesh, color ='g',
plt.ylabel('Power consumption in kWh') linestyle ='dashed', linewidth = 2,
label ='Bangladesh')
# naming the title of the plot
plt.title('Electricity consumption per capita\ plt.xlabel('Years')
of India and Bangladesh') plt.ylabel('Power consumption in kWh')

plt.legend() plt.title('Electricity consumption per \


plt.show() capita of India and Bangladesh')

plt.legend()
plt.show()

Linear Plot with Line Formatting


In this example we will plot the same plot but with a variation in the lines
plotted. We can use dashed line or a line with markers.
# Python Program to illustrate Linear Plotting
import matplotlib.pyplot as plt
Scatter Plot with Color Mapping
year = [1972, 1982, 1992, 2002, 2012] In this example Python code uses Matplotlib and NumPy to generate a scatter
e_india = [100.6, 158.61, 305.54, plot with random data. The `x` and `y` arrays represent the coordinates, and
394.96, 724.79] the `colors` array provides color values. The plot includes a color mapping
using the ‗viridis‘ colormap, a color bar for reference, and axis labels. Finally,
e_bangladesh = [10.5, 25.21, 58.65, the plot is displayed using `plt.show()`.
119.27, 274.87]
import matplotlib.pyplot as plt
# formatting of line style and import numpy as np
# plotting of co-ordinates
17 | P a g e 18 | P a g e
Vandana Rajput Vandana Rajput

Matplotlib Simple Line Plot


# Generate random data In this example, a simple line chart is generated using NumPy to define data
np.random.seed(42) values. The x-values are evenly spaced points, and the y-values are calculated
x = np.random.rand(50) as twice the corresponding x-values.
y = np.random.rand(50)
colors = np.random.rand(50)
# importing the required libraries
# Create a scatter plot with color mapping import matplotlib.pyplot as plt
plt.scatter(x, y, c=colors, cmap='viridis', s=100, alpha=0.8) import numpy as np

# Add color bar for reference # define data values


cbar = plt.colorbar() x = np.array([1, 2, 3, 4]) # X-axis points
cbar.set_label('Color Value') y = x*2 # Y-axis points

# Set plot title and labels plt.plot(x, y) # Plot the chart


plt.title('Scatter Plot with Color Mapping') plt.show() # display
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Display the plot


plt.show()

Bar Plot in Matplotlib


A bar plot or bar chart is a graph that represents the category of data with
Line chart in Matplotlib rectangular bars with lengths and heights that is proportional to the values
which they represent. The bar plots can be plotted horizontally or vertically. A
Matplotlib is a data visualization library in Python. The pyplot, a sublibrary bar chart describes the comparisons between the discrete categories. One of
of Matplotlib, is a collection of functions that helps in creating a variety of the axis of the plot represents the specific categories being compared, while
charts. Line charts are used to represent the relation between two data X and the other axis represents the measured values corresponding to those
Y on a different axis. categories.

19 | P a g e 20 | P a g e

Vandana Rajput Vandana Rajput

Creating a bar plot


Pie chart in Python using Matplotlib-
The matplotlib API in Python provides the bar() function which can be used A Pie Chart is a circular statistical plot that can display only one series of
in MATLAB style use or as an object-oriented API. The syntax of the bar() data. The area of the chart is the total percentage of the given data. Pie charts
function to be used with the axes is as follows:- are commonly used in business presentations like sales, operations, survey
plt.bar(x, height, width, bottom, align) results, resources, etc. as they provide a quick summary.
How to draw pie chart?
import numpy as np Matplotlib API has pie() function in its pyplot module which create a pie chart
import matplotlib.pyplot as plt representing the data in an array. let‘s create pie chart in python.
Syntax: matplotlib.pyplot.pie(data, explode=None, labels=None,
colors=None, autopct=None, shadow=False)
# creating the dataset Parameters:
data = {'C':20, 'C++':15, 'Java':30, data represents the array of data values to be plotted, the fractional area of
'Python':35} each slice is represented by data/sum(data). If sum(data)<1, then the data
courses = list(data.keys()) values returns the fractional area directly, thus resulting pie will have empty
values = list(data.values()) wedge of size 1-sum(data).
labels is a list of sequence of strings which sets the label of each wedge.
fig = plt.figure(figsize = (10, 5)) color attribute is used to provide color to the wedges.
autopct is a string used to label the wedge with their numerical value.
# creating the bar plot shadow is used to create shadow of wedge.
plt.bar(courses, values, color ='maroon',
width = 0.4) # Import libraries
from matplotlib import pyplot as plt
plt.xlabel("Courses offered") import numpy as np
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show() # Creating dataset
cars = ['AUDI', 'BMW', 'FORD',
'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating plot
fig = plt.figure(figsize=(10, 7))
plt.pie(data, labels=cars)

# show plot
plt.show()

21 | P a g e 22 | P a g e
Vandana Rajput Vandana Rajput

textprops=dict(color="magenta"))

# Adding legend
ax.legend(wedges, cars,
title="Cars",
loc="center left",
bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")


ax.set_title("Customizing pie chart")
# Import libraries
import numpy as np # show plot
import matplotlib.pyplot as plt plt.show()

# Creating dataset
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating explode data


explode = (0.1, 0.0, 0.2, 0.3, 0.0, 0.0)

# Creating color parameters


colors = ("orange", "cyan", "brown","grey", "indigo", "beige")

# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}

# Creating autocpt arguments

def func(pct, allvalues): Pandas


absolute = int(pct / 100.*np.sum(allvalues))
return "{:.1f}%\n({:d} g)".format(pct, absolute) Pandas is a powerful and open-source Python library. The Pandas library is
used for data manipulation and analysis. Pandas consist of data structures and
# Creating plot functions to perform efficient operations on data.
fig, ax = plt.subplots(figsize=(10, 7))
wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data), What is Pandas Libray in Python?
explode=explode, Pandas is a powerful and versatile library that simplifies the tasks of data
labels=cars, manipulation in Python.
shadow=True, Pandas is well-suited for working with tabular data, such
colors=colors, as spreadsheets or SQL tables.
startangle=90, The Pandas library is an essential tool for data analysts, scientists, and
wedgeprops=wp, engineers working with structured data in Python.

23 | P a g e 24 | P a g e

Vandana Rajput Vandana Rajput

What is Python Pandas used for? Creating a Series


The Pandas library is generally used for data science, but have you wondered Pandas Series is created by loading the datasets from existing storage (which
why? This is because the Pandas library is used in conjunction with other can be a SQL database, a CSV file, or an Excel file).
libraries that are used for data science. Pandas Series can be created from lists, dictionaries, scalar values, etc.
It is built on top of the NumPy library which means that a lot of the structures Example: Creating a series using the Pandas Library.
of NumPy are used or replicated in Pandas.
The data produced by Pandas is often used as input for plotting functions import pandas as pd
in Matplotlib, statistical analysis in SciPy, and machine learning import numpy as np
algorithms in Scikit-learn.
You must be wondering, Why should you use the Pandas Library. Python‘s # Creating empty series
Pandas library is the best tool to analyze, clean, and manipulate data. ser = pd.Series()
Here is a list of things that we can do using Pandas. print("Pandas Series: ", ser)
 Data set cleaning, merging, and joining.
 Easy handling of missing data (represented as NaN) in floating point as # simple array
well as non-floating point data. data = np.array(['g', 'e', 'e', 'k', 's'])
 Columns can be inserted and deleted from DataFrame and higher-
dimensional objects. ser = pd.Series(data)
 Powerful group by functionality for performing split-apply-combine print("Pandas Series:\n", ser)
operations on data sets. Output
 Data Visualization. Pandas Series: Series([], dtype: float64)
Pandas Series:
Data Structures in Pandas Library 0 g
Pandas generally provide two data structures for manipulating data. They are: 1 e
 Series 2 e
 DataFrame 3 k
Pandas Series 4 s
A Pandas Series is a one-dimensional labeled array capable of holding data of dtype: object
any type (integer, string, float, Python objects, etc.). The axis labels are
collectively called indexes. Pandas DataFrame
The Pandas Series is nothing but a column in an Excel sheet. Labels need not Pandas DataFrame is a two-dimensional data structure with labeled axes (rows
be unique but must be of a hashable type. and columns).
The object supports both integer and label-based indexing and provides a host Creating DataFrame
of methods for performing operations involving the index. Pandas DataFrame is created by loading the datasets from existing storage
(which can be a SQL database, a CSV file, or an Excel file).
Pandas DataFrame can be created from lists, dictionaries, a list of dictionaries,
etc.
Example: Creating a DataFrame Using the Pandas Library
import pandas as pd

# Calling DataFrame constructor


df = pd.DataFrame()
print(df)

25 | P a g e 26 | P a g e
Vandana Rajput Vandana Rajput

# list of strings # Observe the result


lst = ['Geeks', 'For', 'Geeks', 'is', 'portal', 'for', 'Geeks'] print(df)

# Calling DataFrame constructor on list


df = pd.DataFrame(lst) Output:
print(df) Name Height Age Qualification
0 Jai 5.1 21 Msc
Output: 1 Princi 6.2 23 MA
Empty DataFrame 2 Gaurav 5.1 24 Msc
Columns: [] 3 Anuj 5.2 21 Msc
Index: []
0
Adding Columns to Pandas DataFrame using Dataframe.assign()
0 Geeks
1 For This method will create a new dataframe with a new column added to the old
2 Geeks dataframe.
3 is
4 portal import pandas as pd
5 for
6 Geeks # Define a dictionary containing Students data
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
Adding new column to existing DataFrame in Pandas 'Height': [5.1, 6.2, 5.1, 5.2],
Adding new columns to an existing DataFrame is a fundamental task in data 'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
analysis using Pandas. It allows you to enrich your data with additional
information and facilitate further analysis and manipulation. This article will
explore various methods for adding new columns, including simple # Convert the dictionary into DataFrame
assignment, the insert() method, the assign() method. df = pd.DataFrame(data)

Add a New Column to an Existing Datframe using DataFrame.insert() # Using 'Address' as the column name and equating it to the list
df2 = df.assign(address=['Delhi', 'Bangalore', 'Chennai', 'Patna'])
It gives the freedom to add a column at any position we like and not just at the
end. It also provides different options for inserting the column values.
print(df2)
import pandas as pd
Output:
# Define a dictionary containing Students data
Name Height Qualification address
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
0 Jai 5.1 Msc Delhi
'Height': [5.1, 6.2, 5.1, 5.2],
1 Princi 6.2 MA Bangalore
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
2 Gaurav 5.1 Msc Chennai
3 Anuj 5.2 Msc Patna
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)

# Using DataFrame.insert() to add a column


df.insert(2, "Age", [21, 23, 24, 21], True)

27 | P a g e 28 | P a g e

Vandana Rajput Vandana Rajput

Pandas Add Column to DataFrame using a Dictionary # and equating it to the list
We can use a Python dictionary to add a new column in pandas DataFrame. df['Address'] = address
Use an existing column as the key values and their respective values will be
the values for a new column. print(df)
Import pandas package
import pandas as pd Output:
Name Height Qualification Address
# Define a dictionary containing Students data 0 Jai 5.1 Msc Delhi
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'], 1 Princi 6.2 MA Bangalore
'Height': [5.1, 6.2, 5.1, 5.2], 2 Gaurav 5.1 Msc Chennai
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']} 3 Anuj 5.2 Msc Patna

# Define a dictionary with key values of In Python Delete rows/columns from DataFrame using Pandas.drop()
# an existing column and their respective Python is a great language for doing data analysis, primarily because of the
# value pairs as the # values for our new column. fantastic ecosystem of data-centric Python packages. Pandas is one of those
address = {'Delhi': 'Jai', 'Bangalore': 'Princi', packages which makes importing and analyzing data much easier.
'Patna': 'Gaurav', 'Chennai': 'Anuj'}
Python Drop Function in Pandas
# Convert the dictionary into DataFrame Pandas provide data analysts with a way to delete and filter data frames
df = pd.DataFrame(data) using dataframe.drop() the method. Rows or columns can be removed using
an index label or column name using this method.
# Provide 'Address' as the column name Deleting Rows and Columns from Pandas DataFrame
df['Address'] = address Below are some ways and example by which we can delete a row in Excel
using Pandas in Python.
# Observe the output Dropping Rows in Pandas by Index Label
print(df) In this code, A list of index labels is passed and the rows corresponding to
those labels are dropped using .drop() method.
Output: Example:
Name Height Qualification Address # importing pandas module
0 Jai 5.1 Msc Delhi import pandas as pd
1 Princi 6.2 MA Bangalore
2 Gaurav 5.1 Msc Chennai # making data frame from csv file
3 Anuj 5.2 Msc Patna data = pd.read_csv("nba.csv", index_col="Name")
print(data.head(5))
Adding a New Column to a Pandas DataFrame using List
In this example, Pandas add new columns from list ―Address‖ to an existing
Pandas DataFrame using a dictionary and a list.
Python

# Declare a list that is to be converted into a column


address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']

# Using 'Address' as the column name


29 | P a g e 30 | P a g e
Vandana Rajput Vandana Rajput

Delete a CSV Column in Python Method 1: Using pandas library


The comma-separated values (CSV) file is a delimited text file that uses
commas for individual values. Each line of the file is a data record in CSV. Python is a great language for doing data analysis, primarily because of the
This format used for tabular data, rows, and columns, exactly like a fantastic ecosystem of data-centric python packages. Pandas is one of those
spreadsheet. The CSV file stores data in rows and the values in each row are packages and makes importing and analyzing data much easier. Pandas consist
separated with a comma(separator), also known as a delimiter. of a drop function that is used in removing rows or columns from the CSV
There are 2 ways to remove a column entirely from a CSV in python. Let us files. Pandas Pop() method is common in most of the data structures but the
now focus on the techniques : pop() method is a little different from the rest. In a stack, pop doesn‘t require
any parameters, it pops the last element every time. But the pandas pop
1. With pandas library — drop() or pop()
method can take input of a column from a data frame and pop that directly.
2. Without pandas library
Example 1: Using drop()
A simple CSV file is used i.e input.csv
data.drop( labels=None, axis=0, index=None, columns=None, level=None,
inplace=False,errors='raise')
id day month year item_quantity Name
1. Import Pandas
2. Read CSV File
1 12 3 2020 12 Oliver
3. Use drop() function for removing or deleting rows or columns from the
CSV files
2 13 3 2020 45 Henry 4. Print Data

3 14 3 2020 8 Benjamin
# import pandas with shortcut 'pd'
4 15 3 2020 23 John
import pandas as pd
5 16 3 2020 31 Camili

6 17 3 2020 40 Rheana
# read_csv function which is used to read the required CSV file
7 18 3 2020 55 Joseph
data = pd.read_csv('input.csv')
8 19 3 2020 13 Raj

9 20 3 2020 29 Elias
# display
10 21 3 2020 19 Emily
print("Original 'input.csv' CSV Data: \n")

print(data)

31 | P a g e 32 | P a g e

Vandana Rajput Vandana Rajput

Example 2: Using pop()


We can use the panda pop () method to remove columns from CSV by naming
the column as an argument.
# drop function which is used in removing or deleting rows or columns from the
CSV files 𝑑𝑎𝑡𝑎.𝑝𝑜𝑝(′𝑐𝑜𝑙𝑢𝑚𝑛−𝑛𝑎𝑚𝑒′)data.pop(′column−name′)
1. Import Pandas
2. Read CSV File
data.drop('year', inplace=True, axis=1)
3. Use pop() function for removing or deleting rows or columns from the CSV
files
4. Print Data

# display

print("\nCSV Data after deleting the column 'year':\n") # import pandas with shortcut 'pd'

print(data) import pandas as pd

# read_csv function which is used to read the required CSV file

Output: data = pd.read_csv('input.csv')

# display

print("Original 'input.csv' CSV Data: \n")

print(data)

# pop function which is used in removing or deleting columns from the


CSV files

data.pop('year')

33 | P a g e 34 | P a g e
Vandana Rajput Vandana Rajput

# display Python Tkinter


Python offers multiple options for developing GUI (Graphical User Interface).
print("\nCSV Data after deleting the column 'year':\n") Out of all the GUI methods, tkinter is the most commonly used method. It is a
standard Python interface to the Tk GUI toolkit shipped with Python. Python
Tkinter is the fastest and easiest way to create GUI applications. Creating a
print(data) GUI using Tkinter is an easy task.
To create a Tkinter Python app, you follow these basic steps:
Output: 1. Import the tkinter module: This is done just like importing any other
module in Python. Note that in Python 2.x, the module is named ‗Tkinter‘,
while in Python 3.x, it is named ‗tkinter‘.
2. Create the main window (container): The main window serves as the
container for all the GUI elements you‘ll add later.
3. Add widgets to the main window: You can add any number of widgets
like buttons, labels, entry fields, etc., to the main window to design the
interface as desired.
4. Apply event triggers to the widgets: You can attach event triggers to the
widgets to define how they respond to user interactions.

Create First Tkinter GUI Application


There are two main methods used which the user needs to remember while
creating the Python application with GUI.
Tk()
To create a main window, tkinter offers a method
‗Tk(screenName=None, baseName=None, className=‘Tk‘, useTk=1)‘. To
change the name of the window, you can change the className to the desired
one. The basic code used to create the main window of the application is:
mainloop()
There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the
application, wait for an event to occur, and process the event as long as the
window is not closed.
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
Output

35 | P a g e 36 | P a g e

Vandana Rajput Vandana Rajput

Label Display static text or images.

It is used to implement one-of-many selection as it allows


RadioButton
only one option to be selected

Checkbutton Create checkboxes for boolean options.


Tkinter Widget
What are Widgets in Tkinter? ListBox Display a list of items for selection.
In Tkinter, a widget is essentially a graphical component that the user can
interact with. They can range from simple elements like buttons and labels to
more complex ones like text entry fields, listboxes, and canvases. Each widget Scrollbar Add scrollbars to widgets like Listbox.
serves a specific purpose and can be customized to fit the design and
functionality requirements of your application.
How Do Tkinter Widgets Work? Menu It is used to create all kinds of menu used by an application
Each widget in Tkinter is an instance of a specific class defined in the Tkinter
Module. These classes provide methods and attributes that allow you to
configure the widget‘s appearance, behavior, and functionality. Widgets are Canvas Draw shapes, lines, text, and images.
typically added to the application‘s window or frames using layout managers
like pack(), grid(), or place(), which determine their position and size within
the interface.
1. Label
It refers to the display box where you can put any text or image which can be
There are a number of widgets which you can put in your tkinter application. updated any time as per the code. The general syntax is:
Some of the major widgets are explained below: w=Label(master, option=value)
Tkinter Widget Basics master is the parameter used to represent the parent window.
Tkinter supports the below mentioned core widgets –
Label Display static text or images.
from tkinter import *
root = Tk()
w = Label(root, text='United group of college')
Button It is used to add buttons to your application
w.pack()
root.mainloop()
Entry It is used to input single line text entry from user
2. Button
To add a button in your application, this widget is used. The general syntax is:
Frame It is used as container to hold and organize the widgets
w=Button(master, option=value)

37 | P a g e 38 | P a g e
Vandana Rajput Vandana Rajput

master is the parameter used to represent the parent window. There are number There are number of options which are used to change the format of this
of options which are used to change the format of the Buttons. Number of widget. Number of options can be passed as parameters separated by commas.
options can be passed as parameters separated by commas. Some of them are listed below.
import tkinter as tk Python

r = tk.Tk() from tkinter import *


r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy) master = Tk()
button.pack() var1 = IntVar()
r.mainloop() Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
3. Entry mainloop()
It is used to input the single line text entry from the user.. For multi-line text Output
input, Text widget is used. The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window. There are number
of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are
listed below.
Python
5. RadioButton
from tkinter import *
It is used to offer multi-choice option to the user. It offers several options to
the user and the user has to choose one option. The general syntax is:
master = Tk()
w = RadioButton(master, option=value)
Label(master, text='First Name').grid(row=0)
There are number of options which are used to change the format of this
Label(master, text='Last Name').grid(row=1)
widget. Number of options can be passed as parameters separated by commas.
e1 = Entry(master)
Some of them are listed below.
e2 = Entry(master)
Python
e1.grid(row=0, column=1)
e2.grid(row=1, column=1) from tkinter import *
mainloop()
Output root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()
4. CheckButton Output
To select any number of options by displaying a number of options to a user as
toggle buttons. The general syntax is:
w = CheckButton(master, option=value)

39 | P a g e 40 | P a g e

Vandana Rajput Vandana Rajput

6. Listbox
It offers a list to the user from which the user can accept any number of root = Tk()
options. The general syntax is: scrollbar = Scrollbar(root)
w = Listbox(master, option=value) scrollbar.pack(side=RIGHT, fill=Y)
master is the parameter used to represent the parent window. mylist = Listbox(root, yscrollcommand=scrollbar.set)
There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by commas. for line in range(100):
Some of them are listed below. mylist.insert(END, 'This is line number' + str(line))
Python
mylist.pack(side=LEFT, fill=BOTH)
from tkinter import * scrollbar.config(command=mylist.yview)
mainloop()
top = Tk() Output
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()
Output

8. Menu
It is used to create all kinds of menus used by the application. The general
syntax is:
w = Menu(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of this
widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
Python
7. Scrollbar
from tkinter import *
It refers to the slide controller which will be used to implement listed widgets.
The general syntax is:
root = Tk()
w = Scrollbar(master, option=value)
menu = Menu(root)
master is the parameter used to represent the parent window.
root.config(menu=menu)
There are number of options which are used to change the format of the
filemenu = Menu(menu)
widget. Number of options can be passed as parameters separated by commas.
menu.add_cascade(label='File', menu=filemenu)
Some of them are listed below.
filemenu.add_command(label='New')
Python
filemenu.add_command(label='Open...')
from tkinter import * filemenu.add_separator()

41 | P a g e 42 | P a g e
Vandana Rajput Vandana Rajput

filemenu.add_command(label='Exit', command=root.quit) # Create a Combobox widget


helpmenu = Menu(menu) combo_box = ttk.Combobox(root, values=["Option 1", "Option 2", "Option 3"])
menu.add_cascade(label='Help', menu=helpmenu) combo_box.pack(pady=5)
helpmenu.add_command(label='About')
mainloop() # Set default value
Output combo_box.set("Option 1")

# Bind event to selection


combo_box.bind("<<ComboboxSelected>>", on_select)

root.mainloop()
Output

9. Combobox 10. Scale


Combobox widget is created using the ttk.Combobox class from the tkinter.ttk It is used to provide a graphical slider that allows to select any value from that
module. The values for the Combobox are specified using the values scale. The general syntax is:
parameter. The default value is set using the set method. An event handler w = Scale(master, option=value)master is the parameter used to represent the
function on_select is bound to the Combobox using the bind method, which parent window.
updates a label with the selected item whenever an item is selected. There are number of options which are used to change the format of the
Python widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
import tkinter as tk Python
from tkinter import ttk
from tkinter import *
def on_select(event):
selected_item = combo_box.get() master = Tk()
label.config(text="Selected Item: " + selected_item) w = Scale(master, from_=0, to=42)
w.pack()
root = tk.Tk() w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
root.title("Combobox Example") w.pack()
mainloop()
# Create a label Output
label = tk.Label(root, text="Selected Item: ")
label.pack(pady=10)

43 | P a g e 44 | P a g e

Vandana Rajput Vandana Rajput

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the
widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
Python

from tkinter import *

main = Tk()
11. TopLevel ourMessage = 'This is our Message'
messageVar = Message(main, text=ourMessage)
This widget is directly controlled by the window manager. It don‘t need any
messageVar.config(bg='lightgreen')
parent window to work on.The general syntax is:
messageVar.pack()
w = TopLevel(master, option=value)
main.mainloop()
There are number of options which are used to change the format of the
Output
widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
Python

from tkinter import *


13. MenuButton
root = Tk() It is a part of top-down menu which stays on the window all the time. Every
root.title('GfG') menubutton has its own functionality. The general syntax is:
top = Toplevel() w = MenuButton(master, option=value)
top.title('Python') master is the parameter used to represent the parent window.
top.mainloop() There are number of options which are used to change the format of the
Output widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
Python

from tkinter import *

top = Tk()
mb = Menubutton ( top, text = "GfG")
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.menu.add_checkbutton ( label ='Contact', variable = cVar )
12. Message mb.menu.add_checkbutton ( label = 'About', variable = aVar )
It refers to the multi-line and non-editable text. It works same as that of Label. mb.pack()
The general syntax is: top.mainloop()
w = Message(master, option=value) Output

45 | P a g e 46 | P a g e
Vandana Rajput Vandana Rajput

14. Progressbar
Tkinter application with a Progressbar widget and a button to start the
progress. When the button is clicked, the progressbar fills up to 100% over a
short period, simulating a task that takes time to complete. 15. SpinBox
Python It is an entry of ‗Entry‘ widget. Here, value can be input by selecting a fixed
value of numbers.The general syntax is:
import tkinter as tk w = SpinBox(master, option=value)
from tkinter import ttk There are number of options which are used to change the format of the
import time widget. Number of options can be passed as parameters separated by commas.
Some of them are listed below.
def start_progress(): Python
progress.start()
from tkinter import *
# Simulate a task that takes time to complete
for i in range(101): master = Tk()
# Simulate some work w = Spinbox(master, from_=0, to=10)
time.sleep(0.05) w.pack()
progress['value'] = i mainloop()
# Update the GUI Output:
root.update_idletasks()
progress.stop()

root = tk.Tk() 16. Text


root.title("Progressbar Example") To edit a multi-line text and format the way it has to be displayed. The general
syntax is:
# Create a progressbar widget w =Text(master, option=value)
progress = ttk.Progressbar(root, orient="horizontal", length=300, There are number of options which are used to change the format of the text.
mode="determinate") Number of options can be passed as parameters separated by commas. Some
progress.pack(pady=20) of them are listed below.
from tkinter import *
# Button to start progress
start_button = tk.Button(root, text="Start Progress", command=start_progress) root = Tk()
start_button.pack(pady=10) T = Text(root, height=2, width=30)
T.pack()
root.mainloop() T.insert(END, 'Hello I m here\nBEST WEBSITE\n')
Output mainloop()

47 | P a g e 48 | P a g e

Vandana Rajput Vandana Rajput

Python Tkinter Geometry 8. bluebutton.pack( side = TOP )


9. blackbutton = Button(parent, text = "Green", fg = "red")
The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry 10.blackbutton.pack( side = BOTTOM)
methods. 11.parent.mainloop()

1. The pack() method


2. The grid() method
3. The place() method

Python Tkinter pack() method


Output:
The pack() widget is used to organize widget in the block. The positions
widgets added to the python application using the pack() method can be
controlled by using the various options specified in the method call.

However, the controls are less and widgets are generally added in the less
organized manner.
Python Tkinter grid() method
The syntax to use the pack() is given below.
The grid() geometry manager organizes the widgets in the tabular form. We can
Syntax specify the rows and columns as the options in the method call. We can also
widget.pack(options) specify the column span (width) or rowspan(height) of a widget.

A list of possible options that can be passed in pack() is given below. This is a more organized way to place the widgets to the python application.
The syntax to use the grid() is given below.
o expand: If the expand is set to true, the widget expands to fill any space.
Syntax
o Fill: By default, the fill is set to NONE. However, we can set it to X or Y
widget.grid(options)
to determine whether the widget contains any extra space.
o size: it represents the side of the parent to which the widget is to be A list of possible options that can be passed inside the grid() method is given
placed on the window. below.

Example Column
# !/usr/bin/python3 The column number in which the widget is to be placed. The leftmost column is
represented by 0.
1. from tkinter import *
Columnspan
2. parent = Tk() The width of the widget. It represents the number of columns up to which, the
3. redbutton = Button(parent, text = "Red", fg = "red") column is expanded.
4. redbutton.pack( side = LEFT) ipadx, pady
5. greenbutton = Button(parent, text = "Black", fg = "black") It represents the number of pixels to pad the widget inside the widget's border.
6. greenbutton.pack( side = RIGHT ) padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
7. bluebutton = Button(parent, text = "Blue", fg = "blue")
49 | P a g e 50 | P a g e
Vandana Rajput Vandana Rajput

row o Anchor: It represents the exact position of the widget within the
The row number in which the widget is to be placed. The topmost row is container. The default value (direction) is NW (the upper left corner)
represented by 0.
rowspan o bordermode: The default value of the border type is INSIDE that refers
The height of the widget, i.e. the number of the row up to which the widget is to ignore the parent's inside the border. The other option is OUTSIDE.
expanded. o height, width: It refers to the height and width in pixels.
Sticky
o relheight, relwidth: It is represented as the float between 0.0 and 1.0
If the cell is larger than a widget, then sticky is used to specify the position of
the widget inside the cell. It may be the concatenation of the sticky letters indicating the fraction of the parent's height and width.
representing the position of the widget. It may be N, E, W, S, NE, NW, NS, o relx, rely: It is represented as the float between 0.0 and 1.0 that is the
EW, ES. offset in the horizontal and vertical direction.
Example o x, y: It refers to the horizontal and vertical offset in the pixels.
1. # !/usr/bin/python3
Example
2. from tkinter import *
1. # !/usr/bin/python3
3. parent = Tk()
2. from tkinter import *
4. name = Label(parent,text = "Name").grid(row = 0, column = 0)
3. top = Tk()
5. e1 = Entry(parent).grid(row = 0, column = 1)
4. top.geometry("400x250")
6. password = Label(parent,text = "Password").grid(row = 1, column = 0)
5. name = Label(top, text = "Name").place(x = 30,y = 50)
7. e2 = Entry(parent).grid(row = 1, column = 1)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
8. submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
7. password = Label(top, text = "Password").place(x = 30, y = 130)
9. parent.mainloop()
8. e1 = Entry(top).place(x = 80, y = 50)
Output: 9. e2 = Entry(top).place(x = 80, y = 90)
10.e3 = Entry(top).place(x = 95, y = 130)
11.top.mainloop()

Output:

Python Tkinter place() method

The place() geometry manager organizes the widgets to the specific x and y
coordinates.

Syntax
widget.place(options)

A list of possible options is given below.

51 | P a g e 52 | P a g e

Vandana Rajput Vandana Rajput

# update the expression by using set method


equation.set(expression)

# Function to evaluate the final expression


def equalpress():
# Try and except statement is used
# for handling the errors like zero
# division error etc.

# Put that code inside the try block


# which may generate the error
try:

global expression
Simple GUI calculator using Tkinter
Python offers multiple options for developing a GUI (Graphical User
# eval function evaluate the expression
Interface). Out of all the GUI methods, Tkinter is the most commonly used
# and str function convert the result
method. It is a standard Python interface to the Tk GUI toolkit shipped with
# into string
Python. Python with Tkinter outputs the fastest and easiest way to create GUI
total = str(eval(expression))
applications. Creating a GUI using Tkinter is an easy task.
To create a Tkinter: equation.set(total)
1. Importing the module – tkinter
# initialize the expression variable
2. Create the main window (container)
# by empty string
3. Add any number of widgets to the main window
expression = ""
4. Apply the event Trigger on the widgets.
# if error is generate then handle
from tkinter import *
# by the except block
except:
# globally declare the expression variable
expression = ""
equation.set(" error ")
expression = ""
# Function to update expression
# in the text entry box
# Function to clear the contents
def press(num):
# of text entry box
# point out the global expression variable
def clear():
global expression
global expression
expression = ""
# concatenation of string
equation.set("")
expression = expression + str(num)

53 | P a g e 54 | P a g e
Vandana Rajput Vandana Rajput

# Driver code button4 = Button(gui, text=' 4 ', fg='black', bg='medium violet red',
if __name__ == "__main__": command=lambda: press(4), height=1, width=7)
# create a GUI window button4.grid(row=3, column=0)
gui = Tk()
button5 = Button(gui, text=' 5 ', fg='black', bg='medium violet red',
# set the background colour of GUI window command=lambda: press(5), height=1, width=7)
gui.configure(background="black") button5.grid(row=3, column=1)

# set the title of GUI window button6 = Button(gui, text=' 6 ', fg='black', bg='medium violet red',
gui.title(" Calculator") command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
# set the configuration of GUI window
gui.geometry("300x150") button7 = Button(gui, text=' 7 ', fg='black', bg='medium violet red',
command=lambda: press(7), height=1, width=7)
# StringVar() is the variable class button7.grid(row=4, column=0)
# we create an instance of this class
equation = StringVar() button8 = Button(gui, text=' 8 ', fg='black', bg='medium violet red',
command=lambda: press(8), height=1, width=7)
# create the text entry box for button8.grid(row=4, column=1)
# showing the expression .
expression_field = Entry(gui, textvariable=equation) button9 = Button(gui, text=' 9 ', fg='black', bg='medium violet red',
command=lambda: press(9), height=1, width=7)
# grid method is used for placing button9.grid(row=4, column=2)
# the widgets at respective positions
# in table like structure . button0 = Button(gui, text=' 0 ', fg='black', bg='medium violet red',
expression_field.grid(columnspan=25, ipadx=100) command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
# create a Buttons and place at a particular
# location inside the root window . plus = Button(gui, text=' + ', fg='black', bg='medium violet red',
# when user press the button, the command or command=lambda: press("+"), height=1, width=7)
# function affiliated to that button is executed . plus.grid(row=2, column=3)
button1 = Button(gui, text=' 1 ', fg='black', bg='medium violet red',
command=lambda: press(1), height=1, width=7) minus = Button(gui, text=' - ', fg='black', bg='medium violet red',
button1.grid(row=2, column=0) command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
button2 = Button(gui, text=' 2 ', fg='black', bg='medium violet red',
command=lambda: press(2), height=1, width=7) multiply = Button(gui, text=' * ', fg='black', bg='medium violet red',
button2.grid(row=2, column=1) command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
button3 = Button(gui, text=' 3 ', fg='black', bg='medium violet red',
command=lambda: press(3), height=1, width=7) divide = Button(gui, text=' / ', fg='black', bg='medium violet red',
button3.grid(row=2, column=2) command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)

55 | P a g e 56 | P a g e

Vandana Rajput

equal = Button(gui, text=' = ', fg='black', bg='medium violet red',


command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)

clear = Button(gui, text='Clear', fg='black', bg='medium violet red',


command=clear, height=1, width=7)
clear.grid(row=5, column='1')

Decimal= Button(gui, text='.', fg='black', bg='medium violet red',


command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()

57 | P a g e

You might also like