104 Python Programs For Beginners-1
104 Python Programs For Beginners-1
104 Python Programs For Beginners-1
[2]: s=input()
#In online coding tests, do not type any statement inside input() function
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
raveesh hegde
[3]: print(type(s))
<class 'str'>
1
4 How to input an integer in Jupyter Notebook
#If you want an integer, convert string to integer using int() function
Enter an integer2
[5]: n=int(input())
#In online coding tests, do not type any statement inside input() function
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
[6]: print(type(n))
<class 'int'>
#If you want a float, convert string to float using float() function
[8]: x=float(input())
#In online coding tests, do not type any statement inside input() function
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
2
2.3
#At this point, list1 is a single string. Even space is considered as a string.
Enter multiple strings separated by space : raveesh hegde cmrit ece 123
list1=list1.split()
[12]: #In online coding tests, do not type any statement inside input() function
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
3
[13]: #In online coding tests, do not type any statement inside input() function
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
raveesh,hegde,cmrit,ece,123
for i in range(n):
list1.append(input())
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
5
raveesh
hegde
cmrit
ece
123
4
For Ex. : [‘raveesh’,‘hegde’,‘cmrit’,‘ece’]
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every element
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
5
raveesh
hegde
cmrit
ece
123
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
2 4 6 8
5
list1=[int(i) for i in list1] #Convert every element of the list to integer
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
2,4,6,8
for i in range(n):
list1.append(int(input()))
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
4
2
4
6
8
for i in range(n):
list1.append(int(input())) #Press 'Enter' key after typing every element
6
#In online coding tests, input data will be taken automatically, you need not␣
,→enter any data manually
4
2
4
6
8
[21]: print(list1)
[2, 4, 6, 8]
[22]: print(*list1)
2 4 6 8
[23]: print(*list1,sep=",")
2,4,6,8
7
2,4,6,8,
2,4,6,8,
[25]: print(*list1,sep="\n")
2
4
6
8
2,
4,
6,
8,
8
24 Important Note :
There are multiple ways to input and output data in Python.
Which method should we follow?
In online coding tests, along with questions, sample test cases will also be given.
We have to follow the method which matches the format of sample input and output test cases.
25 Variables
1. In Python, there is no need to declare a variable. We can directly assign a value to it.
2. A variable name must start with a letter or the underscore character
3. A variable name cannot start with a number
4. A variable name can only contain alpha-numeric characters and underscores (A to z, 0 to 9,
and _ )
5. Variable names are case-sensitive (age, Age and AGE are three different variables)
6. A variable name cannot be any of the Python keywords.
7. Type of a variable can change during the course of a program
[27]: x=5
y=5.0
z="Raveesh"
a=3>2
26 Operators
Following are the built-in operators in python
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
9
27 Arithmetic Operators
[28]: x=2
y=3
# Addition
z=x+y
print(z)
[29]: # Subtraction
z=x-y
print(z)
-1
[30]: # Multiplication
z=x*y
print(z)
[31]: # Division
z=x/y
print(z)
0.6666666666666666
z=x%y
print(z)
10
[33]: # Floor division
z=x//y
print(z)
[34]: # Exponentiation
print(z)
28 Assignment Operators
[35]: x=2
print(x)
print(x)
[37]: # Similarly -=, *=, /=, %=, //=, **= all are valid
29 Comparison Operators
[38]: x=2
y=3
x==y
[39]: False
11
[40]: # Check whether x is not equal to y
x!=y
[40]: True
x>y
[41]: False
x<y
[42]: True
x>=y
[43]: False
x<=y
[44]: True
[45]: print(x)
print(y)
2
3
12
[46]: # and operator : returns true if both conditions are met
[46]: False
x>0 or y<3
[47]: True
not(x>0 or y<3)
[48]: False
print(x)
y = ["apples", "oranges"]
print(y)
z = x
print(z)
['apples', 'oranges']
['apples', 'oranges']
['apples', 'oranges']
[50]: print(x is z)
True
[51]: print(x is y)
# Returns False because x is not the same object as y, even though they have the␣
,→same content
False
13
[52]: print(x == y)
True
False
# Returns True because x is not the same object as y, even though they have the␣
,→same content
True
[55]: x=[2,4,6,8]
print(x)
[2, 4, 6, 8]
[56]: 2 in x
[56]: True
[57]: 3 in x
[57]: False
[58]: 3 not in x
[58]: True
14
33 Bitwise Operators
[59]: x=2
print(x)
y=4
print(y)
2
4
z=x&y
print(z)
z=x|y
print(z)
[62]: # Bitwise xor : Set each bit to 1 if both bits are different
z=x^y
print(z)
z=~x
print(z)
-3
[64]: # Zero fill left shift the bits, fill zeros in the end
z=x<<1
15
print(z)
z=x>>1
print(z)
34 Conditional Statements
[66]: x=2
if x>0:
print("The number is positive")
elif x<0:
print("The number is negative")
else:
print("The number is 0")
35 Loops
35.1 For Loop
[67]: x=[2,4,6,8]
for i in x:
print(i)
2
4
6
8
[68]: for i in range(0,len(x)): #This will loop from 0 to length(x)-1, not up to␣
,→length(x)
print(x[i])
2
4
6
8
16
35.2 While Loop
[69]: i=0
while(i<len(x)):
print(x[i])
i=i+1
2
4
6
8
[70]: x=[2,4,6,8]
for i in x:
print(i)
else:
print("Done printing")
2
4
6
8
Done printing
36 Data Types
Following are the built-in data types in Python
1. Numeric Types: int, float, complex
2. Text Type: str
3. Boolean Type: bool
4. Sequence Types: list, tuple, range
17
5. Mapping Type: dict
6. Set Types: set, frozenset
7. Binary Types: bytes, bytearray, memoryview
8. None Type: NoneType
We can use print() function to display the value of a variable.
We can use type() function to display the type of a variable.
We can use id() function to display the address of a variable.
[71]: x=5
print(x)
type(x)
[71]: int
[72]: x=5.0
print(x)
type(x)
5.0
[72]: float
x=2+3j
print(x)
type(x)
(2+3j)
18
[73]: complex
[74]: print(x.real)
2.0
[75]: print(x.imag)
3.0
[76]: print(x.conjugate())
(2-3j)
[77]: print(abs(x))
3.6055512754639896
[78]: print(angle(x))
---------------------------------------------------------------------------
<ipython-input-78-d583ba68d5ae> in <module>
----> 1 print(angle(x))
print(cmath.phase(x))
0.982793723247329
(3.6055512754639896, 0.982793723247329)
(2.0000000000000004+3.0000000000000004j)
19
40 String Data Type
[82]: x="Raveesh"
print(x)
type(x)
Raveesh
[82]: str
x="Raveesh"
y=" Hegde"
print(x+y)
#We have to use '+' operator to append a string with another string
Raveesh Hegde
[84]: print(x[0])
x[0]=A
---------------------------------------------------------------------------
<ipython-input-85-ae43f5e15f4e> in <module>
3 # That means, we cannot overwrite a value
4
----> 5 x[0]=A
20
[86]: #Strings are iterable
for i in x:
print(i)
R
a
v
e
e
s
h
veesh
print(x[-1::-1]) #First '-1' indicates last element. Last '-1' indicates step␣
,→size
hseevaR
x.append(c)
print(x)
---------------------------------------------------------------------------
<ipython-input-89-aa52899887e1> in <module>
1 #Appending a value to a string
2
----> 3 x.append(c)
4
5 print(x)
[90]: x+'c'
21
[90]: 'Raveeshc'
asc=ord(' ')
print(asc)
32
[92]: 14
[93]: 14
[94]: 20
[95]: 20
22
x="Raveesh Hegde ECE"
y=x.replace("ECE","CMRIT")
print(y)
print(y)
print(y)
y=x.capitalize()
print(y)
y=x.title()
print(y)
23
[101]: #To convert to upper case
y=x.upper()
print(y)
y=x.lower()
print(y)
y=x.swapcase()
print(y)
[104]: #To remove spaces at the beginning and at the end of the string
y=x.strip()
print(y)
x = "#".join(myTuple)
print(x)
type(x)
24
John#Peter#Vicky
[105]: str
[106]: #To join the elements of an iterable with ' space '
x = " ".join(myTuple)
print(x)
y=x.endswith("$")
print(y)
True
Some more string methods
1. isalnum() Returns True if all characters in the string are alphanumeric
2. isalpha() Returns True if all characters in the string are in the alphabet
3. isdecimal() Returns True if all characters in the string are decimals
4. isdigit() Returns True if all characters in the string are digits
5. isidentifier() Returns True if the string is an identifier
6. islower() Returns True if all characters in the string are lower case
7. isnumeric() Returns True if all characters in the string are numeric
8. isprintable() Returns True if all characters in the string are printable
9. isspace() Returns True if all characters in the string are whitespaces
10. istitle() Returns True if the string follows the rules of a title
11. isupper() Returns True if all characters in the string are upper case
print(x)
25
type(x)
True
[108]: bool
[109]: y=True
print(y)
type(y)
True
[109]: bool
[110]: z=False
print(z)
type(z)
False
[110]: bool
42 Collection of Elements :
Python has 4 built-in data types for collection of elements - List, Tuple, Set, Dictionary
List is ordered, indexed, mutable, heterogeneous, allows duplicates
Tuple is ordered, indexed, immutable, heterogeneous, allows duplicates
Set is unordered, unindexed, immutable, heterogeneous, with NO duplicates
Dictionary is unordered, indexed, mutable, heterogeneous, allows duplicate values, but NOT
duplicate keys
print(x)
26
type(x)
[111]: list
[112]: 2
[113]: False
x[0]=4
print(x)
len(x)
[115]: 4
y=[1,3,5,7]
27
[118]: # To append elements of another list
z=[2,4,6,8]
[119]: # To append elements of one list to another list and create a new list
p=[2,4,6,8]
q=[1,3,5,7]
r=p+q
print(r)
[2, 4, 6, 8, 1, 3, 5, 7]
print("List a is")
print(a)
print("List x is ")
print(x)
#Overwrite an element of a
a[0]=100 #This will not only overwrite a[0], but also x[0]
List a is
[4, 3.0, 'Raveesh', False, [1, 3, 5, 7], 2, 4, 6, 8]
List x is
[4, 3.0, 'Raveesh', False, [1, 3, 5, 7], 2, 4, 6, 8]
New list a is
[100, 3.0, 'Raveesh', False, [1, 3, 5, 7], 2, 4, 6, 8]
New list x is
28
[100, 3.0, 'Raveesh', False, [1, 3, 5, 7], 2, 4, 6, 8]
b=x.copy()
print(b)
print(b)
[]
a.count(100) #In list 'a', how many times '100' has appeared
[123]: 1
---------------------------------------------------------------------------
<ipython-input-124-b216379d57ef> in <module>
4 #Returns an error if the value is not found
5
----> 6 a.find(100) #Returns the index of the value '100'
7 #If the value is repeated, only the first index will be␣
,→ouput
29
[125]: #To insert a value at a specific position
x=[2,4,6,8]
x.reverse() #This will reverse the original list itself. It does NOT create a␣
,→new list.
30
print("The original list is",x)
x.sort() #This will sort the original list itself. It does NOT create a new list.
#If you want to create a NEW list which contains the sorted elements, then use␣
,→sorted() function
list1.sort()
print(list1)
[2, 4, 6, 8]
print(max(list1))
print(min(list1))
8
2
list1.sort(reverse=True)
print(list1)
[8, 6, 4, 2]
31
43.1 List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values
of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the
name.
Without list comprehension you will have to write a for statement with a conditional test inside:
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
print(newlist)
32
print(x)
type(x)
[135]: tuple
[136]: 2
[137]: False
[138]: 4
x[0]=4
print(x)
---------------------------------------------------------------------------
<ipython-input-139-1c4571ce6d83> in <module>
1 #Tuple is immutable. So, we cannot overwrite a value
2
----> 3 x[0]=4
4
5 print(x)
---------------------------------------------------------------------------
33
AttributeError Traceback (most recent call last)
<ipython-input-140-99fae3912164> in <module>
1 #Tuple is immutable. So, we cannot append any value.
----> 2 x.append(10)
x=(2,4,4,6,8)
[141]: 2
[142]: 1
[143]: #From 0 to 4
x=range(5)
print(x)
type(x)
range(0, 5)
[143]: range
[144]: len(x)
[144]: 5
34
46 Dictionary Data Type
print(x)
type(x)
[145]: dict
[146]: x["Name"]
[146]: 'Virat'
[147]: x["Matches"]
[147]: 350
[148]: x["Centuries"]
[148]: 50
[149]: 3
35
[152]: #To get key:value pair of the dictionary
c=x.items()
print(c)
print(p)
print(x['Name'])
Virat
Virat
print(p)
None
---------------------------------------------------------------------------
<ipython-input-154-87cdffbf3b28> in <module>
4 print(p)
5
----> 6 print(x['Name1'])#If the key is not present, throws an error
KeyError: 'Name1'
x["Centuries"]=51
36
print("New dictionary is",x)
x.update({"Runs":10000})
x.popitem()
a=x.copy()
print(a)
a.clear()
New dictionary is {}
[161]: #To return a dictionary with the specified keys and value
p = ('key1', 'key2', 'key3')
37
q = 0
new_dict = dict.fromkeys(p,q)
print(new_dict)
print("Value of c is ",c)
print(x)
type(x)
[163]: set
38
---------------------------------------------------------------------------
<ipython-input-164-a1a636ee0185> in <module>
1 #Set is unordered. So, indexing does not work.
----> 2 set[0]
[165]: x.append(2)
---------------------------------------------------------------------------
<ipython-input-165-ef5ccb6ef609> in <module>
----> 1 x.append(2)
print(x)
x={1,3,5,7}
y={2,4,6,8}
z=x|y
print(z)
{1, 2, 3, 4, 5, 6, 7, 8}
y={2,4,6,8}
39
z=x.union(y)
print(z)
{1, 2, 3, 4, 5, 6, 7, 8}
# union() method takes any iterable object such as list, string, dictionary
x={1,3,5,7}
y={2,4,6,8}
z=x&y
print(z)
set()
x={1,3,5,7}
y={2,4,6,8}
z=x.union(y)
print(z)
{1, 2, 3, 4, 5, 6, 7, 8}
[172]: #update() method does the union of two sets and updates the first set
x={1,3,5,7}
y={2,4,6,8}
x.update(y)
print(x)
{1, 2, 3, 4, 5, 6, 7, 8}
40
[173]: #intersection_update() method does the intersection of two sets and updates the␣
,→first set
x={1,3,5,7}
y={2,4,6,8}
x.intersection_update(y)
print(x)
set()
x={1,3,5,7,2,4}
y={2,4,6,8}
z = x.difference(y) #This will give elements present in x, which are not present␣
,→in y
print(z)
{1, 3, 5, 7}
x={1,3,5,7,2,4}
y={2,4,6,8}
x.difference_update(y)
print(x)
{1, 3, 5, 7}
[176]: #Symmetric difference : Elements that are not present in both sets
x={1,3,5,7,2,4}
y={2,4,6,8}
z=x.symmetric_difference(y)
print(z)
41
{1, 3, 5, 6, 7, 8}
x={1,3,5,7,2,4}
y={2,4,6,8}
x.symmetric_difference_update(y)
print(x)
{1, 3, 5, 6, 7, 8}
[178]: #To remove a random element from the list and give the removed element
x={1,3,5,7,2,4}
y=x.pop()
print(y)
print(x)
1
{2, 3, 4, 5, 7}
x={1,3,5,7,2,4}
x.discard(10)
print(x)
{1, 2, 3, 4, 5, 7}
42
x={1,3,5,7,2,4}
x.remove(10)
print(x)
---------------------------------------------------------------------------
<ipython-input-180-137cb818148b> in <module>
7 x={1,3,5,7,2,4}
8
----> 9 x.remove(10)
10
11 print(x)
KeyError: 10
x={1,3,5,7,2,4}
y={2,4,6,8}
z=x.isdisjoint(y)
print(z)
False
x={2,4}
y={2,4,6,8}
z1 =x.issubset(y)
z2=y.issubset(x)
print(z1)
print(z2)
True
43
False
x={2,4}
y={2,4,6,8}
z=y.issuperset(x)
print(z)
True
x={2,4,6,8}
y=x.copy()
print(y)
{8, 2, 4, 6}
x={2,4,6,8}
x.clear()
print(x)
set()
list1=[2,2,4,4,4,6,6,7,7,8,8]
set1=set(list1) #This will convert list into set. Set will not allow duplicates
print("List 1 is - ",list1)
print("List 2 is - ",list2)
List 1 is - [2, 2, 4, 4, 4, 6, 6, 7, 7, 8, 8]
List 2 is - [2, 4, 6, 7, 8]
44
[187]: #To get the frequency of each element of the list
list1=[2,2,4,4,4,6,8,8,8,8]
for i in set1:
print("Count of {} is {}".format(i,list1.count(i)))
Count of 8 is 4
Count of 2 is 2
Count of 4 is 3
Count of 6 is 1
print(x)
type(x)
[188]: frozenset
[189]: x = b"Hello"
print(x)
type(x)
b'Hello'
[189]: bytes
print(x)
45
type(x)
bytearray(b'\x00\x00\x00\x00\x00')
[190]: bytearray
[191]: x = memoryview(bytes(5))
print(x)
type(x)
<memory at 0x019693D8>
[191]: memoryview
[192]: x = None
print(x)
type(x)
None
[192]: NoneType
53 Type Conversion
[193]: x=1
print(type(x))
y=1.9
print(type(y))
z=1+2j
print(type(z))
<class 'int'>
<class 'float'>
<class 'complex'>
46
[194]: #We can convert int to float
x=1
a=float(x)
print(a)
1.0
b=2.9
y=int(b)
print(y)
[196]: c=str(z)
print(c)
(1+2j)
c=float(z)
print(c)
---------------------------------------------------------------------------
<ipython-input-197-359add14c132> in <module>
1 # We cant convert complex to any other data type
2
----> 3 c=float(z)
4
5 print(c)
47
[198]: # We cant convert string to float
x="raveesh"
y=float(x)
print(y)
---------------------------------------------------------------------------
<ipython-input-198-d3a83e4767bb> in <module>
3 x="raveesh"
4
----> 5 y=float(x)
6
7 print(y)
54 Operators
Following are the built-in operators in python
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
55 Arithmetic Operators
[199]: x=2
print(x)
y=3
48
print(y)
2
3
[200]: # Addition
z=x+y
print(z)
[201]: # Subtraction
z=x-y
print(z)
-1
[202]: # Multiplication
z=x*y
print(z)
[203]: # Division
z=x/y
print(z)
0.6666666666666666
[204]: # Modulus
# This gives the reminder
z=x%y
print(z)
z=x//y
49
print(z)
[206]: # Exponentiation
z=x**y
print(z)
56 Assignment Operators
[207]: x=2
print(x)
print(x)
[209]: # Similarly -=, *=, /=, %=, //=, **= all are valid
57 Comparison Operators
[210]: x=2
y=3
x==y
[211]: False
x!=y
[212]: True
50
[213]: # Check whether x is greater than y
x>y
[213]: False
x<y
[214]: True
x>=y
[215]: False
x<=y
[216]: True
[217]: print(x)
print(y)
2
3
[218]: False
x>0 or y<3
[219]: True
not(x>0 or y<3)
51
[220]: False
print(x)
y = ["apples", "oranges"]
print(y)
z = x
print(z)
['apples', 'oranges']
['apples', 'oranges']
['apples', 'oranges']
[222]: print(x is z)
True
[223]: print(x is y)
# Returns False because x is not the same object as y, even though they have the␣
,→same content
False
[224]: print(x == y)
True
False
# Returns True because x is not the same object as y, even though they have the␣
,→same content
52
True
[227]: x=[2,4,6,8]
print(x)
[2, 4, 6, 8]
[228]: 2 in x
[228]: True
[229]: 3 in x
[229]: False
[230]: 3 not in x
[230]: True
61 Bitwise Operators
[231]: x=2
print(x)
y=4
print(y)
2
4
z=x&y
print(z)
z=x|y
53
print(z)
[234]: # Bitwise xor : Set each bit to 1 if both bits are different
z=x^y
print(z)
z=~x
print(z)
-3
[236]: # Zero fill left shift the bits, fill zeros in the end
z=x<<1
print(z)
z=x>>1
print(z)
62 Functions
[238]: # Defining a function
def my_function(x,y):
z1=x+y
z2=x-y
return z1,z2
# Calling a function
54
a1,a2=my_function(2,3)
print(a1,a2)
63 Lambda Function
1. A lambda function is a small anonymous function. ( It does not have any name).
2. A lambda function can take any number of arguments, but can only have one expression.
3. Lambda helps you use a function only once, and hence, avoids cluttering up the code with
function definitions.
4. In short, Python’s lambda keyword lets you define a function in a single line of code and use
it immediately.
5. Syntax : lambda arguments : expression
[239]: x = lambda a, b, c : a + b + c
print(x(2,4,6))
12
# It has properties like Name, Matches,Runs, Wickets, Average and functions like␣
,→Avg
# These properties are called Atributes and functions are called Methods
55
class Cricketer:
def __init__(self,arg1,arg2,arg3,arg4):
self.Name=arg1
self.Matches=arg2
self.Runs=arg3
self.Wickets=arg4
# Self is a keyword here
Virat.Avg(10000,200)
Rohit.Avg(5000,150)
65 Inheritance
1. Inheritance allows us to define a class that inherits all the methods and properties from
another class.
2. Parent class is the class being inherited from, also called base class.
3. Child class is the class that inherits from another class, also called derived class.
56
# Now, lets create a child class 'Player' which inherits all properties and␣
,→methods of parent class 'Cricketer'
class Player(Cricketer):
pass
66 Polymorphism
1. Poly means many.
2. Polymorphism refers to methods/functions/operators with the same name that can be exe-
cuted on many objects or classes.
3. For ex., len() function can be used with list, tuple, set, dictionary type of objects
print(len(x))
y=(1,3,5) # y is a tuple
print(len(y))
4
3
67 File Handling
Prerequisite : Make sure that the text file and the program file are in same folder.
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename and mode.
There are four different methods (modes) for opening a file:
“r” - Read - Default value. Opens a file for reading, error if the file does not exist
“a” - Append - Opens a file for appending, creates the file if it does not exist
“w” - Write - Opens a file for writing, creates the file if it does not exist
“x” - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
“t” - Text - Default value. Text mode
“b” - Binary - Binary mode (e.g. images)
57
67.1 Reading an Existing Text File
f.read()
f.close()
# In some cases, due to buffering, changes made to a file may not show until we␣
,→close the file.
# So, we should close the files after all the operations are done.
f.close()
f.read()
58
67.4 Overwriting the Contents of a Text File
f.close()
f.read()
---------------------------------------------------------------------------
<ipython-input-248-897abeac6a66> in <module>
1 # To create a new text file
2
----> 3 f1 = open("My New Text File.txt", "x")
4
5 # Returns an error if the file already exists
59
67.6 Deleting a Text File
[249]: import os
os.remove("To Delete.txt")
---------------------------------------------------------------------------
<ipython-input-249-d7e6c1af39b7> in <module>
1 import os
----> 2 os.remove("To Delete.txt")
68 Exception Handling
try:
print(a) #Suppose 'a' is not defined
except:
print("Variable 'a' not found. An exception occurred")
1.0
[251]: try:
print("Hello")
except:
print("Something went wrong")
else: #This is executed if except condition is not executed
print("Nothing went wrong")
Hello
Nothing went wrong
[252]: try:
print(a)
except:
print("Variable a is not defined")
finally:#This is executed if except condition executed
print("The 'try except' is finished")
1.0
60
The 'try except' is finished
try:
print(a)
except NameError:
print("Variable a is not defined")
except:
print("Something else went wrong")
1.0
[254]: # Name error also occurs when a method (function) is used before importing the␣
,→module
x = 5.5
try :
print(math.ceil(x))
except :
print("Math module not imported")
[255]: x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
---------------------------------------------------------------------------
<ipython-input-255-2edc57024fbc> in <module>
2
3 if x < 0:
----> 4 raise Exception("Sorry, no numbers below zero")
[256]: x = "hello"
61
raise TypeError("Only integers are allowed")
---------------------------------------------------------------------------
<ipython-input-256-bc91768a6271> in <module>
2
3 if not type(x) is int:
----> 4 raise TypeError("Only integers are allowed")
69 Modules
1. Module is a library of functions
2. To create a module, save the functions in a file with extension .py
def greeting(name):
print("Hello, " + name)
[258]: # To use the module in a program, import the module using 'import' keyword
import mymodule
mymodule.greeting("Jonathan")
---------------------------------------------------------------------------
<ipython-input-258-16f087db6b2f> in <module>
1 # To use the module in a program, import the module using 'import'␣
,→keyword
2
----> 3 import mymodule
4
5 mymodule.greeting("Jonathan")
62
ModuleNotFoundError: No module named 'mymodule'
[259]: # Use dir() function to list out all functions present in a module
y=dir(mymodule)
print(y)
---------------------------------------------------------------------------
<ipython-input-259-0a4b962921db> in <module>
1 # Use dir() function to list out all functions present in a module
2
----> 3 y=dir(mymodule)
4
5 print(y)
70 Datetime Module
[260]: # To Display Current Date and Time
import datetime
print(x)
2023-11-08 13:22:46.552733
[261]: # Use dir() function to list out all funtions present in a module
y=dir(datetime)
print(y)
63
[262]: import datetime
x = datetime.datetime.now()
print(x.year)
2023
print(x.strftime("%A"))
Wednesday
print(x.strftime("%a"))
Wed
print(x.strftime("%w"))
print(x.strftime("%d"))
08
print(x.strftime("%b"))
Nov
print(x.strftime("%B"))
November
print(x.strftime("%m"))
11
64
[270]: # Year Short Version
print(x.strftime("%y"))
23
print(x.strftime("%Y"))
2023
[272]: # Hour 0 to 23
print(x.strftime("%H"))
13
[273]: # Hour 0 to 12
print(x.strftime("%I"))
01
[274]: # AM/PM
print(x.strftime("%p"))
PM
[275]: # Minute 0 to 59
print(x.strftime("%M"))
22
[276]: # Second 0 to 59
print(x.strftime("%S"))
48
print(x.strftime("%Z"))
print(x.strftime("%j"))
65
312
print(x.strftime("%U"))
45
print(x.strftime("%c"))
[281]: # Century
print(x.strftime("%C"))
20
print(x.strftime("%x"))
11/08/23
print(x.strftime("%X"))
13:22:48
print(x)
print(y)
5
25
[285]: x = abs(-7.25)
print(x)
7.25
66
[286]: x=3+4j
print(abs(x))
5.0
[287]: x = pow(4, 3)
print(x)
64
72 Math Module
[288]: # Square Root
import math
x = math.sqrt(64)
print(x)
8.0
import math
print(x) # returns 2
print(y)
print(z)
2
1
1
import math
67
x = math.pi
print(x)
y=math.e
print(y)
z=math.inf
print(z)
a=math.nan
print(a)
b=math.tau
print(b)
3.141592653589793
2.718281828459045
inf
nan
6.283185307179586
73 Math Functions
1. math.acos() Returns the arc cosine of a number
2. math.acosh() Returns the inverse hyperbolic cosine of a number
3. math.asin() Returns the arc sine of a number
4. math.asinh() Returns the inverse hyperbolic sine of a number
5. math.atan() Returns the arc tangent of a number in radians
6. math.atan2() Returns the arc tangent of y/x in radians
7. math.atanh() Returns the inverse hyperbolic tangent of a number
8. math.ceil() Rounds a number up to the nearest integer
9. math.comb() Returns the number of ways to choose k items from n items without repetition
and order
10. math.copysign() Returns a float consisting of the value of the first parameter and the sign of
the second parameter
11. math.cos() Returns the cosine of a number
12. math.cosh() Returns the hyperbolic cosine of a number
68
13. math.degrees() Converts an angle from radians to degrees
14. math.dist() Returns the Euclidean distance between two points (p and q), where p and q are
the coordinates of that point
15. math.erf() Returns the error function of a number
16. math.erfc() Returns the complementary error function of a number
17. math.exp() Returns E raised to the power of x
18. math.expm1() Returns Ex - 1
19. math.fabs() Returns the absolute value of a number
20. math.factorial() Returns the factorial of a number
21. math.floor() Rounds a number down to the nearest integer
22. math.fmod() Returns the remainder of x/y
23. math.frexp() Returns the mantissa and the exponent, of a specified number
24. math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
25. math.gamma() Returns the gamma function at x
26. math.gcd() Returns the greatest common divisor of two integers
27. math.hypot() Returns the Euclidean norm
28. math.isclose() Checks whether two values are close to each other, or not
29. math.isfinite() Checks whether a number is finite or not
30. math.isinf() Checks whether a number is infinite or not
31. math.isnan() Checks whether a value is NaN (not a number) or not
32. math.isqrt() Rounds a square root number downwards to the nearest integer
33. math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x
and i
34. math.lgamma() Returns the log gamma value of x
35. math.log() Returns the natural logarithm of a number, or the logarithm of number to base
36. math.log10() Returns the base-10 logarithm of x
37. math.log1p() Returns the natural logarithm of 1+x
38. math.log2() Returns the base-2 logarithm of x
39. math.perm() Returns the number of ways to choose k items from n items with order and
without repetition
40. math.pow() Returns the value of x to the power of y
41. math.prod() Returns the product of all the elements in an iterable
42. math.radians() Converts a degree value into radians
69
43. math.remainder() Returns the closest value that can make numerator completely divisible
by the denominator
44. math.sin() Returns the sine of a number
45. math.sinh() Returns the hyperbolic sine of a number
46. math.tan() Returns the tangent of a number
47. math.tanh() Returns the hyperbolic tangent of a number
70
17. cmath.polar() Convert a complex number to polar coordinates
18. cmath.rect() Convert polar coordinates to rectangular form
19. cmath.sin(x) Returns the sine of x
20. cmath.sinh(x) Returns the hyperbolic sine of x
21. cmath.sqrt(x) Returns the square root of x
22. cmath.tan(x) Returns the tangent of x
23. cmath.tanh(x) Returns the hyperbolic tangent of x
75 Random Module
[292]: import random
print(x)
0.7300469140482612
print(x)
16
[294]: l=[2,4,6,8]
print(x)
print(x)
10
import random
dir(random)
71
[296]: ['BPF',
'LOG4',
'NV_MAGICCONST',
'RECIP_BPF',
'Random',
'SG_MAGICCONST',
'SystemRandom',
'TWOPI',
'_BuiltinMethodType',
'_MethodType',
'_Sequence',
'_Set',
'__all__',
'__builtins__',
'__cached__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'_acos',
'_bisect',
'_ceil',
'_cos',
'_e',
'_exp',
'_inst',
'_itertools',
'_log',
'_os',
'_pi',
'_random',
'_sha512',
'_sin',
'_sqrt',
'_test',
'_test_generator',
'_urandom',
'_warn',
'betavariate',
'choice',
'choices',
'expovariate',
'gammavariate',
'gauss',
'getrandbits',
72
'getstate',
'lognormvariate',
'normalvariate',
'paretovariate',
'randint',
'random',
'randrange',
'sample',
'seed',
'setstate',
'shuffle',
'triangular',
'uniform',
'vonmisesvariate',
'weibullvariate']
[297]: help(random.uniform)
76 Numpy Module
1. Numpy is a python library
2. Numpy is short form for Numerical Python
3. Numpy is used to work with arrays
import numpy as np
print(arr)
print(type(arr))
[1 2 3 4 5]
<class 'numpy.ndarray'>
import numpy as np
73
arr = np.array([[2,4,6,8],[1,3,5,7]]) # 2 Square Brackets Indicate 2D Array
print(arr)
[[2 4 6 8]
[1 3 5 7]]
<class 'numpy.ndarray'>
2
(2, 4)
5
import numpy as np
[2 3 4]
import numpy as np
print(arr.dtype)
int32
import numpy as np
newarr = arr.reshape(4, 3)
74
print(newarr)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
print(newarr2)
print(newarr3)
[ 1 2 3 4 5 6 7 8 9 10 11 12]
[ 1 4 7 10 2 5 8 11 3 6 9 12]
import numpy as np
for x in arr:
print(x)
[2 4 6 8]
[1 3 5 7]
import numpy as np
for x in arr:
for y in x:
print(y)
2
4
6
8
1
75
3
5
7
import numpy as np
print(arr)
[1 2 3 4 5 6]
import numpy as np
print(np.sort(arr))
[0 1 2 3]
import numpy as np
print(x)
[41 43]
77 Matrix Operations
[309]: import numpy as np
x=[2,4,6,8]
y=[1,3,5,7]
76
print(x)
print(y)
[2, 4, 6, 8]
[1, 3, 5, 7]
z=x+y
print(z)
[2, 4, 6, 8, 1, 3, 5, 7]
z=np.add(x,y)
print(z)
[ 3 7 11 15]
z=np.subtract(x,y)
print(z)
[1 1 1 1]
z=np.multiply(x,y)
print(z)
[ 2 12 30 56]
z=np.divide(x,y)
print(z)
77
print(z)
100
x=[[2,4,6,8],[1,3,5,7]]
z=np.transpose(x)
print(z)
[[2 1]
[4 3]
[6 5]
[8 7]]
print(x)
print(np.linalg.inv(x))
print(np.linalg.det(x))
2.0
78 Graphs
[319]: #First Import the necessary packages and modules
# x axis values
x = [1,2,3]
78
y = [2,4,1]
plt.xlabel('time')
plt.ylabel('amplitude')
plt.show()
C:\Users\cmrit\anaconda3\lib\site-packages\ipykernel_launcher.py:15:
UserWarning: In Matplotlib 3.3 individual lines on a stem plot will be added as
a LineCollection instead of individual lines. This significantly improves the
performance of a stem plot. To remove this warning and switch to the new
behaviour, set the "use_line_collection" keyword argument to True.
from ipykernel import kernelapp as app
79
[320]: #How to plot multiple graphs
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
80
# naming the x axis
plt.xlabel('time')
plt.ylabel('amplitude')
plt.legend()
plt.show()
[321]: #Subplot
81
import matplotlib.pyplot as plt
x1 = [1,2,3]
y1 = [2,4,1]
x2 = [1,2,3]
y2 = [4,1,3]
plt.subplot(2, 1, 1)
plt.xlabel('time')
plt.ylabel('amplitude')
plt.title('First Subplot')
plt.subplot(2, 1, 2)
plt.xlabel('time')
plt.ylabel('amplitude')
plt.title('Second Subplot')
plt.show()
82
[322]: # Plotting sin wave
import numpy as np
amplitude = np.sin(2*np.pi*time)
# Plot a sine wave using time and amplitude obtained for the sine wave
plot.plot(time, amplitude)
plot.title('Sine wave')
83
plot.xlabel('Time')
plot.ylabel('Amplitude = sin(time)')
plot.grid(True, which='both')
plot.axhline(y=0, color='k')
plot.show()
84
1.Student Data
1 Write a Python program to read the student details like Name, USN,
and Marks in three subjects. Display the student details, total marks
and percentage with suitable messages.
[1]: name = input("Enter your name: ") #By default, input() function takes string␣
,→data type
usn = input("Enter your USN: ") #By default, input() function takes string data␣
,→type
sub01 = int(input("Enter your marks out of 100 in Subject 1: ")) #If you want␣
,→integer data, use int() function
sub02 = int(input("Enter your marks out of 100 in Subject 2:")) #If you want␣
,→integer data, use int() function
sub03 = int(input("Enter your marks out of 100 in Subject 3: ")) #If you want␣
,→integer data, use int() function
avg = (total)/3
1
print("Subject 02 Marks: ", sub02)
Name: raveesh
USN: 1cr22ec000
Subject 01 Marks: 35
Subject 02 Marks: 37
Subject 03 Marks: 38
Total Marks: 110
Percentage = 36.667
2
2.Celsius to Fahrenheit
#If you want to take float values from user, use float() function
fahrenheit=celsius*1.8+32
1
3.Simple Interest
def simple_interest(p,t,r):
si = (p * t * r)/100
print('The Simple Interest is', si)
simple_interest(P,T,R)
1
4.Compound Interest
def compound_interest(P,T,R):
Final_Amount = P * (math.pow((1 + (R/100)),T))
Compound_Interest = Final_Amount - P
return Final_Amount,Compound_Interest
fin_amount,comp_int=compound_interest(P,T,R)
1
5.Largest of 3 Numbers
else:
print("The largest number is ",n3)
1
6.Best 2 Test Marks
1 Write a Python program to find the best 2 test marks out of 3 tests and
find the average of them.
else:
if test1marks>=test2marks:
total=test3marks+test1marks
else:
total=test3marks+test2marks
average=total/2
1
7.Number of Likes, Dislikes
B=input("Enter list2")
out= count_like_dislike(A, B)
print (out)
Enter list1101011
Enter list21010
4
1
8.Even Odd
Sample Input :
12345
Sample Output :
23
1
list1=[int(i) for i in list1] #Convert every element to integer
5
1 2 3 4 5
[2]: even=0
odd=0
for i in list1:
if i%2==0:
even=even+1
else:
odd=odd+1
[3]: print(even,odd)
2 3
2 Given a list of numbers, find the sum of odd and even numbers.
Sample Input : 2 3 4 5 6 7
2 3 4 5 6 7
[6]: even_sum=0
odd_sum=0
for i in list1:
if i%2==0 and i%3!=0:
even_sum=even_sum+i
elif i%2!=0 and i%3!=0:
odd_sum=odd_sum+i
[7]: print("{},{}".format(even_sum,odd_sum))
6,12
2
9.Reverse the Array and Find the Sum
Example: Input:
2531
Output :
3883
[1]: len1=int(input()) #Enter the length of the list
1
[2]: list1=input() #Enter the elements of the list separated by space
2 5 3 1
for i in range(len(list1)):
sum1=list1[i]+list2[i]
list3.append(sum1)
3 8 8 3
2
10.Type of Triangle
enter side 1 : 2
enter side 2 : 2
enter side 3 : 3
[2]: if x == y == z:
print("Equilateral Triangle")
elif x==y or y==z or z==x:
print("Isosceles Triangle")
else:
print("Scalene Triangle")
isosceles triangle
1
11.Parity Bit
101011
[3]: if l%2==0:
parity="0"
else:
parity="1"
[4]: n=n+parity #Here '+' does concatenation of strings, NOT arithmetic addition
[5]: print(n)
1010110
1
12.Odd Factors of a Number
Input Format : 10
Output Format : 1 5
10
[2]: if num<1:
print("Number must be greater than 0")
else:
list1=[] #Start with an empty list
for i in range(1,num+1):
if num%i==0 and i%2!=0:
list1.append(i)
print(*list1)
1 5
[4]: #If we have to print the values separated by comma, but no comma after the last␣
,→element
print(*list1,sep=",")
1,5
[5]: #If we have to print the values separated by comma and there should be a comma␣
,→even after the last element
for i in list1:
1
print(i,end=",")
1,5,
[6]: #If we have to print the values one below the other
print(*list1,sep="\n")
1
5
[7]: #If we have to print the values one below the other and there should be a comma␣
,→after every element
for i in list1:
print("{},".format(i))
1,
5,
print(list1)
[1, 5]
2 Important Note :
There are multiple ways to input and output data in Python.
Which method should we follow?
In online coding tests, along with questions, sample test cases will also be given.
We have to follow the method which matches the format of sample input and output test cases.
2
13.Rule Based Product
Input :
15678
Output :
336
[1]: n = int(input()) #Enter the length of the list
#But the input format indicates that elements are separated by space
1
#So use the following method to take input
list1 =input() #Enter multiple integers separated by space. At this point, list1␣
,→is NOT a list, but a string. Because, input() function takes string by default.
list1=list1.split() #After split(), we get a list. But the list elements are␣
,→still NOT integers, but strings.
1 5 6 7 8
if 5 not in list1:
for i in list1:
product=product*i
else:
index1 = list1.index(5)
if index1 == len(list1)-1:
product = -1
else:
for i in list1[index1+1:]:
if i !=5:
product=product*i
336
2
14.Spy Number
Bacause,
1412
[2]: #Note that integer cannot be indexed, but string can be indexed
[3]: prod=1
sum1=0
[4]: for i in n:
prod=prod*int(i) #int() function converts 'str' to 'int'
sum1=sum1+int(i) #int() function converts 'str' to 'int'
1
[5]: if prod==sum1:
print("Spy Number")
else:
print("Not a Spy Number")
Spy Number
2
15.Neon Number
Sample Input : 9
Sample Output : True
Explanation : 9^2=81
8+1=9
[1]: num1=int(input()) #Enter a number
[3]: sum1=0
for i in num2:
sum1=sum1+int(i)
[4]: if sum1==num1:
print("True")
else:
print("False")
True
1
16.Armstrong Number
153
count1=len(str(n))
[3]: sum1=0
for i in str(n):
sum1=sum1+int(i)**count1 #Here '**' is used to compute power
1
[4]: if n==sum1:
print("{} is an Armstrong number".format(n))
else:
print("{} is not an Armstrong number".format(n))
2
17.GCD
1 Write a Python program to find the GCD of the given two numbers
Sample Input : 16 20
Sample Output : 4
#But the input format indicates that elements are separated by space
list1 =input() #Enter multiple integers separated by space. At this point, list1␣
,→is NOT a list, but a string. Because, input() function takes string by default.
list1=list1.split() #After split(), we get a list. But the list elements are␣
,→still NOT integers, but strings.
16 20
1
18.LCM
#But the input format indicates that elements are separated by comma
list1 =input() #Enter multiple integers separated by space. At this point, list1␣
,→is NOT a list, but a string. Because, input() function takes string by default.
list1=list1.split(",") #After split(), we get a list. But the list elements are␣
,→still NOT integers, but strings.
4,7
[3]: for i in range(n,num1*num2+1): #value of 'i' ranges from 'n' to 'num1*num2', NOT␣
,→upto "num1*num2+1"
if i%num1==0 and i%num2==0: #if 'i' is divisible by both 'num1' and 'num2',␣
,→thats the LCM
print(i)
break
28
1
19.Perfect Square
25
if num3==num1:
print("is a perfect square")
else:
print("is not a perfect square")
is a perfect square
1
20.Sum of Squares of First n Natural Numbers
1 Write a Python program to find the sum of squares of first ‘n’ natural
numbers.
Sample Input : 5
Sample Output : 55
[2]: sum1=0
for i in range(1,n+1): #Here, 'i' takes values from 1 to 'n', NOT up to 'n+1'
sum1=sum1+i**2
print(sum1)
55
1
21.Factorial of a Number
Sample Input : 5
[2]: fact=1
[3]: print(fact)
120
1
2 Write a Python program to check whether a given number is Krish-
namurthy number or not.
def factorial(n):
fact=1
for i in range(n,0,-1): #Here, value of i ranges from n to 1, NOT up to 0.
fact=fact*i
return fact
def Krishnamurthy(n) :
sum1=0
n=str(n) #'int' cannot be indexed. So, convert 'int' to 'str'
for i in n:
sum1=sum1+factorial(int(i))
if sum1==int(n):
return True
else:
return False
145
[10]: if Krishnamurthy(n):
print("True")
else:
print("False")
True
2
3 Write a Python program to print Krishnamurthy numbers between 1
and 200001
[11]: for i in range(1,200001):
if (Krishnamurthy(i)):
print(i)
1
2
145
40585
3
22.Palindrome
Because whether you read the digits from left to right or from
right to left, you will get the same number
25352
if num1==num2:
print("True")
else:
print("False")
True
1
23.Tens Place Ones Place
426
if len(num)==1: #Note that len() function works with 'str', NOT with 'int'
result=0
else:
lsd=num[-1] #num[-1] means last element of the string
#Note that lsd is a string, NOT an integer
result=count+lsd #Note that count and lsd are strings. So '+' does␣
,→ concatenation, NOT arithmetic addition
print(result)
36
1
24.Leap Year
200
[3]: print(isleap(year))
False
1
2 Write a Python program to To Generate Leap Years in an Interval.
Sample Input :
200
300
Sample Output :
4 208 212 216 220 224 228 232 236 240 244 248 252 256 260 264 268 272
276 280 284 288 292 296
[4]: start = int(input()) #Enter the start year
200
300
204 208 212 216 220 224 228 232 236 240 244 248 252 256 260 264 268 272 276 280
284 288 292 296
200
count=0
while count<15:
2
if isleap(year):
leap.append(year)
count=count+1
year=year+1
204,208,212,216,220,224,228,232,236,240,244,248,252,256,260
3
25.Prime Number
if num%i==0:
return False
else:
return True
[3]: print(is_prime(number))
True
1
2 Write a Python program to print all Prime numbers in an Interval.
Sample Input :
10
Sample Output:
7
[4]: lower_limit=int(input()) #Enter the lower limit
1
10
if is_prime(i):
prime.append(i)
print(*prime,sep="\n") #To print the elements of the list one below the other
2
3
5
7
2
3 Write a Python program to generate N prime numbers starting from
the given number.
Sample Input :
10
Sample Output :
10
5
[7]: count=0
while count<N:
if is_prime(start):
prime.append(start)
count=count+1
start=start+1
[8]: print(prime)
3
26.Sum of Consecutive Primes
For example 5 = 2 + 3, 17 = 2 + 3 + 5 + 7, 41 = 2 + 3 + 5 + 7 + 11
+ 13.
Write a python program to find out the prime numbers that sat-
isfy this property up to a given number.
Sample Input : 50
Sample Output :
17
41
[1]: def is_prime(num):
if num<2:
return False
elif num==2:
return True
else:
for i in range(2,num): #Here 'i' will vary from 2 to 'num-1', NOT up to␣
,→'num'
if num%i==0:
return False
else:
return True
1
[2]: num=int(input()) #Enter a number
50
for i in range(2,num+1):
if is_prime(i):
list1.append(i)
print(list1)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
5
17
41
2
27.Prime Product
if num%i==0:
return False
else:
return True
10
for i in range(1,num+1):
if num%i==0 and is_prime(i):
list1.append(i)
[4]: flag=0 #flag=0 indicates that the number cannot be expressed as a product of␣
,→prime numbers
for i in range(0,len(list1)):
for j in range(0,len(list1)):
if list1[i]*list1[j]==num:
1
flag=1 #flag=1 indicates that the number can be expressed as a␣
product of prime numbers
,→
break
if flag==1:
print(True)
else:
print(False)
True
flag=0 #flag=0 indicates that the number cannot be expressed as a product of␣
,→prime numbers
for i in range(0,len(list1)):
for j in range(0,len(list1)):
if list1[i]*list1[j]==num:
flag=1 #flag=1 indicates that the number can be expressed as a␣
,→product of prime numbers
[2, 5]
2
28.Product of Unique Prime Factors
Sample Input : 20
Sample Output :
25
10
Output Description:
The First line consists of the Prime Factors of 20 ie, 2 and 5 8.
The second line consists of the product of the prime factors : 2X5 =10
Enter a number20
[3]: l=[]
for i in range(2,n+1):
if n%i==0 and isprime(i):
l.append(i)
1
2 5
[4]: prod=1
for i in l:
prod=prod*i
print(prod)
10
2
29.List of Unique Numbers in a List
Input :
10 12 45 12 10 65
Output : [45,65]
6
10 12 45 12 10 65
[2]: list1=list1.split() #After splitting, we get a list with every element as 'str'
1
[3]: list2=[] #start with an empty list
for i in list1:
if list1.count(i)==1:
list2.append(i)
if len(list2)==0:
print("NULL")
else:
print(list2)
[45, 65]
2
30.Fibonacci Series
Sample Input : 5
Sample Output :
3
[1]: n=int(input()) #Enter how many Fibonacci numbers to be printed
[2]: if n==1:
fib=[0]
elif n==2:
fib=[0,1]
elif n>2:
fib=[0,1]
for i in range (2,n):
present=fib[i-1]+fib[i-2]
fib.append(present)
0
1
1
1
2
3
Sample Input : 5
Sample Output :
5
[4]: n=int(input()) #Enter up to what number Fibonacci numbers to be printed
[5]: if n==0:
fib=[0]
elif n==1:
fib=[0,1,1]
elif n>=2:
fib=[0,1,1]
present=fib[-1]+fib[-2]
while(present<=n):
fib.append(present)
present=fib[-1]+fib[-2]
print(*fib,sep="\n")
0
1
1
2
2
3
5
Sample Input :
Sample Output :
3
[6]: n=int(input()) #Enter the value of 'n'
if n==1:
print(0)
elif n==2:
print(1)
else:
fib=[0,1]
count=2
while(count<n):
present=fib[-1]+fib[-2]
fib.append(present)
count=count+1
print(present)
3
4 Write a Python program to to check whether a number is Fibonacci
or Not.
Sample Input : 8
[9]: if n<0:
print(False)
elif n==0 or n==1:
print(True)
else:
fib=[0,1]
present=fib[-1]+fib[-2]
flag=0
while(present<=n):
if present==n:
flag=1
fib.append(present)
break
else:
fib.append(present)
present=fib[-1]+fib[-2]
if flag:
print(True)
else:
print(False)
True
4
31.ASCII Value
Enter a character : a
[2]: try:
y=ord(x)
print("ASCII Value of {} Is".format(x))
print(y)
except: #If you give invalid input
print("Invalid Input")
ASCII Value of a Is
97
chr(97)
[3]: 'a'
1
32.Caeser Cipher
A to Z : 65 to 90
a to z : 97 to 122
[1]: message = input() #Enter a string
XYz
3
1
else:
code=chr(97+new%123)
print(result)
ABc
2
33.Run Length Encoding
Output the string in the form in which the count of the each
character appears followed by character for example .
Input:
XXXyZZZZZ
Output:
3X1y5Z
[1]: #Function definition
def encode(message):
encoded_message ="" #Start with an empty string
i = 0
while (i <len(message)):
count = 1
ch = message[i]
j = i
while (j < len(message)-1):
if (message[j] == message[j+1]):
count = count+1
j = j+1
else:
break
encoded_message=encoded_message + str(count) + ch #Here, '+' does␣
,→concatenation of strings.
1
i = j+1
return encoded_message
coded_msg=encode(msg)
print(coded_msg)
XXXyZZZZZ
3X1y5Z
2
34.Pythagorean Triplets
20
[2]: c=0
m=2
while(c<limit):
for n in range(1,m):
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if(c>limit):
break
print(a,b,c)
m=m+1
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
1
35.Senior Citizen
1
36.Mean, Variance and Standard Deviation
[2]: mean=statistics.mean(list1)
variance=statistics.pvariance(list1)
std_dev=statistics.pstdev(list1)
Mean is 20.00
Variance is 66.67
Standard deviation is 8.16
1
37.Largest Even Number
Find the largest even number from the available digit after re-
moving the duplicates.
cmrit@1234
else:
num=sorted(num,reverse=True)
for i in range(len(num)):
if int(num[len(num)-1-i])%2==0:
smallest_even = num[len(num)-1-i]
num.remove(smallest_even)
num.append(smallest_even)
flag=1 #flag=1 indicates that even number is possible
break
if flag==1:
1
ans = "".join(num)
print(str(ans))
else:
print(-1)
4312
2
38.Binary to Decimal
1011
[2]: decimal=0
power=0
for i in num:
decimal=decimal+int(i)*(2**power)
power=power+1
[3]: print(decimal)
11
1
39.Decimal to Binary
while(num>0):
bit=num%2
binary=str(bit)+binary #Here '+' does concatenation, NOT addidtion of␣
,→integers
11
[3]: print(dec_to_bin(num))
1011
1
40.Decimal to Hexadecimal
23
0x17
0X17
23
1
41.Roman to Decimal
deci=0
for i in range(len(roman)):
prev=d[roman[i-1]]
current=d[roman[i]]
if current>prev and i>0:
deci=deci+current-2*prev
else:
deci=deci+current
return(deci)
[2]: r=input()
dec=roman_to_int(r)
print(dec)
XXIV
24
1
42.Guess the Number
for i in range(6):
print('Take a guess.')
guess = int(input())
Take a guess.
8
Your guess is high.
Take a guess.
3
Your guess is high.
Take a guess.
1
Your guess is low.
Take a guess.
2
1
print('No. The number I was thinking of was ',secretNumber)
2
43.Number Pattern
1 Pattern 1
[4]: rows = 6
# if you want user to enter a number, uncomment the below line
# rows = int(input('Enter the number of rows'))
# outer loop
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
2 Pattern 2
[5]: rows = 5
b = 0
# reverse for loop from 5 to 0
for i in range(rows, 0, -1):
b += 1
for j in range(1, i + 1):
print(b, end=' ')
print('\r')
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
1
3 Pattern 3
[6]: rows = 5
num = rows
# reverse for loop
for i in range(rows, 0, -1):
for j in range(0, i):
print(num, end=' ')
print("\r")
5 5 5 5 5
5 5 5 5
5 5 5
5 5
5
4 Pattern 4
[7]: rows = 5
for i in range(rows, 0, -1):
for j in range(0, i + 1):
print(j, end=' ')
print("\r")
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
5 Pattern 5
[8]: rows = 5
i = 1
while i <= rows:
j = 1
while j <= i:
print((i * 2 - 1), end=" ")
j = j + 1
i = i + 1
print('')
1
3 3
5 5 5
7 7 7 7
9 9 9 9 9
2
6 Pattern 6
[9]: rows = 5
# reverse loop
for i in range(rows, 0, -1):
num = i
for j in range(0, i):
print(num, end=' ')
print("\r")
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
7 Pattern 7
[10]: rows = 6
for i in range(1, rows):
for j in range(i, 0, -1):
print(j, end=' ')
print("")
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
8 Pattern 8
[13]: rows = 5
for i in range(0, rows + 1):
for j in range(rows - i, 0, -1):
print(j, end=' ')
print()
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
3
9 Pattern 9
[14]: rows = 5
for i in range(1, rows + 1):
for j in range(1, rows + 1):
if j <= i:
print(i, end=' ')
else:
print(j, end=' ')
print()
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
10 Pattern 10
[15]: rows = 8
# rows = int(input("Enter the number of rows "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
# multiplication current column and row
square = i * j
print(i * j, end=' ')
print()
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
4
44.Star Pattern
1 Pattern 1
[1]: # number of rows
rows = 5
for i in range(0, rows):
# nested loop for each column
for j in range(0, i + 1):
# print star
print("*", end=' ')
# new line after each row
print("\r")
*
* *
* * *
* * * *
* * * * *
[4]: rows = 5
for j in range(1, rows+1):
print("* " * j)
*
* *
* * *
* * * *
* * * * *
2 Pattern 2
[3]: # number of rows
rows = 5
k = 2 * rows - 2
for i in range(0, rows):
# process each column
for j in range(0, k):
# print space in pyramid
print(end=" ")
1
k = k - 2
for j in range(0, i + 1):
# display star
print("* ", end="")
print("")
*
* *
* * *
* * * *
* * * * *
3 Pattern 3
[5]: rows = 5
for i in range(rows + 1, 0, -1):
# nested reverse loop
for j in range(0, i - 1):
# display star
print("*", end=' ')
print(" ")
* * * * *
* * * *
* * *
* *
*
4 Pattern 4
[6]: rows = 5
k = 2 * rows - 2
for i in range(rows, -1, -1):
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
for j in range(0, i + 1):
print("*", end=" ")
print("")
* * * * * *
* * * * *
* * * *
* * *
* *
*
2
5 Pattern 5
[7]: rows = 5
i = rows
while i >= 1:
j = rows
while j > i:
# display space
print(' ', end=' ')
j -= 1
k = 1
while k <= i:
print('*', end=' ')
k += 1
print()
i -= 1
* * * * *
* * * *
* * *
* *
*
6 Pattern 6
[8]: print("Print equilateral triangle Pyramid using asterisk symbol ")
# printing full Triangle pyramid using stars
size = 7
m = (2 * size) - 2
for i in range(0, size):
for j in range(0, m):
print(end=" ")
# decrementing m after each loop
m = m - 1
for j in range(0, i + 1):
print("* ", end=' ')
print(" ")
3
7 Pattern 7
[9]: rows = 6
for i in range(0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print(" ")
print(" ")
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
8 Pattern 8
[10]: rows = 5
for i in range(0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")
*
* *
* * *
* * * *
* * * * *
4
* * * *
* * *
* *
*
9 Pattern 9
[12]: rows = 5
i = 1
while i <= rows:
j = i
while j < rows:
# display space
print(' ', end=' ')
j += 1
k = 1
while k <= i:
print('*', end=' ')
k += 1
print()
i += 1
i = rows
while i >= 1:
j = i
while j <= rows:
print(' ', end=' ')
j += 1
k = 1
while k < i:
print('*', end=' ')
k += 1
print('')
i -= 1
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
5
10 Pattern 10
[13]: rows = 5
i = 0
while i <= rows - 1:
j = 0
while j < i:
# display space
print('', end=' ')
j += 1
k = i
while k <= rows - 1:
print('*', end=' ')
k += 1
print()
i += 1
i = rows - 1
while i >= 0:
j = 0
while j < i:
print('', end=' ')
j += 1
k = i
while k <= rows - 1:
print('*', end=' ')
k += 1
print('')
i -= 1
* * * * *
* * * *
* * *
* *
*
*
* *
* * *
* * * *
* * * * *
11 Pattern 11
[14]: rows = 5
k = 2 * rows - 2
for i in range(0, rows):
for j in range(0, k):
6
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = rows - 2
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
12 Pattern 12
[15]: rows = 5
i = 1
while i <= rows:
j = rows
while j > i:
# display space
print(' ', end=' ')
j -= 1
print('*', end=' ')
k = 1
while k < 2 * (i - 1):
print(' ', end=' ')
k += 1
if i == 1:
print()
else:
print('*')
7
i += 1
i = rows - 1
while i >= 1:
j = rows
while j > i:
print(' ', end=' ')
j -= 1
print('*', end=' ')
k = 1
while k <= 2 * (i - 1):
print(' ', end=' ')
k += 1
if i == 1:
print()
else:
print('*')
i -= 1
*
* *
* *
* *
* *
* *
* *
* *
*
[ ]:
8
45.Bank Transaction
1 Write a python program that computes the net amount of a bank ac-
count based on a transaction log from console input. The transaction
log format is shown below.
Input Format :
4
D 300
D 300
W 200
D 100
Output Format :
B 500
[1]: n=int(input())
x=[]
for i in range(n):
x.append(input())
3
D 100
D 200
W 100
[2]: balance=0
for i in x:
i=i.split()
if i[0]=="D" or i[0]=="d":
balance=balance+int(i[1])
if i[0]=="W" or i[0]=="w":
balance=balance-int(i[1])
[3]: print("B",balance)
B 200
1
46.Permutations and Combinations
(1, 2)
(2, 1)
perm_set = itertools.permutations(str1)
for i in perm_set:
print(i)
('A', 'B')
('B', 'A')
perm_set = itertools.permutations(val,2)
for i in perm_set:
print(i)
(1, 2)
(1, 3)
1
(2, 1)
(2, 3)
(3, 1)
(3, 2)
for i in com_set:
print(i)
(1, 2)
(1, 3)
(2, 3)
for i in com_set:
print(i)
(1, 1)
(1, 2)
(1, 3)
(2, 2)
(2, 3)
(3, 3)
[21]: npr=math.factorial(n)/math.factorial(n-r)
[22]: npr
[22]: 60.0
2
[23]: ncr=math.factorial(n)/math.factorial(n-r)/math.factorial(r)
[24]: ncr
[24]: 10.0
3
47.Transpose of a Matrix
result = [[X[j][i] for j in range (len (X))] for i in range (len (X[0]))]
for r in result:
print (r)
[1, 4, 7, 6]
[3, 5, 9, 7]
[13]: import numpy #numpy is a Python library used to work with arrays
Y=numpy.transpose(X)
[14]: type(Y)
[14]: numpy.ndarray
1
48.Shuffle Two Lists
1 Write a function shuffle(l1,l2) that takes as input two lists, 11 and l2,
and returns a list consisting of the first element in l1, then the first
element in l2, then the second element in l1, then the second element
in l2, and so on.
If the two lists are not of equal length, the remaining elements
of the longer list are appended at the end of the shuffled output.
list1=[int(i) for i in list1.split()] #Split the list and convert every element␣
,→to integer
2 4 6 8
list2=[int(i) for i in list2.split()] #Split the list and convert every element␣
,→to integer
1 3 5
for i in range(0,min(len(list1),len(list2))):
list3.append(list1[i])
list3.append(list2[i])
[4]: if len(list1)>len(list2):
list3.extend(list1[len(list2):])
elif len(list2)>len(list1):
list3.extend(list2[len(list1):])
list3
[4]: [2, 1, 4, 3, 6, 5, 8]
1
49.Fully Dividing Sequence
for x in range(n):
L.append(int(input()))
best_stored.append(0)
5
2
4
6
8
16
best_stored[0] = 1
for i in range(n):
maxval = 1
for j in range(i):
if L[i] % L[j] == 0:
maxval = max(maxval,(best_stored[j])+1)
best_stored[i] = maxval
1
[3]: print(max(best_stored),end="")
2
50.Histogram
For each number n that appears in l, there should be exactly one pair
(n,r) in the list returned by the function, where r is the number of
repetitions of n in l.
[2]: x=[2,2,2,3,3,4,4,4,5]
histogram(x)
1
51.Expanding List
[2]: True
1
52.Number of Occurrences
Enter a string/number1122233412
[2]: str2=set(str1) #Converting 'string' data type to 'set' data type removes all␣
,→duplicates
for i in str2:
count1=str1.count(i)
print("The frequency of digit/string ", i , " = ",count1)
1
53.Voting Machine
Enter names separated by space raveesh raveesh mahesh mahesh mahesh raveesh
[2]: names=names.split() #split() function separates the elementys by space and gives␣
,→a list
[3]: names
[4]: keys=set(names) #set() function eliminates duplicates and gives only unique␣
,→elements
[5]: keys
1
dict1 #dict1 contains name and vote
[7]: max_vote=max(dict1.values())
[8]: max_vote
[8]: 3
list1
mahesh 3
[12]: #If you want to print name and vote separated by comma
print("{},{}".format(list2[0],dict1[list2[0]]))
mahesh,3
2
54.Vehicle Parking
Find the row in the parking lot which has the most available
space to park the vehicle. The Row index starts from 1.
1
1
0
0
1
0
0
0
0
0
1
0
0
for i in range(r):
list1=(p[i*c:(i+1)*c]) #Make a list row wise
count1=list1.count('0') #Count the number of 0s
if count1>empty_space:
req_row=i+1
empty_space=count1
print(req_row)
2
55.Remove Spaces and Find Length
1 Given a string s, remove any spaces if any and output the length of
the string and whether it is even or odd.
[3]: if len(str3)%2==0:
print(len(str3),"even")
else:
print(len(str3),"odd")
20 even
1
56.Words Longer Than n
[2]: list1=sentence.split(" ") #Wherever space is there, sentence will be split and a␣
,→list will be formed
print(list1)
for i in list1:
if len(i)>n:
list2.append(i)
print(list2)
1
57.Common and Uncommon Words
[2]: str1=str1.split()
str2=str2.split()
[3]: common=[]
uncommon=[]
for i in str1:
if i in str2:
common.append(i)
for i in str1:
if i not in str2:
uncommon.append(i)
for i in str2:
if i not in str1:
uncommon.append(i)
1
58.Duplicate Character
raveesh hegde
for i in string1:
if i not in string2:
string2=string2+i
print(string2)
for i in name:
if name.count(i)>1 and i not in l:
l=l+i
if len(l)>0:
print(*l,sep=",")
1
else:
print("There are no duplicate characters in the string.")
e,h
print(sentence2)
for i in sentence2:
if i not in sentence3:
sentence3=sentence3+" "+i
print(sentence3)
[9]: st1=[]
c=0
for x in st:
if x not in st1:
st1.append(x)
print(sorted(st1))
2
59.Remove Adjacent Duplicates
1 You are given a number with duplicate digits your task is to remove
the immediate duplicate digits and print the result.
result=remove_adjacent_dup(num)
print(result)
Enter a number133322
132
1
60.First Non Repeating Character
If you find all the characters are repeating print the answer as
-1.
[1]: str1=input() #Enter a string
engineering
1
61.Anagram and Heterogram
def isanagram(x,y):
x=sorted(x.lower())
y=sorted(y.lower())
if x==y:
return True
else:
return False
for i in list1:
for j in list1:
if i!=j and isanagram(i,j):
if i not in list2:
list2.append(i)
if j not in list2:
list2.append(j)
if len(list2)==0:
1
print("No Anagrams")
else:
print(*list2)
listen silent
if len(str1)==len(str2):
print(True)
else:
print(False)
True
2
62.Remove Repeated Words
Write a Python program to remove the repeated words of length greater than or equal to 5.
for i in str1:
if i not in list1:
list1.append(i) #This is to append the word to the list
str3=str3+" "+i #This is to concatenate the word to the string
else:
if len(i)<5:
list1.append(i) #This is to append the word to the list
str3=str3+" "+i #This is to concatenate the word to the string
print(str3)
1
63.Remove a Digit
Take size of the list, digit to be removed, and the list of elements as
input.
Sample Input :
432 52 123
Sample Output :
[43, 5, 13]
[1]: len1=int(input()) #Enter the number of elements
3
2
432 52 123
1
[3]: list2=[] #Start with an empty list
for i in list1:
new=i.replace(num,"") #Replace the number with empty string
list2
2
64.String Similarity
For ex.
Input :
Python Exercises
Python Exercises
Output: 1
Input :
Python Exercises
Python Exercise
Output : 0.9696969696969697
Python Excercises
Python Excercise
1
[3]: len1=len(str1)
len2=len(str2)
L=min(len1,len2)
[4]: similar=0
for i in range(L):
if str1[i]==str2[i]:
similar=similar+1
print(similar*2/(len1+len2))
0.9696969696969697
Python Excercises
Python Excercise
[7]: a=str1
b=str2
c=difflib.SequenceMatcher(a=a,b=b)
[9]: print(c.ratio())
0.9696969696969697
2
65.Shadow Sentences
The function should return True if they are and False if they
aren’t.
[1]: s1=input() #Enter the first sentence
[3]: flag=1
if len(s1)!=len(s2):
flag=0
else:
for i in range(len(s1)):
if len(s1[i])!=len(s2[i]):
flag=0
break
else:
for j in range(len(s1[i])):
for k in range(len(s1[i])):
if s1[i][j]==s2[i][k]:
flag=0
break
if flag==1:
1
print(True)
else:
print(False)
True
2
66.Vowels, Consonents, Digits
[2]: spaces=[]
space_count=0
numbers=[]
numbers_count=0
upper_cases=[]
upper_cases_count=0
lower_cases=[]
lower_cases_count=0
special_char=[]
special_char_count=0
vowels=[]
vowels_count=0
consonents=[]
consonents_count=0
1
space_count=space_count+1
elif i.isupper():
upper_cases.append(i)
upper_cases_count=upper_cases_count+1
if i in "AEIOU":
vowels.append(i)
vowels_count=vowels_count+1
else:
consonents.append(i)
consonents_count=consonents_count+1
elif i.islower():
lower_cases.append(i)
lower_cases_count=lower_cases_count+1
if i in "aeiou":
vowels.append(i)
vowels_count=vowels_count+1
else:
consonents.append(i)
consonents_count=consonents_count+1
elif i.isdigit():
numbers.append(i)
numbers_count=numbers_count+1
else:
special_char.append(i)
special_char_count=special_char_count+1
2
Consonent count is 12
The digits count is 3
The special char count is 1
3
67.To Remove Vowels and Consonants from a String
Sample Output : i
cmrit ece
for i in str1:
if i in "aeiouAEIOU" or i in " ":
str2=str2+i #Here 'str2' and 'i' are strings. So, '+' does␣
,→concatenation, NOT arithmetic addition.
[3]: print(str2)
i ee
1
2 Write a Python Program to remove all vowels from a string without
affecting spaces. If there are no consonants, print -1.
Sample Output 2 : -1
cmrit ece
for i in str1:
if i not in "aeiouAEIOU":
str2=str2+i #Here 'str2' and 'i' are strings. Hence, '+' does␣
,→concatenation, NOT arithmetic addition.
[6]: if str2==" "*len(str2): #Here '*' does repetion of space, NOT arithmetic␣
,→multiplication.
print("-1")
else:
print(str2)
cmrt c
2
68.Highest Number of Vowels
1 Write a Python program to find the word in a sentence which has the
most number vowels
[1]: x=input() #Enter a string
[3]: count1=0
for i in x:
count2=0
for j in i:
if j in "aeiouAEIOU":
count2=count2+1
if count2>count1:
count1=count2
req_word=i
[4]: print(req_word)
raveesh
1
69.Substring
[2]: if (str1.find(str2) == -1): #find() function returns -1 if str2 is not found in␣
,→str1
Substring is present
1
70.Reverse the Words
output = " ".join(str3) #Join the elements of the list using space
print(output)
1
71.Reverse a Name and Capitalize Each Word
Raveesh Hegde
[3]: print(str2.title())
Edgeh Hseevar
1
72.Car Engine Number
1 A car company numbers the car’s engine numbers based on the car’s
number plate. The engine number is the sum of all the integers
present on the car’s number plate. The issuing authority has hired
you in order to provide the engine numbers to the cars. Your task is
to develop an algorithm which takes input as in the form of string
(Number Plate) and gives back the car’s engine number in the form
of an integer.
Sample Output: 18
ka-53-mj2038
[2]: sum=0
for i in s:
if i in n:
sum=sum+int(i)
print(sum)
21
1
73.Replace a Character
raveesh
r
k
for i in str1:
if i==a:
str2=str2+b #Here '+' does concatenation of strings, NOT arithmetic␣
,→addition
else:
str2=str2+i #Here '+' does concatenation of strings, NOT arithmetic␣
,→addition
kaveesh
1
74.Remove Duplicates and Sort Alphanumerically
Remove all duplicate words and print the remaining words sort-
ing them alphanumerically.
str3=list(str2) #Set cannot be indexed, but list can be indexed. So, convert␣
,→'str2' to list
str5=" ".join(str4) #Join all the elements of str4 and give a single string
print(str5)
1
75.Fill With Stars
1 Write a Python program to take a line of text as input and Find the
number of even length words in that line.
If those words length is less than 10, pad them in the right with
the character ’*’ up to the length 10 .
Sample Output :
Hi********
you?******
to********
[1]: str1=input() #Enter a sentence
Hi********
you?******
to********
1
76.Wonderful String
aabbbcccc
[3]: if len(set(str1))==3:
print("Wonderful")
else:
print("-1")
Wonderful
1
77.Name, Company from Email Id
1 Write a Python program to input email addresses and print the user
name and company names
Sample Ouput :
peter yahoo
john google
xyz accenture
peter yahoo
john google
xyz accenture
1
2 Method 2 : Using Regular Expressions
peter yahoo
john google
xyz accenture
2
78.Extract Email IDs from a Sentence
Sample Output :
jhon.b@gmail.com
Paul.c@yahoo.ac.in
for i in list1:
print(i[0])
jhon.b@gmail.com
Paul.c@yahoo.ac.in
1
79.Start with A, end with Z
Find all the words that start with “A” or “a” and end with “Z”
or “z”
Sample Output:[‘bcd’,’baf’]
for i in range(n):
list1.append(input()) #Press "Enter" key after entering every element
4
asdfz
aghjjjz
az
ArhtZ
for i in list1:
if len(i)==5 and i[0] in "Aa" and i[-1] in "Zz":
list2.append(i[1:4]) #Pick 2nd,3rd,4th characters
print(list2)
['sdf', 'rht']
1
80.Start with Hello, End with a Digit
Display all the strings that start with the word ‘Hello’ and end
with the word of digits 0 - 9.
Sample Input:
Helo How is
Hello 999
Sample Output:
Hello 999
[1]: n=int(input()) #Enter the number of strings
1
for i in range(n):
list1.append(input())
#I have used this method of input, because sample inputs are given one below the␣
,→other
4
Hello How you 9
Helo How is
How are you99
Hello 999
for i in list1:
if i[0:5]=="Hello" and i[-1].isdigit():
list2.append(i)
print(*list2,sep="\n")
[6]: s=[]
i=0
while i<n:
s1=input("Enter the next word")
s.append(s1)
i=i+1
2
Enter the next wordHow are you99
Enter the next wordHello 999
[7]: for i in s:
print(i)
[8]: import re
n=int(input())
i=0
lst=[]
while i<n:
item=input()
lst=lst+ [item]
i=i+1
pattRegex = re.compile(r'^Hello .*\d+$')
for i in lst:
if pattRegex.search(i)!=None:
print(i)
4
Hello How you 9
Helo How is
How are you99
Hello 999
Hello How you 9
Hello 999
3
81.Parenthesis Matching
def par_match(s):
count=0
for i in s:
if i == ')':
count=count-1
if count<0:
return False
elif i=='(':
count=count+1
if count==0:
return True
else:
return False
)(
False
1
82.Valid USN
Write a Python program to take ‘n’ strings and print all the strings
which are USNs.
Sample Input :
askdf
1CR20IS003
1CR19EC112
2CE18EC110
Sample Output :
1CR20IS003
1CR19EC112
2CE18EC110
[1]: n=int(input()) #Enter the number of strings
1
[2]: #Input strings are given one below the other.
x=[]
for i in range(n):
x.append(input()) #Press 'Enter' key after typing every input
askdf
1CR20IS003
1CR19EC112
2CE18EC110
def isusn(x):
if len(x)==10:
cond1=i[0].isdigit() #Returns true if all string elements are digits
cond2=i[1:3].isalpha() #Returns true if all string elements are␣
,→alphabetic
for i in x:
if isusn(i):
list2.append(i)
[5]: if len(list2)==0:
print(None)
else:
print(*list2,sep="\n") #To print the elements one below the other
1CR20IS003
1CR19EC112
2CE18EC110
2
2 Method 2 : Using Regular Expressions
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every input
4
askdf
1CR20IS003
1CR19EC112
2CE18EC110
for i in list1:
if sp.search(i)!=None:
list2.append(i)
[8]: if len(list2)==0:
print(None) #If there are NO valid USNs
else:
print(*list2,sep="\n") #To print the elements one below the other
1CR20IS003
1CR19EC112
2CE18EC110
3
83.Valid Phone Number
Valid : 123-4563-7891
Invalid : 123-4563+7891
123-4563-7891
[3]: if is_phonenum(phone_number):
print(True)
else:
print(False)
True
1
2 Given a string containing phone number, write a python program to
identify the same and print the Phone Number.
080-2847-4463
2
3 Method 2 : Using Regular Expressions
for i in list1:
if sp.search(i)!=None:
print(i)
flag=1
if flag==0:
print("Nil")
080-2847-4463
3
84.Valid PAN
BDDQS6617D
[2]: flag=0
if len(str1)!=10:
flag=0
else:
if str1[0:5].isalpha() and str1[5:9].isdigit() and str1[9].isalpha():
flag=1
if flag==1:
print("Valid PAN")
else:
print("Invalid PAN")
Valid PAN
BDDQS6617D
1
[4]: sp = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}") #Form a search pattern
if sp.search(str1)!=None:
print("Valid PAN")
else:
print("Invalid PAN")
Valid PAN
2
85.Valid Date
for i in str1:
str2=i.split("-") #After split(), we get a list
if(len(str2[0])==4):
str2.reverse()
str3="-".join(str2)
list1.append(str3)
else:
list1.append(i)
[3]: print(*list1) #We use this method of printing because sample output shows that␣
,→output values should be printed in a sinle line separated by space
1
2 Method 2 : Using Regular Expressions
print(valid_dates)
2
86.Valid Password
1
1 Write a Python program to check the validity of password input by
users.
Sample Input :
ABd12t34@1
a F1ttt
2w3EEEgw3*
2We3345
ab34#ullo*12AakQ
Sample Output :
2
ABd12t34@1
[1]: n=int(input()) #Enter the length of the list
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every string
ABd12t34@1
a F1ttt
2w3EEEgw3*
2We3345
ab34#ullo*12AakQ
[4]: l=0
for i in list1:
if valid(i):
print(i)
l=l+1
if l==0:
print("None")
ABd12t34@1
3
2 Method 2 : Using Regular Expressions
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every string
ABd12t34@1
a F1ttt
2w3EEEgw3*
2We3345
ab34#ullo*12AakQ
for i in list1:
cond1=len(i)>=8 and len(i)<=15 #There should be at least 8 and at most 15␣
,→letters in the password
ABd12t34@1
4
87.Valid Vehicle Number
1 Write a Python program to find the valid vehicle numbers from the
given list of numbers.
Sample Input :
KA55NK2040
AB68XY3049
55KANK2040
AB6830XY49
Sample Output :
KA55NK2040
AB68XY3049
[1]: n=int(input()) #Enter the length of the list
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every element
4
KA55NK2040
AB68XY3049
55KANK2040
1
AB6830XY49
for i in list1:
cond1=len(i)==10 #There should be 10 letters in the vehicle number
[3]: if len(list2)==0:
print(None) #If there are NO valid vehivle numbers
else:
print(*list2,sep="\n") #To print the elements one below the other
KA55NK2040
AB68XY3049
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every element
4
KA55NK2040
AB68XY3049
55KANK2040
AB6830XY49
2
for i in list1:
if sp.search(i)!=None:
list2.append(i)
[7]: if len(list2)==0:
print(None) #If there are NO valid vehicle numbers
else:
print(*list2,sep="\n") #To print the elements one below the other
KA55NK2040
AB68XY3049
3
88.Valid IP Address
Sample Input :
192.168.0.1
292.168.0.1
192.168.02.1
192.16.0.1
Sample Output :
192.168.0.1
192.16.0.1
1
for i in range(n):
list1.append(input()) #Press 'Enter' key after typing every element
4
192.168.0.1
292.168.0.1
192.168.02.1
192.16.0.1
return False
else:
return True
else:
return False
for i in list1:
if valid_ip(i):
list3.append(i)
[4]: if len(list3)==0:
print(None) #If there are no valid IP addresses
else:
print(*list3,sep="\n") #To print the elements one below the other
192.168.0.1
192.16.0.1
2
89.Valid URL
Input :
6
https://www.yahoo.com
http://blog.hubspot.com/marketing/Index.html
http://www.cmrit.ac.in
https://www.karnatakacareers.in
ftp://internet.address.edu/file/path/file.txt
abc:/xxx.abc.vvv.in
Output:
https://www.yahoo.com
http://blog.hubspot.com/marketing/Index.html
http://www.cmrit.ac.in
https://www.karnatakacareers.in
ftp://internet.address.edu/file/path/file.txt
1
[1]: import re #Import REgular Expressions module
1
for i in range(n):
list1.append(input())
https://www.yahoo.com
http://blog.hubspot.com/marketing/Index.html
http://www.cmrit.ac.in
https://www.karnatakacareers.in
ftp://internet.address.edu/file/path/file.txt
abc:/xxx.abc.vvv.in
for i in list1:
if sp1.search(i)!=None:
list2.append(i)
[5]: print(*list2,sep="\n") #To print the elements one below the other
https://www.yahoo.com
http://blog.hubspot.com/marketing/Index.html
http://www.cmrit.ac.in
https://www.karnatakacareers.in
ftp://internet.address.edu/file/path/file.txt
count=0
for i in list2:
if sp2.search(i)!=None:
count+=1
print(count)
2
90.Exception Handling
try:
c = a/b
print(c)
except:
print("Error : Division by Zero")
2
0
Error : Division by Zero
1
91.Top 10 Words
[3]: word_list = [] #Start with an empty list. This list will eventually contain all␣
,→words in the text file
for i in sentence_list:
word_list = word_list+i.split() #split() function separates words
[4]: word_dict = {} #Start with an empty dictionary. This list will eventually␣
,→contain all words in the text file and their frequency
for i in word_set:
word_dict[i] = word_list.count(i) # Creating a dictionary with word and count.
count=0
for i in sorted_keys: # 'i' will give the keys in the dictionary
print(" Frequency of word '", i,"'=", word_dict[i])
count+=1
if(count == 10):
break
1
Frequency of word ' with '= 1
Frequency of word ' was '= 3
Frequency of word ' to '= 1
Frequency of word ' the '= 14
Frequency of word ' that '= 1
Frequency of word ' than '= 1
Frequency of word ' supreme '= 1
Frequency of word ' supremacy, '= 1
2
92.Sort a Text File
1 Write a program to sort the contents of a text file and write the sorted
contents into a separate text file.
[2]: word_lst = []
for i in fp:
word_lst+=i.split()
# append all the words to the list -> lst
[3]: word_lst.sort()
# Sorts all the words alphabetical order.
str = " ".join(word_lst)
# Joins all words by the delimited " " = space.
1
93.ZIP a Folder
if os.path.exists('Zipped Folder.zip'):
print(archived)
else:
print("ZIP file not created")
1
94.Class Complex
1
a = a.split()
areal = int(a[0])
aimaginary = int(a[1])
2
95.Class Student
1 Write a program that uses class Student which prompts the user to
enter marks in three subjects and calculates total marks, percentage
and displays the score card details.
[2]: a = Student()
print("\nEnter your scores out of 100 in Physics, Chemistry and Mathematics.\n")
a.setMarks()
print("\n---------SCORE CARD ---------\n")
a.display()
1
Enter Physics Marks : 35
Enter Chemistry Marks : 36
Enter Math Marks : 37
2
96.Class Circle
Sample Input: 4
Sample Output:
Area 50.27
Perimeter: 25.13
[1]: import math
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_circle_area(self):
return math.pi * self.radius**2
def calculate_circle_perimeter(self):
return 2 * math.pi * self.radius
circle = Circle(radius)
area = circle.calculate_circle_area()
perimeter = circle.calculate_circle_perimeter()
print("Perimeter: {:.2f}".format(perimeter))
1
Area: 50.27
Perimeter: 25.13
2
97.Add Two Time Objects
1 Write a Python program to add the two time objects and display
[1]: class t:
def __init__(self,hh,mm,ss):
self.hh=hh
self.mm=mm
self.ss=ss
def addition(self,h,m,s):
if self.ss>59 or s>59:
print("invalid input")
else:
self.ss=self.ss+s
if self.ss>60:
self.mm=self.mm+1
self.ss=self.ss-60
if self.mm>59 or m>59:
print("invalid input")
else:
self.mm=self.mm+m
if self.mm>60:
self.hh=self.hh+1
self.mm=self.mm-60
self.hh=self.hh+h
print(str(self.hh)+":"+str(self.mm)+":"+str(self.ss))
[4]: a,b,c=input().split()
x,y,z=input().split()
obj=t(int(a),int(b),int(c))
obj.addition(int(x),int(y),int(z))
10 20 30
1 2 3
11:22:33
1
98.LInear Search
2 4 6 8
for i in range(len(x)):
if x[i]==a:
print(i)
flag=1 #flag=1 indicates that element is found
if flag==0:
print(-1) #Print -1 if the element is not found
1
99.Binary Search
if list1[mid]==x:
return mid
if list1[mid] < x:
low = mid + 1
2 4 6 8 10
1
8
2
100.Bubble Sort
bubbleSort(arr)
1
101.Selection Sort
1
102.Insertion Sort
1
103.Merge Sort
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
1
104.Quick Sort
# This implementation utilizes pivot as the last element in the nums list
# It has a pointer to keep track of the elements smaller than the pivot
# At the very end of partition() function, the pointer is swapped with the pivot
# to come up with a "sorted" nums relative to the pivot
1
# function to perform quicksort
size = len(data)
quickSort(data, 0, size - 1)
Unsorted Array
[1, 7, 4, 1, 10, 9, -2]
Sorted Array in Ascending Order:
[-2, 1, 1, 4, 7, 9, 10]