0% found this document useful (0 votes)
23 views27 pages

Operators in Python

The document explains various operators in Python, categorizing them into arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators, each with specific functions and examples. It also covers lists and strings, detailing their characteristics, methods, and how to manipulate them in Python. Key points include the mutability of lists, the immutability of strings, and the use of operators for operations on these data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views27 pages

Operators in Python

The document explains various operators in Python, categorizing them into arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators, each with specific functions and examples. It also covers lists and strings, detailing their characteristics, methods, and how to manipulate them in Python. Key points include the mutability of lists, the immutability of strings, and the use of operators for operations on these data types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1.Explain various Operators in Python?

Operators in python
1.Python Operators in general are used to perform operations on values and variables.
2.The operator can be defined as a symbol which is responsible for a particular operation between two operands.
3.Operators are the pillars of a program on which the logic is built in a specific programming language.
4.Python provides a variety of operators, which are described as follows.

Types of operators in python


1) Arithmetic Operators
2) Comparison or Relational Operators
3) Logical Operators
4) Bitwise Operators
5) Assignment Operators
6) Identity Operators
7) Membership Operators

Arithmetic Operators
1.Arithmetic operators are used to perform arithmetic operations between two operands.
2.Arithmetic operators are used to performing mathematical operations like + (addition), - (subtraction),
*(multiplication), /(divide), %(reminder), //(floor division), and exponent (**) operators.

Operator Description Syntax


+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two x*y
operands
/ Division (float): divides the first x/y
operand by the second
// Division (floor): divides the first x // y
operand by the second
% Modulus: returns the remainder x%y
when the first operand is divided by
the second
** Power: Returns first raised to power x ** y
second

Example: Arithmetic operators in Python


Input
# Examples of Arithmetic Operator
a=9
b=4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number


mod = a % b

# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)

Output
13
5
36
2.25
2
1
6561

Comparison Operators
1.Comparison operators are used to compare two values
2.Comparison operators are used to comparing the value of the two operands and returns Boolean true or false
according to the condition.
3.Comparison are also called as Relational operators compares the values.

Operator Description Syntax


> Greater than: True if the left x>y
operand is greater than the right
< Less than: True if the left operand is x<y
less than the right
== Equal to: True if both operands are x == y
equal
!= Not equal to – True if operands are x != y
not equal
>= Greater than or equal to True if the x >= y
left operand is greater than or equal
to the right
<= Less than or equal to True if the left x <= y
operand is less than or equal to the
right

Example: Comparison Operators in Python


# Examples of Relational Operators
a = 13
b = 33

Input
# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)

Output
False
True
False

Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional
statements.

Operator Description Syntax


and Logical AND: True if both the x and y
operands are true
or Logical OR: True if either of the x or y
operands is true
not Logical NOT: True if the operand is not x
false

Example: Logical Operators in Python

Input
# Examples of Logical Operator
a = True
b = False
# Print a and b is False
print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)

Output
False
True
False

Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary numbers.

Operator Description Syntax


& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Example: Bitwise Operators in Python


# Examples of Bitwise operators
a = 10
b=4

Input
# Print bitwise AND operation
print(a & b)

# Print bitwise OR operation


print(a | b)

# Print bitwise NOT operation


print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)

Output
0
14
-11
14
2
40

Assignment Operators
Assignment operators are used to assigning values to the variables.

Operator Description Syntax


= Assign value of right side of x=y+z
expression to left side operand
+= Add AND: Add right-side operand a+=b a=a+b
with left side operand and then
assign to left operand
-= Subtract AND: Subtract right a-=b a=a-b
operand from left operand and then
assign to left operand
*= Multiply AND: Multiply right a*=b a=a*b
operand with left operand and then
assign to left operand
/= Divide AND: Divide left operand a/=b a=a/b
with right operand and then assign
to left operand
%= Modulus AND: Takes modulus using a%=b a=a%b
left and right operands and assign
the result to left operand
//= Divide(floor) AND: Divide left a//=b a=a//b
operand with right operand and
then assign the value(floor) to left
operand
**= Exponent AND: Calculate a**=b a=a**b
exponent(raise power) value using
operands and assign value to left
operand
&= Performs Bitwise AND on operands a&=b a=a&b
and assign value to left operand
|= Performs Bitwise OR on operands a|=b a=a|b
and assign value to left operand
^= Performs Bitwise xOR on operands a^=b a=a^b
and assign value to left operand
>>= Performs Bitwise right shift on a>>=b a=a>>b
operands and assign value to left
operand
<<= Performs Bitwise left shift on a <<= b a= a << b
operands and assign value to left
operand

