0% found this document useful (0 votes)
12 views80 pages

PP

Uploaded by

kumar108
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views80 pages

PP

Uploaded by

kumar108
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 80

1

Q. Explain various data type in python with the help of


diagram
Data Types in Python: An Overview
A data type in Python is a classification of specific types of data
by a certain value or certain types of mathematical or logical
operations. In this comprehensive Python Tutorial article, we’ll
explore the Data types in Python with examples explaining
what each one is used for and how to know where which one is
suitable. Whether you're new to coding or an experienced
programmer looking for Python training, this article has
something for everyone!
What is a Data Type in Python?
The way that data items are categorized or classified is known
as their data type. It stands for the type of value that indicates
the types of operations that can be carried out on a specific set
of data.
Types of Data Types in Python
Python has various built-in data types which will be discussed
in this article:

Data
Classes Description
Types

int, float,
Numeric holds numeric values
complex

holds sequence of
String str
characters
2

list, tuple,
Sequence holds collection of items
range

holds data in key-value


Mapping dict
pair form

holds either True or


Boolean bool
False

hold collection of
Set set, frozenset
unique items

Numeric
Numeric values are stored in numbers. The whole number,
float, and complex qualities have a place with a Python
Numbers datatype. Python offers the type() function to
determine a variable's data type. The instance () capability is
utilized to check whether an item has a place with a specific
class.
When a number is assigned to a variable, Python generates
Number objects. For instance,
1.a = 5
3

2.print("The type of a", type(a))


3.
4.b = 40.5
5.print("The type of b", type(b))
6.
7.c = 1+3j
8.print("The type of c", type(c))
9.print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.
o Int: Whole number worth can be any length, like numbers
10, 2, 29, - 20, - 150, and so on. An integer can be any
length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902,
15.2, etc. It can be accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair,
i.e., x + iy, where x and y signify the genuine and non-
existent parts separately. The complex numbers like 2.14j,
2.0 + 2.3j, etc.

Sequence Type
String
4

The sequence of characters in the quotation marks can be used


to describe the string. A string can be defined in Python using
single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python
gives worked-in capabilities and administrators to perform tasks
in the string.
When dealing with strings, the operation "hello"+" python"
returns "hello python," and the operator + is used to combine
two strings.
Because the operation "Python" *2 returns "Python," the
operator * is referred to as a repetition operator.
The Python string is demonstrated in the following example.
Example - 1
1.str = "string using double quotes"
2.print(str)
3.s = '''''A multiline
4.string'''
5.print(s)
Output:
string using double quotes
A multiline
string
Look at the following illustration of string handling.
Example - 2
1.str1 = 'hello javatpoint' #string str1
2.str2 = ' how are you' #string str2
5

3.print (str1[0:2]) #printing first two character using slice operato


r
4.print (str1[4]) #printing 4th character of the string
5.print (str1*2) #printing the string twice
6.print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List
Lists in Python are like arrays in C, but lists can contain data of
different types. The things put away in the rundown are isolated
with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators.
Like how they worked with strings, the list is handled by the
concatenation operator (+) and the repetition operator (*).
Look at the following example.
Example:
1.list1 = [1, "hi", "Python", 2]
2.#Checking type of given list
3.print(type(list1))
4.
5.#Printing the list1
6.print (list1)
7.
6

8.# List slicing


9.print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple
In many ways, a tuple is like a list. Tuples, like lists, also
contain a collection of items from various data types. A
parenthetical space () separates the tuple's components from
one another.
Because we cannot alter the size or value of the items in a tuple,
it is a read-only data structure.
Let's look at a straightforward tuple in action.
Example:
7

1.tup = ("hi", "Python", 2)


2.# Checking type of tup
3.print (type(tup))
4.
5.#Printing the tuple
6.print (tup)
7.
8.# Tuple slicing
9.print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
8

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary
A dictionary is a key-value pair set arranged in any order. It
stores a specific value for each key, like an associative array or
a hash table. Value is any Python object, while the key can hold
any primitive data type.
The comma (,) and the curly braces are used to separate the
items in the dictionary.
Look at the following example.
1.d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
2.
3.# Printing dictionary
4.print (d)
5.
6.# Accesing value using keys
7.print("1st name is "+d[1])
8.print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())
Output:
1st name is Jimmy
2nd name is mike
9

{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}


dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean
True and False are the two default values for the Boolean type.
These qualities are utilized to decide the given assertion valid
or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be
represented by any value that is not zero.
Look at the following example.
1.# Python program to check the boolean type
2.print(type(True))
3.print(type(False))
4.print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set
The data type's unordered collection is Python Set. It is iterable,
mutable(can change after creation), and has remarkable
components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of
elements is passed through the curly braces and separated by a
comma to create the set or the built-in function set() is used to
create the set. It can contain different kinds of values.
10

Look at the following example.


1.# Creating Empty set
2.set1 = set()
3.
4.set2 = {'James', 2, 3,'Python'}
5.
6.#Printing Set value
7.print(set2)
8.
9.# Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Q. Write a python function to calculate the square root of a


number. The program accepts the number as an input from
the user.

Example: For positive numbers


11

# Python Program to calculate the square root

# Note: change this value for a different result


num = 8

# To take the input from the user


#num = float(input('Enter a number: '))

num_sqrt = num ** 0.5


print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
Run Code
Output

The square root of 8.000 is 2.828


In this program, we store the number in num and find the
square root using the ** exponent operator. This program
works for all positive real numbers. But for negative or
complex numbers, it can be done as follows.

Source code: For real or complex numbers


# Find square root of real or complex numbers
# Importing the complex math module
import cmath

num = 1+2j

# To take input from the user


#num = eval(input('Enter a number: '))
12

num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}
+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
Run Code
Output

The square root of (1+2j) is 1.272+0.786j


In this program, we use the sqrt() function in the cmath
(complex math) module.

Note: If we want to take complex number as input directly, like


3+4j, we have to use the eval() function instead of float().

The eval() method can be used to convert complex numbers as


input to the complex objects in Python. To learn more, visit
Python eval() function.

Example: C sqrt() Function


#include <math.h>
#include <stdio.h>

int main() {
double number, squareRoot;

printf("Enter a number: ");


13

scanf("%lf", &number);

// computing the square root


squareRoot = sqrt(number);

printf("Square root of %.2lf = %.2lf", number, squareRoot);

return 0;
}

Python math.sqrt() method Example 3


In the following program, we have read a number form the user
and find the square root.

1. Using math.sqrt() method


The sqrt() function is an inbuilt function that returns the square
root of any number. Following are the steps to find the square
root of a number.
1.Start the program
2.Define any number whose square root to be found.
3.Invoke the sqrt() function and pass the value that you have
defined in step 2 and store the result in a variable.
4.Print the square root.
5.Terminate the program.
14

Code
1.# import math module
2.import math
3.a = int(input(" Enter a number to get the Square root "))
4.# Use math.sqrt() function and pass the variable a.
5.result = math.sqrt(a)
6.print(" Square root of the number is ", result)
Output:
Enter a number to get the Square root: 25
Square root of the number is: 5.0

Code
1.# import NumPy module
2.import numpy as np
3.# define an array of numbers
4.array_nums = np.array([ 1, 4, 9, 16, 25 ])
5.# use np.sqrt() function and pass the array
6.result = np.sqrt(array_nums)
7.print(" Square roots of the given array are: ", result)
Output:
Square roots of the given array are: [ 1. 2. 3. 4. 5. ]

Q. Explain various operator and operands in python


15

Operators and Operands in Python


Operators refer to special symbols that perform operations on
values and variables. Furthermore, the operands in python, one
of the programming languages, refer to the values on which the
operator operates. Most noteworthy, operators can carry out
arithmetic, relational, and logical operations.

Arithmetic Operators in Python


The use of arithmetic operators and operands in python takes
place to perform mathematical operations like addition,
subtraction, multiplication and division.
There are 7 arithmetic operators in Python:

 Addition
 Subtraction
 Multiplication
 Division
 Modulus
 Exponentiation
 Floor division

Addition Operator: In Python, the additional operator is +.


Furthermore, its use takes place to add 2 values.

Example:

Copy Code
16

val1 = 2

val2 = 3

# using the addition operator

res = val1/val2

print(res)
Output

Copy Code

5
Subtraction Operator: In Python, the subtraction operator is –.
Furthermore, its use takes place to subtract the second value
from the first value.

Example :

Copy Code

val1 = 2

val2 = 3

# using the subtraction operator


17

res = val1 - val2

# using the subtraction operator

res = val1 - val2

print(res)
Output :

Copy Code

-1
Multiplication Operator: In Python, the multiplication operator is
*. Furthermore, its use takes place to find the product of 2
values.
Example:

Copy Code

Val1 = 2

Val2 = 3

# using the multiplication operator

res = val1 * val2

print(res)
18

Output :

Copy Code

6
Browse more Topics Under Variables, Expressions and
Statements
Values, Variables and Keywords
Operator Precedence
Expressions and Statement
Taking Input and Displaying Output
Putting Comments
Division Operator: In Python, / represents the division operator.
Furthermore, its use takes place to find the quotient when the
division of the first operand takes place by the second.
Example:

Copy Code

val1 = 3

val2 = 2

# using the division operator

res = val1 / val2

print(res)
19

Output :

Copy Code

1.5
Modulus Operator: In Python, % is the modulus operator.
Furthermore, its use takes place to find the remainder when the
division of the first operand happens by the second.
Example :

Copy Code

val1 = 3

val2 = 2

# using the modulus operator

res = val1 % val2

print(res)
Output :

Copy Code

1
20

Exponentiation Operator: In Python, ** is the exponentiation


operator. Furthermore, i to raise the first operand to power of
second.
Example :

Copy Code

val1 = 2

val2 = 3

# using the exponentiation operator

res = val1 ** val2

print(res)
Output :

Floor division: In Python, conducting of floor division takes


place by //. Furthermore, its use takes place to find the floor of
the quotient when the division of the first operand takes place by
the second.
Example :

Copy Code
21

val1 = 3

val2 = 2

# using the floor division

res = val1 // val2

print(res)
Output :

Copy Code

1
Relational Operators in Python
The use of relational operators and operands in python takes
place for comparing the values. Furthermore, it either returns
True or False in accordance with the condition. One may also
call these relational operators in python as comparison operators.

Operator – >

Description – Greater than: True if the left operand is greater


than the right

Syntax – x > y

Operator – <
22

Description – Less than: True if the left operand is less than the
right

Syntax – x < y

Operator – ==

Description – Equal to: True if both operands are equal

Syntax – x == y

Operator – !=

Description – Not equal to – True if operands are not equal

Syntax – x != y

Operator – >=

Description – Greater than or equal to: True if the left operand is


greater than or equal to the right

Syntax – x >= y

Operator – <=
23

Description – Less than or equal to: True if the left operand is


less than or equal to the right

Syntax – x <= y

Logical Operators in Pythons


In Python, the use of logical operators and operands in python
takes place on conditional statements (either True or False).
Furthermore, with logical operands in python, the performance
of Logical AND, Logical OR and Logical NOT operations takes
place. Let us understand logical operators in python with clarity.

Operator – and

Description – Logical AND: True if both the operands are true

Syntax – x and y

Operator – or

Description – Logical OR: True if either of the operands is true

Syntax – x or y

Operator – not

Description – Logical NOT: True if the operand is false


24

Syntax – not x

Q. Write a program to demonstrate the functioning of a


calculator.

A calculator performs arithmetic operations along with solving


equations, exponential and trigonometric operations.

But what if we told you that you can create a calculator program
in Python yourself!

If you know basic Python programming, we will show you to


create a graphical user interface from scratch that can perform
basic arithmetic operations.
So, without further delay, let’s get started.

Also, explore Conditional Statements in Python

Method -1: Simple Calculator Program in Python


# Basic Calculations
# Calculator Program in Python by using input() and format()
functions

#Promting input from the user

n1 = float(input("Enter the First Number: "))


25

n2 = float(input("Enter the Second Number: "))

#addition

print("{} + {} = ".format(n1, n2))


print(n1 + n2)

#subtraction

print("{} - {} = ".format(n1, n2))


print(n1 - n2)

#multiplication

print("{} * {} = ".format(n1, n2))


print(n1 * n2)

#division

print("{} / {} = ".format(n1, n2))


print(n1 / n2)

Output
Enter the first Number :3
Enter the Second Number :3
3.0 + 3.0 = 6.0
3.0 - 3.0 = 0.0
26

3.0 * 3.0 = 9.0


3.0 / 3.0 = 1.0

Explanation: In the above Program, we take two numeric values


(here, we are taking float data type), and we get all the outputs
(addition, subtraction, multiplication, and division) once we
input both numbers

Python Program to Make a Simple Calculator


Create a simple calculator which can perform basic arithmetic
operations like addition, subtraction, multiplication, or division
depending upon the user input. Approach :
User chooses the desired operation. Options 1, 2, 3, and 4 are
valid.
Two numbers are taken and an if…elif…else branching is used
to execute a particular section.
Using functions add(), subtract(), multiply() and divide()
evaluate respective operations.

# Python program for simple calculator

# Function to add two numbers


def add(num1, num2):
return num1 + num2
27

# Function to subtract two numbers


def subtract(num1, num2):
return num1 - num2

# Function to multiply two numbers


def multiply(num1, num2):
return num1 * num2

# Function to divide two numbers


def divide(num1, num2):
return num1 / num2

print("Please select operation -\n" \


"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")

# Take input from the user


select = int(input("Select operations form 1, 2, 3, 4 :"))

number_1 = int(input("Enter first number: "))


number_2 = int(input("Enter second number: "))

if select == 1:
print(number_1, "+", number_2, "=",
add(number_1, number_2))
28

