PP
PP
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
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
Sequence Type
String
4
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
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
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
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
num = 1+2j
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
int main() {
double number, squareRoot;
scanf("%lf", &number);
return 0;
}
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. ]
Addition
Subtraction
Multiplication
Division
Modulus
Exponentiation
Floor division
Example:
Copy Code
16
val1 = 2
val2 = 3
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
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
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
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
print(res)
Output :
Copy Code
1
20
Copy Code
val1 = 2
val2 = 3
print(res)
Output :
Copy Code
21
val1 = 3
val2 = 2
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 – >
Syntax – x > y
Operator – <
22
Description – Less than: True if the left operand is less than the
right
Syntax – x < y
Operator – ==
Syntax – x == y
Operator – !=
Syntax – x != y
Operator – >=
Syntax – x >= y
Operator – <=
23
Syntax – x <= y
Operator – and
Syntax – x and y
Operator – or
Syntax – x or y
Operator – not
Syntax – not x
But what if we told you that you can create a calculator program
in Python yourself!
#addition
#subtraction
#multiplication
#division
Output
Enter the first Number :3
Enter the Second Number :3
3.0 + 3.0 = 6.0
3.0 - 3.0 = 0.0
26
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:
grade = 85
print("Excellent")
print("Good")
print("Average")
else:
print("Needs Improvement")
driving_license = True
if driving_license:
else:
31
else:
for num in a:
# Checking if the number is even
if num % 2 == 0:
even += 1
else:
odd += 1
Output
Even numbers: 4
Odd numbers: 5
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output
Even numbers: 4
Odd numbers: 5
Explanation: The filter() function is used to extract even and
Function Description
true
Q. format operator
36
formatting
W3Schools: Provides information about the Python string
format() method
Simplilearn.com: Offers a tutorial on string formatting in
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
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? ")
Sample Output:
What's your favourite language? english
My favourite language is ENGLISH
My favourite language is english
Flowchart:
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.
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
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
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.
item = my_dict.popitem()
print(item) # ('c', 3)
print(my_dict) # {'a': 1, 'b': 2}
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
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
print(largest)
Output
76
50
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']
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
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.
# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
Python
a = [10, 20, 30, 40, 50]
print("After remove(30):", a)
Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]
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.
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
# 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
Output
Visual Presentation:
61
62
Sample Solution:
Python Code:
63
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:
Sample Solution:
Python Code:
74
# 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)
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
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
After opening a file one should always close the opened file.
We use method close() for this.
Reading a file