Example: Assignment Operators in Python


# Examples of Assignment Operators
a = 10

Input
# Assign value
b=a
print(b)

# Add and assign value


b += a
print(b)

# Subtract and assign value


b -= a
print(b)

# multiply and assign


b *= a
print(b)

# bitwise lishift operator


b <<= a
print(b)

Output
10
20
10
100
102400

Identity Operators
is and is not are the identity operators both are used to check if two values are located on the same part of the
memory. Two variables that are equal d

t imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical

Example: Identity Operator

Input
a = 10
b = 20
c=a

print(a is not b)
print(a is c)

Output
True
True

Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence

Example: Membership Operator

Input
# Python program to illustrate
# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list
2.Expain about Lists in Python?
List
1)List is a collection of elements separated by comma(,) enclosed in square brackets([])
2)all the elements in the list are heterogeneous in nature(we can declare both homogeneous and heterogeneous
elements)
3)list is ordered collection i.e what ever the order we insert or arrange the same order it fallow
4)list is index based collection
 List allows duplicate elements
5)how to declare list
L=[]#empty list
L=[10,]# list with single value
L=[10,20,30,40] #list with homogenous values
L=[10,2.4,”hi”,True]#list with heterogeneous values
L=[10,20,[2,3,4],30]#we can place one list inside other list this is called nesting of list
list()it’s a constructor which is used to convert other collection data types into list or create a new list
ex
l=list((10,20,30,40))#here we have given tuple as input to list() it converts tuple into list
6)list is mutablemeans once we create a list we can add or delete or modify the same list elements
7)we can access list elements using index (supports positive indexing and negative indexing)

l=[12,13,14,15,16]
Print(l[0])#12
Print(l[1])#13
Print(l[4])#15
8)accessing list elements using for loop
l=[12,13,14,15,16]
Ex1: for i in range(len(l)):
print(l[i])
ex2: for i in l:
print(i)
9) +(concatenation) operator and * (repetition) operators in list
Ex-1
l1=[1,2,3]
L2=[4,5,6]
print(l1+l2) # [1,2,3,4,5,6]
Ex l=[2,3,4]
Print(l*2) # [2,3,4,2,3,4]
10)membership operators in list(in and not in)
s=input("enter a value")
l=[4,"hi","how",True,4.5]
if(s in l):
print("element found")
else:
print("element not found")
11)functions in list (len(),max(),min(),sum())
Len()-is a function which is used to find how many elements are present inside the given list
12)methods in list or list operations
Python has a set of built-in methods that you can use on lists/arrays.
i.append()-#we can add only one element at the end
of the list
ii.clear()-Removes all the elements from the list
iii.copy() -Returns a copy of the list
l=[10,20,30,40,10,20,40,20]
l1=l.copy()
print(l1)
iv.count()-Returns the number of elements with the specified value
l=[10,20,30,40,10,20,40,20]
print(l.count(20))
v.extend()-Add the elements of a list (or any iterable), to the end of the current list
l=[10,20,30,40]
l.extend([2,3,4,5,6])
Print(l) #[10,20,30,40,2,3,4,5,6]
vi.index()-Returns the index of the first occurrence element with the specified value
l=[10,20,30,40,10,20,40,20]
print(l.index(10))
vii.insert()-Adds an element at the specified position
l=[10,20,30,40]
print(l)
l.insert(2,25)
print(l)
viii.pop()-Removes the element at the specified position
l=[10,20,30,40,10,20,40]
print(l)
l.pop(1)
print(l)
ix.remove()-Removes the first item with the specified value
l=[10,20,30,40,10,20,40]
print(l)
l.remove(20)
print(l)
x.reverse()-Reverses the order of the list
l=[23,12,24,34]
l.reverse()
print(l)
xi.sort()-Sorts the list in ascending order
l=[23,12,24,34]
l.sort()
print(l)
ex-2
l=[23,12,24,34]
l.sort()
print(l)
l.reverse()
print(l)
13)working with nested list
l=[[1,2,3],[4,5,6],[7,8,9]]
for i in l:
for j in i:
print(j,end="")
print("")
3.Define String? Explain about Strings?
STRINGS
1. Defination:- string is collection of characters enclosed in single quotes(‘ ‘) or double quotes(“ “) or single triple
quotes(‘ ‘ ‘ welcome ‘ ‘ ‘) or double triple quotes (“””welcome”””)
 single line strings
 multi line strings
