python all units
python all units
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 versatile and can be used to create many different things. Following are important characteristics of Python Programming −
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
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
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
Example
3|Page 4|Page
Vandana Rajput Vandana Rajput
% Modulus b%a=0
Operator Example Same As
+= a += 30 a = a + 30
// Floor Division 9//2 = 4
-= a -= 15 a = a - 15
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
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:
Example:
T T T
age > 16 and marks > 80
x=5
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
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
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
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
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
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
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
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.
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:
2. Write a program that prompts the user to enter two integers and display
their sum on the screen.
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
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: "))
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")
1. n = 5
2. for i in range(n):
3. if i < 2:
4. i += 1
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
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’.
P if num % 2 == 0:
print("Even")
P else:
L print("Odd")
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
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]
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
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
Output:
You can access tuple items by referring to the index number, inside square
brackets:
Output: Dictionaries are used to store data values in key: value pairs.
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.
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}
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
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
{}
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:
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
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: "))
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.
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
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
print("Factorial does not exist for negative numbers.") num = int(input("Enter a positive integer: "))
else: factor_sum = 0
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.
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.
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.
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='')
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)
Example
String Methods
To add a space between them, add a " ":
a = "Hello"
b = "World"
Method Description
c=a+""+b
print(c)
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):
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
partition() Returns a tuple where the string is parted into three parts
isdigit() Returns True if all characters in the string are digits
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
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)
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
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)
Example Example
Check if the string ends with punctuation sign (.): Remove spaces to the left of the string:
Example Split a string into a list where each word is a list item:
x = txt.index("welcome") 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)
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']
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")
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
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?:
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
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
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
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
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")
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
4|Page 5|Page
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")
2. Write a program that reads and display all of the numbers stored in the file numbers.txt and
calculates their total.
total = 0
6|Page 7|Page
Vandana Rajput Vandana Rajput
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()
8|Page 9|Page
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!!
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.
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
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
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))
1|Page 2|Page
Vandana Rajput Vandana Rajput
3|Page 4|Page
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
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
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:
Example Example
Get the second element from the following array. Slice elements from the beginning to index 4 (not included):
Get third and fourth elements from the following array and add them.
import numpy as np
NumPy Array Copy vs 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
11 | P a g e 12 | P a g e
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]
15 | P a g e 16 | P a g e
plt.legend()
plt.show()
19 | P a g e 20 | P a g e
# 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))
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR', 'MERCEDES']
# Wedge properties
wp = {'linewidth': 1, 'edgecolor': "green"}
23 | P a g e 24 | P a g e
25 | P a g e 26 | P a g e
Vandana Rajput Vandana Rajput
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)
27 | P a g e 28 | P a g e
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
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
# display
print("\nCSV Data after deleting the column 'year':\n") # import pandas with shortcut 'pd'
# display
print(data)
data.pop('year')
33 | P a g e 34 | P a g e
Vandana Rajput Vandana Rajput
35 | P a g e 36 | P a g e
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
39 | P a g e 40 | P a g e
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
root.mainloop()
Output
43 | P a g e 44 | P a g e
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
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()
47 | P a g e 48 | P a g e
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:
The place() geometry manager organizes the widgets to the specific x and y
coordinates.
Syntax
widget.place(options)
51 | P a g e 52 | P a g e
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
57 | P a g e