elif select == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))

elif select == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))

elif select == 4:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input")

Output:

Please select operation -


1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 15
Enter second number : 14
15 + 14 = 29
29

Q. Explain chained and nested conditionals with the help of


suitable example

A "chained conditional" is a series of "if-elif" statements where


each condition is evaluated sequentially, only moving to the
next one if the previous condition is false, essentially creating a
ladder of possibilities; while a "nested conditional" is when one
"if" statement is placed inside another, allowing for more
complex checks based on multiple conditions being true
simultaneously.
Example of Chained Conditional:

Example of Chained Conditional:

grade = 85

if grade >= 90:

print("Excellent")

elif grade >= 80:

print("Good")

elif grade >= 70:


30

print("Average")

else:

print("Needs Improvement")

 Explanation: This code checks the grade and prints a


corresponding message based on the range it falls into. If the
grade is 90 or above, it prints "Excellent"; if not, it checks if it's
80 or above, then 70 or above, and finally prints "Needs
Improvement" if none of the previous conditions are met.
Example of Nested Conditional:
age = 20

driving_license = True

if age >= 18:

if driving_license:

print("You are eligible to drive")

else:
31

print("You need a driving license to drive")

else:

print("You are too young to drive")

 Explanation: This code first checks if the person is 18 or


older. If they are, it then checks if they have a driving
license; only if both conditions are true will it print "You are
eligible to drive."
Key Differences:
Flow:
In a chained conditional, only one condition is evaluated per
iteration, moving to the next "elif" if the current condition is
false. In a nested conditional, the inner "if" statement is only
evaluated if the outer "if" condition is true.
Complexity:
Chained conditionals are generally used for simple, mutually
exclusive choices, while nested conditionals are used for more
complex scenarios where multiple conditions need to be
checked together.

Q. Write a python program to count the even and odd


numbers in a series of numbers
32

In Python working with lists is a common task and one of the


frequent operations is counting how many even and odd
numbers are present in a given list.
The collections.Counter method is the most efficient for large
datasets, followed by the filter() and lambda approach for clean
and compact code.
Using a Simple Loop
This method is very straightforward and easy to understand. It
loops through the list and checks if each number is even or odd,
and increments the respective counters.
Python
# Creating a list of numbers
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Initializing counters for even and odd numbers


even = 0
odd = 0

for num in a:
# Checking if the number is even
if num % 2 == 0:
even += 1
else:
odd += 1

# Printing the results


print("Even numbers:", even)
33

print("Odd numbers:", odd)

Output
Even numbers: 4
Odd numbers: 5

Explanation: This approach simply iterates through the list,


checks for even or odd, and updates the respective counters
based on the condition

Using filter() and lambda


This method is efficient and concise,
using filter() with lambda functions to separate even and odd
numbers.It creates two lists: One for even numbers and another
for odd numbers, the counts the length of these lists

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Counting even numbers using filter and lambda


even_count = len(list(filter(lambda num: num % 2 == 0, a)))

# Counting odd numbers using filter and lambda


odd_count = len(list(filter(lambda num: num % 2 != 0, a)))

# Printing the results


print("Even numbers:", even_count)
print("Odd numbers:", odd_count)
34

Output
Even numbers: 4
Odd numbers: 5
 Explanation: The filter() function is used to extract even and

odd numbers separately from the list. The length of the


filtered lists gives the count of even and odd numbers.

Q. Built in function in python

Python Built-in Functions


The Python built-in functions are defined as the functions
whose functionality is pre-defined in Python. The python
interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are
several built-in functions in Python which are listed below:

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are


true

any() Returns True if any item in an iterable object is


35

true

ascii() Returns a readable version of an object. Replaces


none-ascii characters with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable,


otherwise False

chr() Returns a character from the specified Unicode


code

Q. format operator
36

format operator allows you to combine and format data from


parsed fields into a user-defined string. This can be useful for
making data in logs more human readable.
Here are some examples of format operators:
Python
The format operator in Python is %, which allows you to
replace parts of a string with data stored in variables. For
example, %d formats an integer, %g formats a floating-point
number, and %s formats a string.
Sumo Logic
The format operator in Sumo Logic allows you to format and
combine data from parsed fields. The syntax
is format(<formatSpecifier>, <field1>[, <field2>,
<field3>, ...]) as <field>.
IBM
The format operator in IBM converts SPL tuples into formatted
data. It can write data in many formats, such as line or bin.
You can learn more about string formatting in Python from
these resources:
 Learn Python.org: Offers a free interactive tutorial on string

formatting
 W3Schools: Provides information about the Python string

format() method
 Simplilearn.com: Offers a tutorial on string formatting in

Python, including different approaches and their strengths and


weaknesses
37

The format operator, % allows us to construct strings, replacing


parts of the strings with the data stored in variables. When
applied to integers, % is the modulus operator. But when the
first operand is a string, % is the format operator.
The first operand is the format string, which contains one or
more format sequences that specify how the second operand is
formatted. The result is a string.
For example, the format sequence "%d" means that the second
operand should be formatted as an integer (d stands for
"decimal"):
>>> camels = 42
>>> '%d' % camels
'42'
The result is the string "42", which is not to be confused with
the integer value 42.
A format sequence can appear anywhere in the string, so you
can embed a value in a sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
If there is more than one format sequence in the string, the
second argument has to be a tuple1. Each format sequence is
matched with an element of the tuple, in order.
The following example uses "%d" to format an integer, "%g" to
format a floating-point number (don't ask why), and "%s" to
format a string:
38

>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')


'In 3 years I have spotted 0.1 camels.'
The number of elements in the tuple must match the number of
format sequences in the string. The types of the elements also
must match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str
In the first example, there aren't enough elements; in the
second, the element is the wrong type.
The format operator is powerful, but it can be difficult to use.

Q. Write a python program to count the number of


characters ( character frequency )in a string
Sample string : google.com
Expected result : { g:2, o:3, l:1, e:1, ; ‘:1, c:1, m:1}

Count character frequency in a string.


Write a Python program to count the number of characters
(character frequency) in a string.
39

Sample Solution:
Python Code:
# Define a function named char_frequency that takes one
argument, str1.
def char_frequency(str1):
# Initialize an empty dictionary named 'dict' to store
character frequencies.
dict = {}
# Iterate through each character 'n' in the input string str1.
for n in str1:
# Retrieve the keys (unique characters) in the 'dict'
dictionary.
keys = dict.keys()
# Check if the character 'n' is already a key in the
dictionary.
if n in keys:
# If 'n' is already a key, increment its value (frequency)
by 1.
40

dict[n] += 1
else:
# If 'n' is not a key, add it to the dictionary with a
frequency of 1.
dict[n] = 1
# Return the dictionary containing the frequency of each
character in the input string.
return dict

# Call the char_frequency function with the argument


'google.com' and print the result.
print(char_frequency('google.com'))
Sample Output:
{'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
Flowchart:
41

Q. write a python program that takes input from the user


and displays that input back in upper and lower case

Display input in upper and lower case.


Write a Python script that takes input from the user and displays
that input back in upper and lower cases.

Sample Solution:
Python Code:

# Prompt the user to enter their favorite language and store the
input in the variable 'user_input'.
user_input = input("What's your favorite language? ")

# Print the message "My favorite language is" followed by the


user's input converted to uppercase.
print("My favorite language is ", user_input.upper())

# Print the message "My favorite language is" followed by the


user's input converted to lowercase.
print("My favorite language is ", user_input.lower())
42

Sample Output:
What's your favourite language? english
My favourite language is ENGLISH
My favourite language is english

Flowchart:

Q. Explain with the help of example various iterations


statement available in python

Python has several iteration statements, including for loops and


while loops:
 For loops: Iterate over a sequence, such as a list, tuple,
dictionary, set, or string. The iteration variable changes for each
iteration of the loop. For example, to print each fruit in a fruit
list, you can use the following code:
Code
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
43

 While loops: Execute a set of statements as long as a condition


is true. The loop is controlled by a logical expression that is
evaluated before deciding whether to run the code. For
example, to print numbers until the value of x is less than 3, you
can use the following code:
Code
x=1
while x < 3:
print(x)
Other iteration statements in Python include nested loops,
where a loop exists inside the body of another loop
Q. build in string operations

Built-in functions that can be used for various operations and


manipulations on strings. These string functions can be used to
perform tasks such as string copy, concatenation, comparison,
length, etc

Here are some built-in string operations:


Concatenation
Joins two or more strings together. In Java, you can use the +
operator or the concat method. In JavaScript, the concat()
method concatenates one or more strings passed as arguments
to the string on which the method is called.
String slicing
In Python, this feature allows you to access a substring or a
portion of a string by specifying a range of indices.
44

String replacement
In C++, this function replaces a portion of a string with another
string.
Substring
In JavaScript, the substring() method extracts characters from a
string between two specified indices.
toUpperCase()
In JavaScript, this method converts all the characters present in
the String to upper case and returns a new String with all
characters in upper case.
lower()
In Python, this string function returns a given string into a new
string where all characters are in lowercase.

Q. Define a dictionary. Write a programme in python for


removing elements from a dictionary

What Is Dictionary in Python?

A dictionary is a kind of data structure that stores items in key-


value pairs. A key is a unique identifier for an item, and a value
is the data associated with that key. Dictionaries often store
information such as words and definitions, but they can be used
for much more. Dictionaries are mutable in Python, which
means they can be changed after they are created. They are also
unordered, indicating the items in a dictionary are not stored in
any particular order.
45

How to Create a Dictionary in Python?

Dictionaries are created using curly braces {}. The key is on the
left side of the colon (:) and the value is on the right. A comma
separates each key-value pair. Creating a Python dictionary is
straightforward. Remember to use curly braces {} and separate
each key-value pair with a comma.
You will use the built-in dictionary data type to create a Python
dictionary. This type stores all kinds of data, from integers to
strings to lists. The dictionary data type is similar to a list but
uses keys instead of indexes to look up values.
You use the dict() function in Python to create a dictionary.
This function takes two arguments:
The first argument is a list of keys.
The second argument is a list of values.
Check out the example of how to create a dictionary using the
dict() function:
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
46

Removing Items from a Dictionary


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

To delete an element from a dictionary in Python, you can use


the del statement. For example:

my_dict = {'a': 1, 'b': 2, 'c': 3}


del my_dict['b']
print(my_dict) # {'a': 1, 'c': 3}
This will remove the key-value pair with key 'b' from the
dictionary. If the key is not found in the dictionary, it will raise
a KeyError exception.

You can also use the pop() method to delete an item from the
dictionary. The pop() method removes an item with the given
key and returns its value. If the key is not found, it can return a
default value instead of raising an exception:
47

my_dict = {'a': 1, 'b': 2, 'c': 3}

value = my_dict.pop('b', None)

print(value) # 2
print(my_dict) # {'a': 1, 'c': 3}
If you want to remove an item from the dictionary and also get
a list of all the removed items, you can use the popitem()
method. This method removes an arbitrary key-value pair from
the dictionary and returns it as a tuple. If the dictionary is
empty, it raises a KeyError exception.

my_dict = {'a': 1, 'b': 2, 'c': 3}

item = my_dict.popitem()

print(item) # ('c', 3)
print(my_dict) # {'a': 1, 'b': 2}

Q. Write a python program to get the largest number from a list


Finding the largest number in a list is a common task in
Python. There are multiple way to do but the simplest way to
48

find the largest in a list is by using Python’s built-


in max() function:

Using max()
Python provides a built-in max() function that returns the
largest item in a list or any iterable. The time complexity of
this approach is O(n) as it traverses through all elements of
an iterable

a = [10, 24, 76, 23, 12]

# Max() will return the largest in 'a'


largest = max(a)
print(largest)
Output
76
Explanation: max(a): This function takes the list ‘a’ as input
and returns the largest value.

Using a Loop (Native method)


If we want to find the largest number in a list without using
any built-in method (i.e. max()) function then can use a loop
(for loop).

a = [10, 24, 76, 23, 12]

# Assuming first element is largest.


largest = a[0]
49

# Iterate through list and find largest


for val in a:
if val > largest:
# If current element is greater than largest
# update it
largest = val

print(largest)

Output
76
Using reduce() function from functools
Another method to find the largest number in a list is by using
the reduce() function along with a lambda expression.
from functools import reduce

a = [10, 24, 76, 23, 12]

# Find the largest number using reduce


largest = reduce(lambda x, y: x if x > y else y, a)

print(largest)

Output
76
50

Explanation: reduce(lambda x, y: x if x > y else y,


a): The reduce() function takes pairs of elements in the
list a and applies the lambda function to return the largest
value. The lambda function compares x and y and returns the
larger of the two.

Q. Explain list with the help of suitable example

In Python, a list is a built-in dynamic sized array


(automatically grows and shrinks) that is used to store an
ordered collection of items. We can store all types of items
(including another list) in a list. A list may contain mixed type
of items, this is possible because a list mainly stores references
at contiguous locations and actual items maybe stored at
different locations.

a = [10, 20, 15]


print(a)

Output
[10, 20, 15]

Creating a List
Here are some common methods to create a list:
Using Square Brackets
Python
# List of integers
51

a = [1, 2, 3, 4, 5]

# List of strings
b = ['apple', 'banana', 'cherry']

# Mixed data types


c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)

Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Using the list() Constructor
We can also create a list by passing an iterable (like
a string, tuple, or another list) to the list() function.
Python
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))