2. characters may be alphabets or digits or special symbols or white space or combination of all
Ex: “abc”,”123”,”[email protected]”, “#insta”,”welcome to vision computers”
3. assigning string to a variable
S=“welcome”
len() function is an inbuilt function in Python programming language that returns the length of the
string.
string is index based collection- Strings are ordered sequences of character data. Indexing allows you to
access individual characters in a string directly by using a numeric value. String indexing is zero-based: the
first character in the string has index 0, the next is 1, and so on
4. string supports both positive indexing and negative indexing-Each character can be accessed using their index
number.
To access characters in a string we have two ways:
Positive index number
Negative index number

In Python Positive indexing, we pass a positive index that we want to access in square brackets. The index
number starts from 0 which denotes the first character of a string.

In negative indexing in Python, we pass the negative index which we want to access in square brackets.
Here, the index number starts from index number -1 which denotes the last character of a string.

5. how to access characters inside string


str = "Hello"
print(str[4])
6. how to access strings using for loop
name = "HELLO"
for letter in name:
print(letter)
7. strings are immutable – once we create a string with certain characters we cant add or modify or delete the
characters
8. concatenation and repetition operators in strings (+ operator)(* operator)-- The + Operator
The + operator concatenates strings. It returns a string consisting of the operands joined
The * operator creates multiple copies of a string. If s is a string and n is an integer, either of the following
expressions returns a string consisting of n concatenated copies of s:
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
9. Membership operators in strings (in operator and not in operator)-- The in Operator
Python also provides a membership operator that can be used with strings. The in operator returns True if
the first operand is contained within the second, and False otherwise:
str = "Hello"
str1 = " world"
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
10. Convert other data types into strings (str() function)- which is used to convert any datatype into string format
Using the str() function
Any built-in data type can be converted into its string representation by the str() function. Built-in data type
in python include:- int, float, complex, list, tuple, dict etc.
# a is of type int
a = 10
print("Type before : ", type(a))

# converting the type from int to str


a1 = str(a)
print("Type after : ", type(a1))

# b is of type float
b = 10.10
print("\nType before : ", type(b))

# converting the type from float to str


b1 = str(b)
print("Type after : ", type(b1))

# type of c is list
c = [1, 2, 3]
print("\nType before :", type(c))

# converting the type from list to str


c1 = str(c)
print("Type after : ", type(c1))

11. string methods


I. lower()-to convert from upper case string into lower case
s=”HELLO”
print(s.lower())
II. upper()-to convert from lower case to upper case
s=”hello”
print(s.upper())
III. title()- converts each word starting character into capital letter
s=”hello how are you”
print(s.title())# Hello How Are You
IV. capitalize()-converts starting letter of sentence into capital
s=”hello how are you”
print(s.capitalize()) #Hello how are you
V. swapcase()-converts each character from existing case to opposite case(lower or upper)
s=”hELlo”
print(s.swapcase())# HelLo
VI. islower() –returns true when ever all the charecters in the string are in lower case
ex-1
s="welcome"
print(s.islower()) #True
ex-2
s=”Welcome”
print(s.islower())#False
VII. isupper()-returns true if all the characters in the string are in upper case
ex-1
s=”welcome”
print(s.isupper()) #False
ex-2
s=”WELCOME”
print(s.isupper())#True
VIII. isdigit()-returns true when ever all the charecters inside string are digits
ex-1
s=”23456”
print(s.isdigit())#True
ex-2
s=”123welcome”
print(s.isdigit())#False
IX. isalpha()-returns true when ever all the charaters inside string are alphabets
ex-1
s=”hello”
print(s.isalpha())#True
ex-2
s=”hello123”
print(s.isalpha())#False
X. isalnum()-The isalnum() method returns True if all characters in the string are alphanumeric (either
alphabets or numbers). If it is whitespace, @, !., it returns False.
ex-1
s=”welcome123”
print(s.isalnum())#true
ex-2
s=”welcome”
print(s.isalnum())#True
ex-3
s=”234”
print(s.isalnum())#True
ex-4
s=”@123”
print(s.isalnum())#False
XI. isspace()-all the charecters inside the string must be spaces
ex-1
s=”hi how are you”
print(s.isspace())#False
ex-2
s=” “
print(s.isspace())#True
XII. startswith()-it checks whether the string starts with particular character or word
txt = " welcome to python"
x = txt.startswith("welcome")
print(x) # True
XIII. endswith()-it checks whether the string ends with particular character or word
ex-1
txt = "welcome to python"
x = txt.endswith("python")
print(x) # True
XIV. count()-returns how many time the particular character or word repeats in the given string
ex-1
s=”welcome”
print(s.count(“e”)) #2
XV. index() and rindex()-returns the index of first occurrence of
of the given character
ex-1
s=”welcome”
print(s.index(“l”)) #2
print(s.index(“e”))#1
XVI. rindex()-returns the index of last occurrence of
of the given character
ex-1
s=”welcome”
print(s.index(“e”))#6

