Unit 3 Built-In Functions, Data Types, and Operators
Unit 3 Built-In Functions, Data Types, and Operators
4. Set
5. Dictionary
6. Binary Types
a=25;
print(type(a))
<class 'int'>
a=25
id(a)
2127243668528
Out[5]:
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
12
8.5
(7+2j)
print(string1)
print(string2)
print(string3)
print(type(string2))
Lists in Python can be created by just placing the sequence inside the square brackets [
].
# from above example it is clear that list can consist of any data type
[4, 5, 8, 101]
[4, (5+10j), 8.09, 101]
[4, 'escape', 'how are you', 7j]
In [21]: a=5
print(a==7-2)
print(a==8-2)
print(type(a==7-2))
print(type(a==8-2))
True
False
<class 'bool'>
<class 'bool'>
Set items cannot be accessed by referring to an index, since sets are unordered the
items has no index. But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in the keyword.
In [23]: set1=set([8,7,5,4,8,8,7,5])
set2=set("python is fun")
print(set1)
print(set2)
{8, 4, 5, 7}
{'p', 'n', 'y', 'h', 'i', ' ', 'o', 'f', 'u', 's', 't'}
# In order to access the items of a dictionary refer to its key name. Key can be used in
print(Dict[1])
print(Dict[3])
In [ ]:
Python Operators
Operators in general are used to perform operations on values and
variables. These are standard symbols used for the purpose of logical
and arithmetic operations.
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
1. Arithmetic Operators
Operators Description Syntax
% Modulus: returns the remainder when the first operand is divided by the second x%y
In [3]: a=5
a+=3
print(a)
11
7
18
4.5
4
1
81
2.Comparison Operators
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
>= Greater than or equal to True if the left operand is greater than or equal to the right x >= y
<= Less than or equal to True if the left operand is less than or equal to the right x <= y
x=25
y=30
print(a>b)
print(a<b)
print(a==b)
print(a!=b)
print(a>=b)
print(a<=b)
True
False
False
True
True
False
3.Logical Operators
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
In [2]: 1 and 1
1
Out[2]:
In [3]: 0 or 1
1
Out[3]:
In [4]: 0 or 0
0
Out[4]:
In [5]: not 1
False
Out[5]:
In [6]: not 5
False
Out[6]:
# or
print(a<30 or a<b)
print(a<5 or a>50)
# not
print(a<30 and a>b)
print(not(a<30 and a>b))
True
False
True
False
True
False
4.Bitwise Operators
Operator Description Syntax
~ Bitwise NOT ~x
0
14
-11
14
2
40
5.Assignment Operators
Operator Description Syntax
= Assign the value of the right side of the expression to the left side operand x=y+z
+= Add AND: Add right-side operand with left-side operand and then assign to left operand a+=b a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a=b a=ab
/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b
Modulus AND: Takes modulus using left and right operands and assign the result to left
%= a%=b a=a%b
operand
Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to
//= a//=b a=a//b
left operand
Exponent AND: Calculate exponent(raise power) value using operands and assign value to
**= a=b a=ab
left operand
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b
a <<= b a= a
<<= Performs Bitwise left shift on operands and assign value to left operand
<< b
10
20
10
100
102400
6 Identity Operators and Membership Operators
In Python, 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 do not imply that they are identical.
Operator Description
a = 10
b = 20
c = a
print(a is not b)
print(a is c)
True
True
In [17]: list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(list1 is not list2) # reference comaprison (is & is not)
print(list1 == list2) # content comparison (==)
1883756003584
1883756013888
False
True
True
7. Membership Operators
We can use Membership operators to check whether the given object
present in the given collection.(It may be String,List,Set,Tuple or Dict)
Operator Description
not in True if the given object not present in the specified Collection
True
False
True
False
True
True
False
True
Syntax:
Gobhi Manchurian
In [10]: # Read two integer numbers from the keyboard and print minimum value using ternary opera
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)
Assume that there are two numbers, x and y, whose values to be read
from the keyboard, and print the following outputs based on the values
of x and y.
case 1: If both are equal, then the output is : Both numbers are equal
case 2: If first number is smaller than second one, then the output is: First Number is Less than Second
Number
case 3: If the firts number is greater than second number, then the output is : First Number Greater than
Second Number
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Functions in Python
In [ ]:
rstrip() # To remove blank spaces present at end of the string (i.e.,right hand side)
lstrip() # To remove blank spaces present at the beginning of the string (i.e.,left hand side)
**************************** len()****************************************************
27
12
**************************** lower()****************************************************
hey! python is fun and easy
hellow world
**************************** upper()****************************************************
HEY! PYTHON IS FUN AND EASY
HELLOW WORLD
**************************** capitalize()***********************************************
*****
Hey! python is fun and easy
Hellow world
**************************** title()****************************************************
Hey! Python Is Fun And Easy
Hellow World
if scity=='Pune':
print("Hello Punekar..Jai Shivaji")
elif scity=='Ahmdabad':
print("Hello Ahmdabadi...Jai Shree Krishna")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")
In [12]: ''' lets full proof that if user enter correct spelling we should get desired output wit
bothering white spaces and capital and small letters. '''
if scity=='Pune':
print("Hello Punekar..Jai Shivaji")
elif scity=='Ahmdabad':
print("Hello Ahmdabadi...Jai Shree Krishna")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")
True
False
True
False
True
True
False
True
True
False
True
True
Lets use above functions to write code which gives details about type of
values entered by the user
In [17]: s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Enter the word to search for vowels: hey how are you
['e', 'o', 'a', 'u']
The number of different vowels present in hey how are you is 4
In [24]: # Suppose if you want lower case and upper case vowels, what you can do is as follows:
vowels=['a','e','i','o','u','A','E','I','O','U']
word=input("Enter the word to search for vowels: ")
found=[]
for letter in word:
if letter in vowels:
if letter not in found:
found.append(letter)
print(found)
print("The number of different vowels present in",word,"is",len(found))
Enter the word to search for vowels: hey I know YOU are smart
['e', 'I', 'o', 'O', 'U', 'a']
The number of different vowels present in hey I know YOU are smart is 6
list.count(obj) # Retuns how many times the object obj appears in a list
In [8]: print(len(L))
6
In [9]: print(max(L))
85
In [10]: print(min(L))
14
In [14]: L.append(101)
print(L)
In [17]: print(L.count(66))
In [18]: L.remove(45)
print(L)
In [19]: print(L.index(66))
4
In [22]: L.reverse()
print(L)
In [23]: L.insert(4,999)
print(L)
In [24]: L.pop()
print(L)
In [ ]:
list=[]
list.append("A")
list.append("B")
list.append("C")
list.append("85")
list.append("C75.3")
print(list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
In [21]: # lets use insert function to add value at specific place in a list
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
[1, 888, 2, 3, 4, 5]
In [22]: n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
print(n.index(777))
print(n.index(999))
[999, 1, 2, 3, 4, 5, 777]
6
0
Q. Write a program to take a tuple of numbers from the
keyboard and print its sum and average.
In [25]: t=eval(input("Enter Tuple of Numbers:"))
print(type(t))
l=len(t)
sum=0
for x in t:
sum = sum + x
print("The Sum=",sum)
print("The Average=",sum/l)
while True:
name=input("Enter Student Name to get Marks: ")
if name in d:
marks=d[name]
print(f"hey {name}, your marks is {marks}")
else:
print("the student does not exist")
1. def (mandatory)
2. return (optional)
Parameters:
Parameters are inputs to the function.
If a function contains parameters,then at the time of calling,compulsory we should provide
values,otherwise we will get error.
wish("upendra","Python")
wish("Jayesh","MATLAB")
The Square of 4 is 16
The Square of 5 is 25
The Square of 7 is 49
return statement
Function can take input values as parameters and executes business logic, and returns output to the
caller with return statement.
Python function can return any number of values at a time by using a return statement.
Default return value of any python function is None.
The sum is 30
The sum is 300
10 is Even Number
15 is Odd Number
enter a number : 5
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
The Factorial of 4 is : 24
In [ ]:
Assignments Questions
1. Write a python program mimiking KBC (Kaun Banega Crorepati). the code should include:
2. take a string input from user and use atleast 8 builtin function for string and display their result.
3. take a list input from user and use atleast 8 builtin function for list and display their result.
4. write a python function which gives factorial of only odd numbers between 1-10.
5. write a python program solving any real-life question using python concepts which you have learnt
upto now.
In [ ]: