Experiment : 01
Title : Exploring basics of python like data types (strings, list, array, dictionaries, set,
tuples) and control statements.
Theory:
Python Data Types:
● Strings: Strings are a sequence of characters enclosed within single quotes, double quotes,
or triple quotes. For example, 'Hello', "World", """Python""".
● Lists: Lists are ordered collections of items enclosed within square brackets and separated
by commas. Lists can contain elements of different data types. For example, [1, 2, 'Hello',
3.14].
● Arrays: Arrays are homogeneous collections of items of the same data type. Arrays can be
created using the array module in Python. For example, import array, my_array =
array.array('i', [1, 2, 3, 4, 5]).
● Dictionaries: Dictionaries are unordered collections of key-value pairs enclosed within
curly braces and separated by commas. For example, {'name': 'John', 'age': 30, 'city': 'New
York'}.
● Sets: Sets are unordered collections of unique items enclosed within curly braces and
separated by commas. For example, {1, 2, 3, 4, 5}.
● Tuples: Tuples are ordered collections of items enclosed within parentheses and separated
by commas. Tuples are similar to lists, but they are immutable. For example, (1, 2,
'Hello', 3.14).
Python Control Statements:
● If-else statements: If-else statements are used for conditional execution. If the condition is
true, the statements inside the if block are executed, otherwise the statements inside the
else block are executed.
● For loops: For loops are used to iterate over a sequence of items. The for loop executes the
statements inside the loop for each item in the sequence.
● While loops: While loops are used to execute a block of code as long as the condition
specified in the while statement is true.
● Break and continue statements: Break and continue statements are used to alter the flow of
control in loops. The break statement terminates the loop, while the continue statement
skips the current iteration and moves on to the next iteration.
● Try-except statements: Try-except statements are used for error handling. The statements
inside the try block are executed, and if an error occurs, the statements inside the except
block are executed.
Program:
Aim : Write a Program to take two numbers from use and perform basic operations add, sub,
division and remainder.
num1=int(input('Enter the 1st no:'))
num2=int(input('Enter the 2nd No:',))
print('Addition of number is',(num1+num2))
print('Subtraction of number is',(num1-num2))
print('Division of number is',(num1/num2))
print('Remainder of number is',(num1%num2))
Output:
Aim : Write a program to take input from user for name ,age, address and print the Person
Details.
name = input('Enter the name of the person: ')
age = int(input('Enter the age of the person: '))
add = input('Enter the address of the person: ')
print('-------Person\'s Details--------')
print('Person\'s Name is:', name, '\nPerson\'s Age is:',
age, '\nPerson\'s Address is:', add)
Output:
Aim : Write a program to ask principal rate and time from user and calculate the Simple Interest
S.I= (P*R*T)/100.
p=int(input('Enter the principal amount='))
r=int(input('Enter the rate of interest='))
t=int(input('Enter the time in Years='))
s=(p*r*t)/100
print(s,'is total interest')
Output:
Aim : Write a program to calculate the area of triangle. Ask input from user
(0.5*base*height).
b=int(input('Enter base :'))
h=int(input('Enter height:'))
area=0.5*b*h
print('Area of Triangle is=',area)
Output:
Aim : Write a program to ask three subject marks from user and calculate the average.
m1=int(input('Enter the marks of English='))
m2=int(input('Enter the marks of Maths='))
m3=int(input('Enter the marks of History='))
Avg=(m1+m2+m3)/3
print('Avrage of marks is=',Avg)
Output:
Aim : Write a program to convert temperature from Fahrenheit to Celsius degree.
t=int(input('Enter the temperature in
Fahrenheit ')) c=(5/9)*(t-32)
print('Temperature in Celsius degree is ',c)
Output:
Aim : Write a program to take year from user and find whether it is a leap year or not.
a=int(input('Enter the year:'))
if(a%4==0):
print(a,'is leap year')
else:
print(a,'is not leap year')
Output:
Aim : Write a program to ask the age from user and check the valid age for a Roller Coaster ride:
a) age less than 12---print a message” You should come after ----- years” b) age greater
than 65---print a message” You should have come before---- years” Note : you need to
calculate the age:
For example if the user enters 9 …you should have come after 3 years…
a=int(input('Enter your age :'))
if(a<=12):
print('please try after',(12-a),'years')
elif(a>=65):
print('Sorry u should have try',(a-65),'years
before') else:
print('Enjoy your ride')
Output:
Aim : Write a program to input student marks by condition :
a)Marks is greater than 0 and less than 50--FAILED.
b)Marks is greater than 50 and less than 75--1stClass.
c)Marks greater than 75 –and less than 100 Distinction.
num = int(input('Enter the Marks : '))
if num<0:
print('Marks cannot be negative')
if num>=0 and num<= 50:
print('Result: FAILED')
if num>50 and num<= 75:
print('Result: 1st Class')
if num>75 and num<= 100:
print('Result: Distinction')
Output:
Aim : Write a program to take three numbers from user and find the smallest number.
n1=int(input('Enter the 1st number='))
n2=int(input('Enter the 2nd number='))
n3=int(input('Enter the 3rd number='))
if(n1<n2 and n1<n3 ):
print(n1,'is smallest number')
elif(n2<n1 and n2<n3):
print(n2,'is smallest number')
else:
print(n3,'is smallest number')
********************************************
n1=int(input('Enter the 1st number='))
n2=int(input('Enter the 2nd number='))
n3=int(input('Enter the 3rd number='))
if(n1<n2 ):
if(n1<n3):
print(n1,'is smallest number')
elif(n2<n1):
if(n2<n3):
print(n2,'is smallest number')
else:
print(n3,'is smallest number')
Output:
Aim : Write a program to find the cube up to the given numbers by the user also find their sum.
num = int (input('Enter the number : '))
print('Cube of the given number is ',(num*num*num))
sum=0
while(num>0):
digit=num%10
sum=sum+digit
num=num//10
print("The total sum of digits is:",sum)
Output:
Aim : Write a program to ask the number from user and calculate factorial. Hint 5! =5*4*3*2*1
num=int(input('Enter the number='))
factorial=1
for i in range(1,num+1,1):
factorial=factorial*i
print(factorial)
Output:
Aim : Write a program to find the sum of digits of a number. Example :If the user enter a number
=123 hen 1+2+3=6
num=int(input('Enter the number:'))
sum=0
while(num>0):
dig=num%10
sum = sum + dig
num=num//10
print(sum)
Output:
Aim : Write a program to ask the limit from user and find the sum of all odd numbers.
n=int(input('enter the limit:'))
sum=0
for i in range(1,n+1,1):
if (i%2!=0):
print(i)
sum=sum+i
print(sum)
Output:
Aim : Write a program to find whether a number entered by the user is a palindrome or not.
n=int(input('Enter the number:'))
temp=n
reverse=0
while(temp!=0):
digit=temp%10
reverse=(reverse*10)+digit
temp=temp//10
if(n==reverse) :
print(n, '==', reverse)
print('value is palindrome')
else:
print(n, '!=', reverse)
print('value is not palindrome')
Output:
Aim : Write a program to find the number of digits entered by the user
Example ( If the user enter a number =213 then number of digits=3).
n=int(input('Enter the number:'))
sum=0
while (n>0):
sum = sum + 1
n=n//10
print(sum)
Output:
Aim : Generate Fibonacci series of a given range. (example 1 1 2 3 8…)
num = int(input("Enter number: "))
n1, n2 = 1, 1
count = 0
if num == 1:
print("Fibonacci sequence upto",num,":")
print(n1)
else:
print("Fibonacci sequence: " , end = " ")
while count < num:
print(n1 , end = " ")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output:
Aim : Write a program to check the number entered by a user is Armstrong or not.(Hint
153=13+53+33)
num=int(input('Enter the number to be checked:'))
Cube=1
sum=0
d=1
temp=num
while(temp>0):
d=temp%10
cube=d**3
print('cube of',d,'=',cube)
sum=sum+cube
temp=temp//10
print(sum)
if (sum==num):
print('Number is armstrong number')
else:
print('Number is not armstrong')
Output:
Aim : Print the following patterns using nested form:
i) A B C
DEF
GHI
ch=64
for i in range(1,4,1):
for j in range(1,4,1):
ch=ch+1
print(chr(ch),end='')
print()
Output:
ii)1
12
123
1234
12345
for i in range(1,6,1):
for j in range(1,i,1):
print(j,end=' ')
print()
Output:
iii) 2 4 6
8 10 12
14 16 18
limit=int(input('Enter the limit:'))
num=0
for i in range(1,limit+1,1):
for j in range(1,limit+1,1):
num=num+2
print(num,end=' ')
print()
Output:
Aim : Write a program to ask a number from user and also ask the limit. Print the multiplication
table of a number.
num=int(input('Enter the number:'))
limit=int(input('Enter the limit:'))
mul=1
sum=0
for i in range(1,limit+1,1):
mul=num*i
print(num,'*',i,'=',mul)
sum=sum+mul
print('Total=',sum)
Output:
Aim : Create a list with data 1,22,11,33,22, and 77,44 then count the number 22 in a given
list.
l=[1,22,11,33,22,77,44]
for i in range(0,len(l),1):
if(l[i]==22):
print()
print('Number 22 is occured :',l.count(22),'times in a
given list')
Output:
Aim : Write a program to display the first and last colors from the following list.Givenlist
color_list = ["Red","Green","White" ,"Black"]
color_list=['Red','Green','White','Black']
print('First color in list',color_list[0])
print('Last color in a list is',color_list[len(color_list)-1])
Output:
Aim : Write a Program to create a List of Numbers and find the sum of elements.
limit=int(input('Enter the number of elements in the
list='))
sum=0
l=[]
for i in range(0,limit+1,1):
num = int(input('Enter numbers in the list='))
l.append(num)
temp=num
sum=sum+temp
print(l)
print(sum)
Output:
Aim : Create a Student list with atleast 10 names ask values from user and append the list with 10
Subjects. Perform the following on the List formed,
i)remove the element at index 1
ii)remove the last element
iii)print the list in reverse order
s=[]
m=[]
for i in range(1,5,1):
n=input('student name is=')
num=int(input('Enter the marks:'))
m.append(num)
s.append(n)
print(s)
print(m)
final_list=s+m
print(final_list)
final_list.reverse()
print(final_list)
del final_list[0]
print(final_list)
final_list.pop()
print(final_list)
Output:
Aim : Create a List with atleast 10 numbers and find the largest and smallest element in List.
List=[45,200,9,67,90,30,11,72,67,20]
print('Largest number in list is=',max(List))
print('Smallest number in list is=',min(List))
Output:
Aim : Write a program to replace the last element in a list with another list.
List=[45,200,9,67,90,30,11,72,67,20]
print('Largest number in list is=',max(List))
print('Smallest number in list is=',min(List))
print(len(List))
print(List)
List[len(List)-1]=4000
print(List)
Output:
Aim : Write a program to create a List and then insert the context “Python is a language ” in
the 3rd index.
List=[45,200,9,67,90,30,11,72,67,20]
print(List)
List.insert(3,'Python is a language')
print(List)
Output:
Aim : Write a Program to Create a List with and check the element is present or not.
List=[45,200,9,67,90,30,11,72,67,20]
print(List)
List.insert(3,'Python is a language')
print(List)
print('is 30 in my list=',30 in List)
Output:
Aim : Create a list with empId name salary taking input from user and then perform the action
to update the name.
num = int(input('How much data do you wanna
store: ')) name1 = []
salary = []
id =[]
for i in range(0,num,1):
empId = int(input('Enter your Id no: '))
id.append(empId)
name = (input('Enter your name: '))
name1.append(name)
salary1 = (input('Enter your salary: '))
salary.append(salary1)
namme = input("check for name: ")
if namme in name1:
print("Found your search!!")
name1[i] = input('change the name: ')
print(name1)
print(salary)
print(id)
else :
print('Name not found')
print(name1)
print(salary)
print(id)
Output:
Aim : Write a program to take input from user and create a List name it as Languages and
convert it to Tuples . Also try it vice versa.
l=[]
t=()
n = int(input("No. of elements: "))
for i in range(0,n,1):
n1 = input("Enter language: ")
l.append(n1)
print(l)
print(tuple(l))
Output:
Aim : Create a List of your favorite songs. Then create a list of your favorite movies. Join the
two lists together (Hint: List1 + List2). Finally, append your favorite book to the end of
the list and print it.
list1 = []
list2 = []
for i in range(0,3,1):
song = input("Enter favourite song: ")
list1.append(song)
movie = input("Enter your favourite movie: ")
list2.append(movie)
list3 = list1 + list2
for i in range(0,3,1):
book = input("Enter favourite book: ")
list3.append(book)
print(list3)
Output:
Aim : Create a Set and add some data to it by taking it from the user and traverse it. Also
perform the following operations: i)union ii)intersection iii)difference
set1 = set({})
set2 = set({})
for i in range(0,3,1):
num =input("Enter Num: ")
set1.add(num)
for i in range(0,3,1):
num2 =input("Enter Num: ")
set2.add(num2)
print(set1.union(set2))
print(set1.intersection(set2))
print(set1.difference(set2))
Output:
Aim : Create a dictionary with subjects as Keys and marks as values Traverse the dictionary
through loop .
size = int(input('Enter size of dictionary: '))
data = {}
for i in range (0,size ,1):
subject = input('Enter Subject: ')
mark = int(input('Enter Mark: '))
data[subject] = mark
print(data)
for key , values in data.items():
print(key , '-------->' ,values)
Output:
Aim : Create a dictionary and values from List,Set and tuples
Create a List of colors.
Create a tuples of Programming language.
Create a Set of Numbers.
data = {}
colours = ["red","white","black"]
programming = ("Python","Java","C++")
num = {1,2,3}
for i in range (0,3 ,1):
data[colours[i]] = programming[i]
print(data)
for key , values in data.items():
print(key , '~~~~~~~~~~>' ,values)
print(num)
Output:
Aim : Create a String and perform the following functions on it:
i) to check the length of String
ii) to convert the String to uppercase
iii) to capitalize the String
iv) to traverse the String using for loop
string = "python"
num = 0
dic = {}
# i) to check the length of String
print("\nLength of string: ",len(string))
# ii) to convert the String to uppercase
print("\nUppercase of string: ",string.upper())
# iii) to capitalize the String
print("\nCapitalize of string:
",string.capitalize(),"\n") # iv) to traverse the
String using for loop
for i in range (0,len(string),1):
dic[num] = string[i]
num +=1
for key , values in dic.items():
print(key , '~~~~~~~~~~>' ,values)
Output:
Conclusion:
We have learned about the basics of python like data types (strings, list, array, dictionaries, set,
tuples) and control statements.