XVII. find() and rfind()


s=”hello”
print(s.find(“o”)#4
XVIII. replace()-replaces the new character or word with the existing character or word
ex-1
s=”welcame”
print(s.replace(“a”,”o”))#welcome
XIX. split()-splits the entire string based on delimiter, if I don’t give any delimiter it will take white space
as a default delimiter
ex-1
s=”hi how are you”
print(s.split()) #(‘hi’,’how’,’are’,’you’)
ex-2
s=”hi,how,are,you”
print(s.split(“,”)) # (‘hi’,’how’,’are’,’you’)
ex-3
s=”[email protected]
print(s.split(“@”)) #(‘hihowareyou’,’gamil.com’)
XX. format() “{}”
ex-1
s=”my name is {} and my age is {}”
print(s.format(‘ramesh’,23))#my name is ramesh and my age is 23
ex-2
s=”my name is {0} and my age is{1}”
print(s.format(“Ramesh”,21))#my name is Ramesh and my age is 21
XXI. strip()used to delete the white spaces of both sides of the string
ex-1
s=” welcome “
print(s.strip())#welcome
XXII. rstrip()removes right side white space of the string
ex-1
s=” welcome “
print(s.rstrip())# welcome
XXIII. lstrip()removes left side white space of the string
ex-1
s=” welcome “
print(s.lstrip())# welcome
XXIV. partition()partition the given string into 3 partitions based on the given parameter
ex-1
s=”welcome to vision computers”
print(s.partition(“to”)) #(‘welcome’,’to’,’vison computers’)
ex-2
s=”welcome to vision computers”
print(s.partition(“vision”)) # (‘welcome to’,’vision’,’computers’)
ex-3
s=”welcome to vision computers”
print(s.partition(“computers”))#(‘welcome to vision’,’computers’,’ ‘)

14) slicing in strings is the technique of getting sub string from the given string
For slicing in strings we take the support of index

Syntax
string[start:end:step]
You can return a range of characters by using the slice syntax.
by default step is 1 if we don’t give any thing
example
b = "Hello, World!"
print(b[2:5])
print
output
llo
example 2:
String ='ASTRING'
# Using indexing sequence
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
# Prints string in reverse
print("\nReverse String")
print(String[::-1])
output
AST
SR
GITA
Reverse String
GNIRTSA
4.What are Data types in Python? Explain them with examples?
Python Data Types
Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do not
need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.
Example:
a=5
The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret
variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides us the type() function,
which returns the type of the variable passed.

example to define the values of different data types and checking its type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>

Standard data types


A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id
must be stored as an integer.

Python provides various standard data types that define the storage method on each of them. The data types
defined in Python are given below.
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating
number or even complex numbers. These values are defined as int, float and complex class in Python.

 Integers – This value is represented by int class. It contains positive or negative whole numbers (without fraction
or decimal). In Python there is no limit to how long an integer value can be.
 Float – This value is represented by float class. It is a real number with floating point representation. It is
specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be
appended to specify scientific notation.
 Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary
part)j. For example – 2+3j
Example:
File:

Input:
# Python program to demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>

Boolean
Boolean type provides two built-in values, True and False. These values are used to determine the given statement
true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false can be
represented by the 0 or 'F'. Consider the following example.
Example:
File:

Input:
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)

Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple
values in an organized and efficient fashion. There are several sequence types in Python –
 String
 List
 Tuple

1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more
characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character
is a string of length one. It is represented by str class.

Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Example:
File:

Input:
# Python Program for
# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String:


Geeks
For
Life

2) List
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as the
items in a list do not need to be of the same type.

Creating List
However, the list can contain data of different types. The items stored in the list are separated with a comma (,) and
enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator
(*) works with the list in the same way as they were working with the strings.
Example:
File:

Input:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


print (list1 + list1)

# List repetation using * operator


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]