print(a)
Output
[1, 2, 3, 'apple', 4.5]
52

Accessing List Elements


Elements in a list can be accessed using indexing. Python
indexes start at 0, so a[0] will access the first element,
while negative indexing allows us to access elements from the
end of the list. Like index -1 represents the last elements of list.
Python
a = [10, 20, 30, 40, 50]

# Access first element


print(a[0])

# Access last element


print(a[-1])

Output
10
50
Adding Elements into List
We can add elements to a list using the following methods:
 append(): Adds an element at the end of the list.

 extend(): Adds multiple elements to the end of the list.

 insert(): Adds an element at a specific position.

# Initialize an empty list


a = []
53

# Adding 10 to end of list


a.append(10)
print("After append(10):", a)

# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the end


a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)
Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]

Removing Elements from List


We can remove elements from a list using:
 remove(): Removes the first occurrence of an element.

 pop(): Removes the element at a specific index or the last

element if no index is specified.


 del statement: Deletes an element at a specified index.

Python
a = [10, 20, 30, 40, 50]

# Removes the first occurrence of 30


a.remove(30)
54

print("After remove(30):", a)

# Removes the element at index 1 (20)


popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)

# Deletes the first element (10)


del a[0]
print("After del a[0]:", a)

Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]

Q. Write a python program to multiply all the items in a list

Multiply Items in List


Write a Python program to multiply all the items in a list.
Visual Presentation:
55

Sample Solution:
# Define a function called multiply_list that takes a list 'items'
as input
def multiply_list(items):
# Initialize a variable 'tot' to store the product of the numbers,
starting with 1
tot = 1
# Iterate through each element 'x' in the input list 'items'
for x in items:
# Multiply the current element 'x' with the 'tot' variable
tot *= x
# Return the final product of the numbers
return tot

# Call the multiply_list function with the list [1, 2, -8] as input
and print the result
print(multiply_list([1, 2, -8]))

Sample Output:
-16
56

Explanation:
In the above exercise -
def multiply_list(items): -> This line defines a function called
“multiply_list” that takes a single argument items. This function
will be used to calculate the product of all the numbers in the
items list.
 tot = 1 -> This line initializes a variable called tot to 1.

This will be used to keep track of the running total of the


product of the numbers in the list.
 for x in items: -> This line starts a loop that will iterate

over each element in the items list, one at a time.


 tot *= x -> This line multiplies the current value of x by

the tot variable. This is equivalent to the shorter form tot =


tot * x.
 return tot -> This line returns the final value of the tot

variable after the loop has finished. This is the product of


all the numbers in the items list.
print(multiply_list([1,2,-8])) -> This line calls the
multiply_list() function and passes in the list [1,2,-8]. The
resulting product is then printed to the console using the print
function.
Flowchart:
57

Q. Define tuples in python. Write a python program to add


an Program to a tuples

Python Tuple
Python Tuple is an immutable (unchangeable) collection of
various data type elements. Tuples are used to keep a list of
immutable Python objects. The tuple is similar to lists in that the
value of the items placed in the list can be modified, however the
tuple is immutable and its value cannot be changed.

Creating a Tuple
A tuple is formed by enclosing all of the items (elements)
in parentheses () rather than square brackets [], and each element
is separated by commas. A tuple can contain any number of
objects of various sorts (integer, float, list, string, etc.). A tuple
can include elements with different data types. You can also
58

specify nested tuples, which have one or more entries that


are lists, tuples, or dictionaries.
Example

Python program to create Tuples


# empty tuple
my_tuple = ()
print(my_tuple)

# tuple with integer values


num = (100, 35, 7, 21)
print(num)

# tuple with mixed values


my_tuple = (23.545, 'Hello', 'A', 785)
print(my_tuple)

# nested tuples
my_tuple = ('Python', [2, 4, 6], (1, 3, 5))
print(my_tuple)

Output
()
(100, 35, 7, 21)
(23.545, 'Hello', 'A', 785)
('Python', [2, 4, 6], (1, 3, 5))
59

A tuple can also be formed without the use of parentheses. This


is referred to as Tuple Packing. The parentheses are optional,
however, it is recommended that they be used.
Example

# Python program to create Tuples


val = 100, 00.245, 'Apple', 21
print(val)
# tuple unpacking is also possible
a, b, c, d = val
print(a)
print(b)
print(c)
print(d)

Output

(100, 0.245, 'Apple', 21)


100
0.245
Apple
21

Python tuple: Exercise-5 with Solution


Write a Python program to add an item to a tuple.
60

Visual Presentation:
61
62

Sample Solution:
Python Code:
63

# Create a tuple containing a sequence of numbers


tuplex = (4, 6, 2, 8, 3, 1)
# Print the contents of the 'tuplex' tuple
print(tuplex)

# Tuples are immutable, so you can't add new elements directly.


# To add an element, create a new tuple by merging the existing
tuple with the desired element using the + operator.
tuplex = tuplex + (9,)
# Print the updated 'tuplex' tuple
print(tuplex)