3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that
tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class. A tuple is a
read-only data structure as we can't modify the size and value of the items of a tuple.

Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ (,) with or without the use of
parentheses () for grouping of the data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).

Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is
not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Example:
File:

Input:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


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)

Traceback (most recent call last):


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

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.
Creating Dictionary
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Example:
File:

Input:
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Consider the following example.

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

# Printing dictionary
print (d)

# Accesing value using keys


print("1st name is "+d[1])
print("2nd name is "+ d[4])

print (d.keys())
print (d.values())

Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The
order of elements in a set is undefined though it may consist of various elements.

Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence
inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various mixed-up data
type values can also be passed to the set.
Example:
File:

Input:
# Python program to demonstrate
# Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with


# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

Output:
Initial blank Set:
set()

Set with the use of String:


{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'Geeks', 'For'}
5.Explain about Standard Type Built-in functions ?
Python Built-in Functions
• print( ) function
• type( ) function
• input( ) function
• abs( ) function
• pow( ) function
• dir( ) function
• sorted( ) function
• max( ) function
• round( ) function
• divmod( ) function
• id( ) function
• ord( ) function
• len( ) function
• sum( ) function
• help( ) function

1)print( ) function
The print() function prints the specified message to the screen or another standard output device.
The message that wants to print can be a string or any other object. This function converts the object into a string
before written to the screen.
Example 1: Print a string onto the screen:
print("welcome to JKC")
Output:
• welcome to JKC
Example 2: Print more than one object onto the screen:
print("Analytics Vidhya", "Chirag Goyal", "Data Scientist", "Machine Learning")
Output:
Analytics Vidhya Chirag Goyal Data Scientist Machine Learning

2)type( ) function
The type() function returns the type of the specified object.
Example 1: Return the type of the following object:
list_of_fruits = ('apple', 'banana', 'cherry', 'mango')
print(type(list_of_fruits))
Output:
<class 'tuple'>
Example 2: Return the type of the following objects:
variable_1 = "Analytics Vidhya"
variable_2 = 105
print(type(variable_1))
print(type(variable_2))
Output:
<class 'str'>
<class 'int'>

type( ) function
The type() function returns the type of the specified object.
Example 1: Return the type of the following object:
list_of_fruits = ('apple', 'banana', 'cherry', 'mango')
print(type(list_of_fruits))
Output:
<class 'tuple'>
Example 2: Return the type of the following objects:
variable_1 = "Analytics Vidhya"
variable_2 = 105
print(type(variable_1))
print(type(variable_2))
Output:
<class 'str'>
<class 'int'>

3)input( ) function
The input() function allows taking the input from the user.
Example: Use the prompt parameter to write the complete message after giving the input:
a = input('Enter your name:')
print('Hello, ' + a + ' to Analytics Vidhya')
Output:
Enter your name:Chirag Goyal
Hello, Chirag Goyal to Analytics Vidhya
4)abs( ) function
The abs() function returns the absolute value of the specified number.
Example 1: Return the absolute value of a negative number:
negative_number = -676
print(abs(negative_number))
Output:
676
Example 2: Return the absolute value of a complex number:
complex_number = 3+5j
print(abs(complex_number))
Output:
5.830951894845301

5) pow( ) function
The pow() function returns the calculated value of x to the power of y i.e, xy.
If a third parameter is present in this function, then it returns x to the power of y, modulus z.
Example 1: Return the value of 3 to the power of 4:
x = pow(3, 4)
print(x)
Output:
81
Example 2: Return the value of 3 to the power of 4, modulus 5 (same as (3 * 3 * 3 * 3) % 5):
x = pow(3, 4, 5)
print(x)
Output:

7) sorted( ) function :
The sorted() function returns a sorted list of the specified iterable object.
You can specify the order to be either ascending or descending. In this function, Strings are sorted alphabetically,
and numbers are sorted numerically.
NOTE: If a list contains BOTH string values AND numeric values, then we cannot sort it.
Example 1: Sort the specified tuple in ascending order:
tuple = ("h", "b", "a", "c", "f", "d", "e", "g")
print(sorted(tuple))
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Example 2: Sort the specified tuple in descending order:
tuple = ("h", "b", "a", "c", "f", "d", "e", "g")
print(sorted(tuple, reverse=True))
Output:
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

8) max( ) function
The max() function returns the item with the maximum value or the item with the maximum value in an iterable.
If the values this function takes are strings, then it is done using an alphabetical comparison.
Example 1: Return the name with the highest value, ordered alphabetically:
names_tuple = ('Chirag', 'Kshitiz', 'Dinesh', 'Kartik')
print(max(names_tuple))
Output:
Kshitiz
Example 2: Return the item in a tuple with the highest value:
number_tuple = (2785, 545, -987, 1239, 453)
print(max(number_tuple))
Output:
2785

9) round( ) function
The round() function returns a floating-point number that is a rounded version of the specified number, with the
specified number of decimals.
The default number of decimals is 0, meaning that the function will return the nearest integer.
Example 1: Round the specified positive number to the nearest integer:
nearest_number = round(87.76432)
print(nearest_number)
Output:
88
Example 2: Round the specified negative number to the nearest integer:
nearest_number = round(-87.76432)
print(nearest_number)
Output:
-88
Example 3: Round the specified number to the nearest integer:
nearest_number = round(87.46432)
print(nearest_number)
Output:
87

10) divmod( ) function


The divmod() function returns a tuple containing the quotient and the remainder when the first argument i.e, the
dividend is divided by the second argument i.e, the divisor.
Example 1: Display the quotient and the remainder when 7 is divided by 3:
x = divmod(7, 3)
print(x)
Output:
(2, 1)
Example 2: Display the quotient and the remainder when 72 is divided by 6:
x = divmod(72, 6)
print(x)
Output:
(12, 0)

11) id( ) function


The id() function returns a unique id for the specified object. Note that all the objects in Python have their own
unique id.
The id is assigned to the object when it is created.
The id is the object’s memory address and will be different for each time you run the program. (except for some
object that has a constant unique id, like integers from -5 to 256)
Example 1: Return the unique id of a tuple object:
names_tuple = ('Chirag', 'Kshitiz', 'Dinesh', 'Kartik')
print(id(names_tuple))
Output:
140727154106096
Example 2: Return the unique id of a string object:
string = "Analytics Vidhya is the Largest Data Science Community"
print(id(string))
Output:
140727154110000

12) ord( ) function


The ord() function returns the number representing the Unicode code of a specified character.
Example 1: Return the integer that represents the character “h”:
x = ord("h")
print(x)
Output:
104
Example 2: Return the integer that represents the character “H”:
x = ord("H")
print(x)
Output:
72

13) len( ) function


The len() function returns the count of items present in a specified object.
When the object is a string, then the len() function returns the number of characters present in that string.
Example 1: Return the number of items in a list:
fruit_list = ["apple", "banana", "cherry", "mango", "pear"]
print(len(fruit_list))
Output:
5
Example 2: Return the number of items in a string object:
string = "Analytics Vidhya is the Largest Data Science Community"
print(len(string))
Output:
54

14) sum( ) function


The sum() function returns a number, the sum of all items in an iterable.
If you are a beginner, I think that you don’t have a good understanding of what Iterables and Iterators are. To learn
these concepts, you can refer to the link.
Example 1: Start with the number 7, and add all the items in a tuple to this number:
a = (1, 2, 3, 4, 5)
print(sum(a, 7))
Output:
22
Example 2: Print the sum of all the elements of a list:
list = [1, 2, 3, 4, 5]
print(sum(list))
Output:
15

15) help( ) function:-


The help() function is used to display the documentation of modules, functions, classes, keywords, etc.
If we don’t give an argument to the help function, then the interactive help utility starts up on the console.
Example 1: Check the documentation of the print function in the python console.
help(print)
Python Objects:
1)What is an object in Python:
Python is an object-oriented programming language. Everything is in Python treated as an object, including variable,
function, list, tuple, dictionary, set, etc. Every object belongs to its class. For example - An integer variable belongs to
integer class. An object is a real-life entity. An object is the collection of various data and functions that operate on
those data. An object contains the following properties.
 State - The attributes of an object represents its state. It also reflects the properties of an object.
 Behavior - The method of an object represents its behavior.
 Identity - Each object must be uniquely identified and allow interacting with the other objects.

READING DATA FROM KEYBOARD


Python provides us with two inbuilt functions to read the input from the keyboard.
1. raw_input ( prompt )
2. input ( prompt )
1.raw_input ( ) :
This function works in older version (like Python 2.x).
This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in
which we want to store
Example:
name = raw_input("Enter your name : ")
print(name)
2. input ( ) :
This function first takes the input from the user and then evaluates the expression, which means Python
automatically identifies whether user entered a string or a number or list. If the input provided is not correct then
either syntax error or exception is raised by python.
Example:
name = input("Enter your name : ")
print (name)

You might also like