# Adding items at a specific index in the tuple.


# This line inserts elements (15, 20, 25) between the first five
elements and duplicates the original five elements.
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
# Print the modified 'tuplex' tuple
print(tuplex)

# Convert the tuple to a list.


listx = list(tuplex)
# Use different methods to add items to the list.
listx.append(30)
# Convert the modified list back to a tuple to obtain 'tuplex'
with the added element.
tuplex = tuple(listx)
# Print the final 'tuplex' tuple with the added element
64

print(tuplex)

Sample Output:
(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)

Flowchart:

Q. Write a python program to slice a tuple

Python tuple: Exercise-13 with Solution


65

Write a Python program to slice a tuple.


Visual Presentation:
66
67
68
69
70
71
72
73

Sample Solution:
Python Code:
74

# Create a tuple containing a sequence of numbers


tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
# Use tuple slicing (tuple[start:stop]) to extract a portion of the
tuple.
# The start index is inclusive, and the stop index is exclusive.

# Slice from index 3 (inclusive) to 5 (exclusive) and store it in


the variable '_slice'
_slice = tuplex[3:5]
print(_slice)

# If the start index isn't defined, it's taken from the beginning of
the tuple.
_slice = tuplex[:6]
print(_slice)

# If the end index isn't defined, it's taken until the end of the
tuple.
_slice = tuplex[5:]
print(_slice)

# If neither start nor end index is defined, it returns the full


tuple.
_slice = tuplex[:]
print(_slice)

# The indexes can be defined with negative values.


75

# Slice from -8 (inclusive) to -4 (exclusive) and store it in the


variable '_slice'
_slice = tuplex[-8:-4]
print(_slice)

# Create another tuple containing the characters of "HELLO


WORLD"
tuplex = tuple("HELLO WORLD")
print(tuplex)

# Use step to specify an increment between the elements to cut


the tuple.
# tuple[start:stop:step]

# Slice from index 2 to 9 with a step of 2 and store it in the


variable '_slice'
_slice = tuplex[2:9:2]
print(_slice)

# Slice with a step of 4, which returns a tuple with a jump every


3 items
_slice = tuplex[::4]
print(_slice)

# When the step is negative, it reverses the order, slicing from


index 9 to 2 with a step of -4
_slice = tuplex[9:2:-4]
print(_slice)
76

Sample Output:
(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')

Flowchart:
77

Q. Define files in python. Explain with the help of suitable


example how to open and read file in python

What is a File?
A file is a resource to store data. As part of the programming
requirement, we may have to store our data permanently for
78

future purpose. For this requirement we should go for files.


Files are very common permanent storage areas to store our
data.
Types of Files:
There can be two types of files based on the type of information
they store. They are:
1.Text files
2.Binary files
Text files: Text files are those which store data in the form of
characters or strings.
Binary files: Binary files are those which store entire data in the
form of bytes, i.e a group of 8 bits each. While retrieving data
from the binary file, the programmer can retrieve it in the form
of bytes. Binary files can be used to store text, images, audio
and video.
File Modes:
Before going into details of how to do operation on files in
python, let’s understand about some modes which are required
to work with them.

To open a file we use open() function. It requires two


arguments, first the file path or file name, second which mode it
should open. Modes are like
 “r” -> open read only, you can read the file but can not

edit / delete anything inside


 “w” -> open with write power, means if the file exists then

delete all content and open it to write


 “a” -> open in append mode
79

The default mode is read only, ie if you do not provide any


mode it will open the file as read only. Let us open a file

>>> fobj = open("love.txt")


>>> fobj
<_io.TextIOWrapper name='love.txt' mode='r' encoding='UTF-
8'>
Closing a file

After opening a file one should always close the opened file.
We use method close() for this.

>>> fobj = open("love.txt")


>>> fobj
<_io.TextIOWrapper name='love.txt' mode='r' encoding='UTF-
8'>
>>> fobj.close()

Reading a file

To read the whole file at once use the read() method.

>>> fobj = open("sample.txt")


>>> fobj.read()
'I love Python\nPradeepto loves KDE\nSankarshan loves
Openoffice\n'
80

If you call read() again it will return empty string as it already


read the whole file. readline() can help you to read one line
each time from the file.

>>> fobj = open("sample.txt")


>>> fobj.readline()
'I love Python\n'
>>> fobj.readline()
'Pradeepto loves KDE\n'

To read all the lines in a list we use readlines() method.

>>> fobj = open("sample.txt")


>>> fobj.readlines()
['I love Python\n', 'Pradeepto loves KDE\n', 'Sankarshan loves
Openoffice\n']

You might also like