0% found this document useful (0 votes)
10 views40 pages

Python Variable and Input Exercises

The document contains a series of exercises aimed at teaching Python programming concepts, including variable usage, input/output functionality, arithmetic operations, decision making, loops, and list manipulation. Each exercise includes a question, objective, requirement analysis, and a sample program with expected output. The exercises are structured to progressively build programming skills through practical coding tasks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views40 pages

Python Variable and Input Exercises

The document contains a series of exercises aimed at teaching Python programming concepts, including variable usage, input/output functionality, arithmetic operations, decision making, loops, and list manipulation. Each exercise includes a question, objective, requirement analysis, and a sample program with expected output. The exercises are structured to progressively build programming skills through practical coding tasks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Exercise 1 # a

Question:
Correct the below code and execute it:
val=789
print("Given value is: ",VAL)
print("Python is a case sensitive language")
Objective:
To learn the concepts of Variables usage with print
Requirement Analysis:
 Spyder IDE installation
 Write the code
 Verify the error
 Execute the code
Program:
val=789
print("Given value is: ",val)
print("Python is a case sensitive language")

Output:

21 | P a g e
Exercise 1 #b

Question
Correct the below code, add the code if needed to display the output as given:
Code snippet:
$name='My name"
@age=40

Objective
To learn variable naming conventions

Requirement Analysis :
 Spyder IDE installation
 Write the corrected code
 Execute the code

Program
name="My name"
age=40
print("Name:",name)
print("Age:",age)

output:

22 | P a g e
Exercise 1 #c
Question
Write a program to assign single value to multiple variables.
Objective
To implement variable assignment
Requirement Analysis :
 Input two variables
 Assign the values while reading the input
 The datatype can be any type
 Print them using separate print statement

Program
x=y=int(input("Enter a value"))
print("x=",x)
print("y=",y)

Output:

23 | P a g e
Exercise 2 #a
Question
Write a python program to read Regd. No, name from the student and display it on the screen
Objective :
To learn input and output functionality in python
Requirement Analysis :
 Declare a variable for Regd No and read using input statement
 Declare a variable student name and read using input statement
 Print each value separately using print statement

Program
Regd_no=input("Enter Student Roll Number :")
Student_name=input("Enter Student Name : ")
print("Regd. No:" + Regd_no+ "")
print("Name:" + Student_name +"")

Output:

24 | P a g e
Exercise 2 #b
Question

Display the given float value adjusted to two decimal points


Objective :
Learn float type usage and its decimal positions
Requirement Analysis :
 Declare a variable for float value and read using input
 Print the value using round built in function

Program
float_value=float(input("Enter a float value : "))
print("Value rounded to 2 Decimals : ",round(float_value,2))

Output

25 | P a g e
Exercise 2 #c
Question
Write a program to display the below message:
Hello, \nREI\n students
Objective :
To learn escape sequence
Requirement Analysis :
Use escape sequence \n appropriately using print statement

Program
print("Hello, \\nREI\\n students")
Output:

26 | P a g e
Exercise 3 #a
Question
Write a program that asks the user for a weight in kilograms and converts it to pounds. There are
2.2 pounds in a Kilogram
Objective
To learn usage of arithmetic operators
To implement round built in function to solve the given problem using conversion

Requirement Analysis:
 Read a variable kg using input function
 Convert into pounds using the given formula
 Assign the value to pounds
 Print the output

Program
kg=float(input("Enter Weight in Kilograms "))
pounds = kg * 2.2
print(kg,"kilograms = ",round(pounds , 3), "pounds ")

Output:

27 | P a g e
Exercise 3 #b
Question

Write a program that asks the user to enter three numbers (use three separate input statements).
Create variables called total and average that hold the sum and average of the three numbers and
print out the values of total and average
Objective
To implement input statements
To understand variable concept
To apply arithmetic operators

Requirement Analysis:
 Read first number using input function
 Read second number using input function
 Read third number using input function
 Compute sum for the above variables
 Compute average for the sum
 Print the sum and average

Program
first_number=int(input("Enter First Number : "))
second_number=int(input("Enter Second Number : "))
third_number=int(input("Enter Third Number : "))
sum_numbers=first_number+second_number+third_number
print("Sum of three numbers is : ",sum_numbers)
print("Average value is : ",round((sum_numbers/3),2))

Output:

28 | P a g e
Exercise 3 #c
Question
Write a program to find power of a number without using loops and built-in functions. Base and
exponent value to be taken from the user
Objective
To learn usage of operators
Requirement Analysis :
 Read two variable x and y
 Use the exponent operator x upon y

Program
print("Finding x power y ")
print("----------------------")
x=int(input("Enter x value : "))
y=int(input("Enter y value : "))
print(x,"to the power of",y,"is",x**y)

Output:

29 | P a g e
Exercise 4# a
Question
Write a program to display ‘Valid’ if the value is odd and lesser than 10000, otherwise ‘Invalid’.
Objective :
To learn and implement decision making using if condition

Requirement Analysis :
 Reading a value using input
 Verify if its odd and compare if it is less than 10000
 Print the message as per the condition

Program
value=int(input("Enter a value : "))
if(value%2==1 and value<10000):
print("Valid")
else:
print("Invalid")

Output:

30 | P a g e
Exercise 4# b
Question
Write a program that asks the user to enter a length in feet. The program should then give the
user the option to convert from feet into inches, yards, miles, millimeters, centimeters, meters, or
kilometers. Say if the user enters a 1, then the program converts to inches, if they enter a 2, then
the program converts to yards, etc.
Use below conversion formulas:
1. inches=multiply the length value with 12
2. yards=divide the length value by 3
3. miles=divide the length value by 5280
4. millimeters=for an approximate result, multiply the length value by 305
5. centimeters=multiply the length value with 30.48
6. meters=for an approximate result, divide the length value by 3.281
7. kilometers=for an approximate result, divide the length value by 3281

Objective
To learn and implement operators in C++
Requirement Analysis :
Read the length using input
Use the given formulas to calculate the result
Display the result in appropriate format

Program
print("Converter ")
print("-----------------------")
print("List of options ")
print("------------------------")
print("1. To Inches")
print("2. To Yards")
print("3. To miles")
print("4. To Millimeters")
print("5. To Centimeters")
print("6. To Meters")
print("7. To Kilometers")
print("------------------------")
print()
option=int(input("Enter your option :"))

31 | P a g e
length=float(input("Enter length in feet : "))

if(option==1):
result=length*12
print("Given length in inches is %.4f"%(result))
elif(option==2):
result=length/3
print("Given length in yards is %.4f"%result)
elif(option==3):
result=length/5280
print("Given length in miles is %.4f"%result)
elif(option==4):
result=length*305
print("Given length in millimeters is %.4f"%result)
elif(option==5):
result=length*30.48
print("Given length in centimeters is %.4f"%result)
elif(option==6):
result=length/3.281
print("Given length in meters is %.4f"%result)
else:
result=length/3281
print("Given length in kilometers is %.4f"%result)

Output:

32 | P a g e
Exercise 4# c
Question
Write a program to check whether given character is alphabet or not, if yes check whether vowel
or consonant
Objective
To learn and implement operators
Requirement Analysis :
 Read the character
 Compare the input with appropriate values
 Display the result

Program
alpha=input("Enter a character : ")
if((alpha>='A' and alpha<='Z') or (alpha>='a' and alpha<='z')):
if(alpha=='a' or alpha=='A' or alpha=='e' or alpha=='E' or alpha=='i' or alpha=='I' or alpha=='o'
or alpha=='O' or alpha=='u' or alpha=='U'):
print("vowel")
else:
print("consonant")
else:
print("Not an alphabet")

Output

33 | P a g e
Exercise 5# a
Question
Write a program to print the following pattern when n (no. of rows) is given as input,
If n=4,
*
**
***
****

Objective :
 To learn usage of loops
 Apply the problem solving technique using loops concepts
Requirement Analysis:
 Take input no of rows the user need to print
 Assign the symbol “*” to a variable
 Print using for loop with range function
Program
rows=int(input("Enter number of rows "))
star="*"
for i in range(1,rows+1):
print(star*i)

Output:

34 | P a g e
Exercise 5# b
Question
Write a program to display first repeating character from the beginning of the given string. If no
repeating is present, display 'None'
Objective:
To implement string concepts along with decision making
Requirement Analysis:
 Read a string value
 Set count  0
 Compare every string characters using for loop
 Print the string character when both the index values are equal and set count  1
 If count value is 1 then break the loop
 If count value is 0 print a message “None”

Program
string=input("Enter a string")
count=0
for i in range(0,len(string)):
for j in range(i+1,len(string)):
if(string[i]==string[j]):
print(string[i])
count=1
if(count==1):
break
if(count==0):
print("None")

Output:

35 | P a g e
Exercise 5# c
Question
Write a program to print next immediate prime number of the given number
Objective:
To Learn looping concept and apply prime number logic to print next prime value
Requirement Analysis :
 Read a number
 Set count0
 Check if the number is divisible by the values ranging from 1 to the number
 If divisible increase count value
 If count is 2 print the value along with the message

Program
number=int(input("Enter any number :"))
count=0
val=number+1
while(1):
count=0
for i in range(1,val+1):
if(val%i==0):
count=count+1
if(count==2):
print("The next immediate prime numbers is",val)
break
else:
val=val+1

Output:

36 | P a g e
Exercise 6# a
Question
Write a program to display numbers between 1 to n. But, one of the numbers between 1 and n is
unsafe and that number shouldn’t be displayed. Assume, unsafe number is a number which is
divisible by 3
Objective :
To learn loop concepts and decision making
Requirement Analysis :
 Read a number
 And check if the number is visible by 3 ranging from 1 to the number+1
 If the remainder is 0 continue the loop
 Else print the value

Program
number=int(input("Enter a number : "))
for val in range(1,number+1):
if(val%3==0):
continue
else:
print(val,end=" ")

Output:

37 | P a g e
Exercise 6# b
Question
Write a program to input some numbers repeatedly and print their sum. The program ends when
the users say no more to enter i.e. normal termination or program aborts when the number
entered is less than 0
Objective:
To learn the concepts of loops and decision making
Requirement Analysis :
 Print a message to the user stating to accept the input and to quit a negative number is
the input
 Read the input continuously using infinite loop
 If the number is negative then break the loop
 Else add the value to sum
 Finally print the sum
Program
print("Enter the numbers , to quit give a negative number :")
sum_val=0
while(1):
i=int(input())
if(i<0):
break;
else:
sum_val+=i
print("Sum of the values is ",sum_val)

Output:

38 | P a g e
Exercise 6# c
Question
Write a program which takes a string from the user and display each character in single line,
while iterating skip the printing if the character is ‘t’

Objective:
To learn the decision making and loops concepts
Requirement Analysis :
 Read a string
 For every character in the string
 Compare if it is’t’ or ‘T’
 If condition is satisfied then continue the loop else print the character
Program
string=input("Enter any string : ")
for char in string:
if (char=='t' or char=='T'):
continue
else:
print(char)
output :

39 | P a g e
Exercise 7# a
Question :
Write a program to compute cumulative product of a list of numbers
Objective :
To learn lists concepts , decision making , loops

Requirement Analysis:
 Read a string
 Declare empty list
 For every value in the string
 Compare if the string is not empty , then add it to the list
 To find the product set a variable j1
 Iterating through the loop multiply every value of list with j and append it to the newlist

Program
string=input("Enter list of numbers with a separator space : ")
mlist=[]
for i in string:
if i!=" ":
[Link](int(i))
new_list=[]
j=1
for i in range(0,len(mlist)):
j*=mlist[i]
new_list.append(j)

print(new_list)
Output:

40 | P a g e
Exercise 7#b
Question
Write a program to find the sum of corner elements in the given matrix
Objective :
To learn matrix concepts
Requirement Analysis:
 Declare an empty matrix
 Read the size
 Read the input .
 Since the input is in the form a string (every row)
 Split it and convert every value to an int and add it to the list
 For corner elements sum iterate for rows and columns values
 Compare if the of row index and column index is 0 or n-1 if equal then add it to sum

Program
mat=[]
n=int(input("Enter size"))
for x in range(n):
str1=input()
list1=[Link]()
nl=[int(x) for x in list1]
[Link](nl)
sum1=0
for x in range(len(nl)):
for y in range(len(nl)):
if((x==0 or x==n-1) and (y==0 or y==n-1)):
sum1+=mat[x][y]
print("Sum of corner elements ",sum1)

Output:

41 | P a g e
Exercise 7# c
Question
Write a program that asks the user for an integer and creates a list that consists of the factors of
that integer.
Objective :
to implement list concepts and loops
Requirement Analysis:
 read a value
 iterate using for loop diving the number from 1 to the number
 if the remainder is 0 then append the value to list

Program
val=int(input("Enter a number :"))
newlist=[x for x in range(1,val+1) if(val%x==0)]
print("Factors of newlist",newlist)

Output:

42 | P a g e
Exercise 8 # a
Question
1. Given a list of numbers, write a Python program to create a list of tuples having first element
as the number and second element as the cube of the number
Objective :
To learn list ,split function
Requirement Analysis :
 Read the values
 Use split function to split the values as the input is a string format
 Convert every value to integer using comprehensive list syntax
 Now make a tuple with a pair of value and its cube add it to an empty list using
comprehensive list

Program
string=input("Enter the values : ")
numlist=[Link]()
newlist = [int(x) for x in numlist]
result=[(val,(val**3)) for val in newlist]
print(result)

Output:

43 | P a g e
Exercise 8 # b
Question:
Write a program to extract only extreme K elements, i.e maximum and minimum K elements in
Tuple. Input : test_tup = (3, 7, 1, 18, 9), k = 2 Output : 3, 1, 9, 18
Objective:
To solve the problem using list , tuple and function split()
Requirement Analysis:
 Read the values
 Take the input k from user
 Split the values and store them in a list
 Convert each value to integer using comprehensive list
 Sort the values using sort function
 Create an empty list
 Append the values in the new list
 From the length-k to length add the values in new list
 Print the result as a tuple

Program
str1=input("Enter values ")
k=int(input("Enter the k value to extract : "))
list1=[Link](',')
nl=[int(x) for x in list1]
[Link]()
resl=[]
for i in range(k-1,-1,-1):
[Link](nl[i])
for i in range((len(nl)-k),len(nl)):
[Link](nl[i])
print(tuple(resl))

Output:

44 | P a g e
Exercise 8 # c
Question
Write a program to produce a tuple of elements which consists of multiplication of each element
and its adjacent element in the original tuple.
Objective :
To learn tuple concepts
Requirement Analysis :
 Read the values
 Convert the values to list using split function
 Create an empty list

Program
string=input("Enter the values : ")
mlist=[Link](',')
nl=[int(x) for x in mlist]
res_list=[]
for i in range(0,len(nl)-1,2):
k=nl[i]*nl[i+1]
res_list.append(k)

minval=res_list[0]
for i in res_list:
if(minval>i):
minval=i
if(len(nl)%2==1):
res_list.append(nl[len(nl)-1]*min)
print(tuple(res_list))

Output:

45 | P a g e
Exercise 9# a
Question:
Write a program to demonstrate the below functions of Set, i) add() ii) update() iii) discard()
Objective:
To learn the set concepts and set operations
Requirement Analysis:
 Create a set with some values
 Read any number from user to add to first set
 Read any number from user to remove an item from second set
 Update the sets
 Sort them in reverse order
 Apply discard function to remove the value
 Display the values of final sets

Program
set1={3,2,4,9}
print(set1)
n=int(input("Enter a number to add in the set "))
set2={10,8,11}
print(set2)
i=int(input("Enter the element to remove from the set "))
l1=[]
[Link](n)
print("First set of values Sorted : ",sorted((list(set1))))
[Link](set2)
print("Updated values Sorted in Reverse order : ",sorted(list(set1),reverse=True))
[Link](i)
print("Now the values is :",sorted(list(set1)))

Output:

46 | P a g e
Exercise 9 # b
Question
Write a program to demonstrate the below functions of Set, i) pop() ii) union() iii) intersection()
Objective:
To learn set operations
Requirement Analysis :
 Create three sets with values
 Show the popped element from the set
 Create an empty set
 Apply union operation on both the sets and assign it to new set
 Display the values
 Apply intersect operation and display them
Program
set1={"C"}
set2={"Python","Java",47,"C++"}
set3={"JS",57,"SQL",47,"Python"}
print("Popped element is : ")
print([Link]())
set2,set3={str(x) for x in set2},{str(y) for y in set3}
set4={}
set4=[Link](set3)
print("Values of combined set are :")
print(sorted(list(set4)))
print("Values that are common : ")
print(sorted(list([Link](set3))))

Output:

47 | P a g e
Exercise 9 # c
Question
Write a program to demonstrate the below functions of Set, i) difference ii) isdisjoint() iii)
symmetric_difference()
Objective :
To learn set operations
Requirement Analysis:
 Create a set
 Convert each value to string and store them in the sets
 Apply set difference operation
 Check if the sets are disjoint and display the result
 Apply symmetric difference operation and display the result
Program
set1={"Python","Java",47,"C++"}
print("Enter values to create a set with comma seperator :")
set2=str(input())
l1=[Link](',')
set2=set(l1)
set2,set1={str(x) for x in set2},{str(y) for y in set1}
print("set1 - set2 values in sorted order : ")
print(sorted(list([Link](set2)),reverse=True))
print("Disjoint sets : ",end="")
print('True') if [Link](set2) else print('False')
print("Symmetric difference values :")
print(sorted(list(set1.symmetric_difference(set2))))

Output:

48 | P a g e
Exercise 10 #a
Question
Write a program to count the numbers of characters in the string and store them in a dictionary
data structure. Sample Input hello python Sample Output : 1, e : 1, h : 2, l : 2, n : 1, o : 2, p : 1, t :
1, y : 1
Objective:
To learn dictionaries
Requirement Analysis :
 Read a string
 Create an empty dictionary
 Store the count of each string in the dictionary using key value pair
 Display items of dictionary using dictionary function

Program
str1=input("Enter a string to count characters :")
str1=sorted(str1)
d={}
for x in str1:
d[x]=[Link](x)
for u,v in [Link]():
print(u,':',v)

Output:

49 | P a g e
Exercise 10 # b
Question
Write a program to use split and join methods in the string and trace a birthday with a Dictionary
data structure. If birthday is not found, display a message ‘Not found’. Sample Input 25/08/1991
XYZ 12/02/1990 ABC 01/01/1989 PQR 25-08-1991 Sample Output The DOB 25/08/1991 found
whose name is XYZ
Objective:
To learn dictionaries
Requirement Analysis:
 Read a string
 Split it and assign to a variable as list values
 Create an empty dictionary
 Assign the values of first list value as key and second list value as value in the dictionary
 Replace the ‘-‘ character with ‘/’
 For every key value pair in the dictionary compare the user input
 If matching then display else show the message “DoB not found”
Program
str1=input("Enter DOB and strings :")
l1=[Link](' ')
d=dict()
flag=0
for i in range(0,len(l1)-1,2):
d[l1[i]]=l1[i+1]
s=input("Enter the DOB to find : ")
s=[Link]('-','/')
for x,y in [Link]():
if(x==s):
print('The DOB',x,'found whose name is',y)
flag=1
break
if(flag==0):
print("DOB is not found!!")
Output:

50 | P a g e
Exercise 10 # c
Question:
Write a program that combines two given lists into a dictionary Sample Input jkl def abc ghi 10
20 30 40 Sample Output abc:30 def:20 ghi:40 jkl:10
Objective :
To learn dictionary concepts
Requirement Analysis:
 Read the keys from user
 Read the values from user
 Separate keys and values into two different lists using split() function
 Combine them using zip function with dict cast operation and store them in a separate
dictionary
 Print the values using key value pair with a for loop

Program
s1=input("Enter values for key : ")
s2=input("Enter values for values :")

l1=[Link](' ')
l2=[Link](' ')
dict1=dict(zip(l1,l2))
l=list([Link]())
[Link]()
print("Dictionary : ")
dict1=dict(l)
for x,y in [Link]():
print(x+':'+y)

Output:

51 | P a g e
Exercise 11 # a
Question
Write a program to find the reverse of each word in the given list of strings and display them
Objective:
To learn strings and lists
Requirement Analysis:
Read the input from user
Use split function and store in the list
Create an empty list
Compare if it contains alphabet values , if true append to a list by reversing it else append the
actual value without reversing
Print the values in the newlist

Program
s=input("Enter the text :")
list1=[Link]()
list2=[]
for x in range(0,len(list1)):
if(list1[x].isalpha()==True):
[Link](list1[x][::-1])
else:
[Link](list1[x])
for y in list2:
print(y,end=' ')

Output:

52 | P a g e
Exercise 11 # b
Question
Given a string, the task is to write a program to extract overlapping consecutive string slices
from the original string according to size K. K and string is to be given by user
Objective :
To learn string concepts and functions
Requirement Analysis:
 Read the text from user
 Read the size of text of overlap from user
 Create an empty list
 Compare the overlapping size with string size
 If overlapping size is more the string size show “Invalid k value “ message
 Else append the values from string from I value to i+overlapping size using for loop

Program
string=input("Input the string : ")
size=int(input("Enter the size to find overlapping :"))
newlist=[]
if(size>len(string)):
print('Invalid k value')
else:
for i in range(len(string)-size+1):
[Link](string[i:i+size])
print(newlist)

Output:

53 | P a g e
Exercise 11 # c
Question:
Given a string, the task is to write a program to replace every Nth character in a string by the
given value K. String, K and N must be given the user
Objective :
To learn string concepts and built in functions
Requirement Analysis :
 Read the string
 Read the character k and position n
 Check if n is greater than length of the string
 If true print a message “Invalid Input”
 Else
 Process the values to add them in the list and assign the character k to list at the index
 Print the values in the list

Program
string=input("Enter string : ")
k=input("Enter the character k : ")
n=int(input("Enter the position n : "))
if(n>len(string)):
print('Invalid input')
else:
l1=[x for x in string]
for i in range(n-1,len(l1),n):
l1[i]=k
for y in l1:
print(y,end='')
Output:

54 | P a g e
Exercise 12 # a
Question
Write a function called ‘sum_digits’ that is given an integer num and returns the sum of the
digits of num
Objective :
To understand use function concepts
Requirement Analysis :
 Define a function with an input number and return value of sum
 Write the logic of sum of individual digits in the function
 Read the input from user
 Call the function by giving the user input

Program
def sum_of_digits(num):
sum1=0
while(num>0):
sum1=sum1+(num%10)
num//=10
return(sum1)

num=int(input("Enter a number :"))


print("Sum of digits :",sum_of_digits(num))

Output:

55 | P a g e
Exercise 12 # b
Question
Write a function called ‘first_diff’ that is given two strings and returns the first location in which
the strings differ. If the strings are identical, it should return -1
Objective
To learn functions concept and use them
Requirement Analysis :
 Define a function as first_diff with two string inputs
 Write the appropriate logic for finding difference between two string :
 Read the input from user
 Call the function with user input

Program
def first_diff(string1,string2):
x=[Link]()
y=[Link]()
if(len(x) < len(y)):
length=len(x)
else:
length=len(y)
for i in range(length):
if x[int(i)] == y[int(i)]:
print("The location of string same")
else:
b=x[i]
print("The location of string different at : ",int(i),"-->",b)

string1="hello you are learning python now"


string2="hello you are good at learning"
first_diff(string1, string2)
Output:

56 | P a g e
Exercise 12 # c
Question:
Write a function ‘ball_collide’ that takes two balls as parameters and computes if they are
colliding. Your function should return a Boolean representing whether or not the balls are
colliding. [functions] Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the radius. If
(distance between two balls centers) <= (sum of their radii) then they are colliding
Objective :
To learn and implement function concepts
Requirement Analysis:
 Import math function
 Define the function with three values are tuple . In the function write the formula using
[Link] function
 Assign the values for two ball tuples
 Make the function call by giving the values are parameters

Program
import math
def ball_collide(ball_tuple1,ball_tuple2):
d=[Link]((ball_tuple1[0]-ball_tuple2[0])**2 +

(ball_tuple1[1]-ball_tuple2[1])**2)
if(d<=(ball_tuple1[2]+ball_tuple2[2])):
return True
else:
return False

ball_tuple1=(-2,-2,3)
ball_tuple2=(1,1,3)

collision=ball_collide(ball_tuple1,ball_tuple2)
if(collision):
print("Balls are collide.")
else:
print("Balls are not collide.")
Output:

57 | P a g e
Exercise 13 # a
Question
Write a program to work with below functions in math module i) cos() ii) ceil() iii) sqrt
Objective:
To learn built in functions of math module
Requirement analysis :
 Import math module
 Apply cos , ceil and sqrt function and print the result

Program
import math
print("Cos 30 is :",[Link](30))
print("Value after ceil funciton :",[Link](4.5867))
print("Square of 2 is ",[Link](2))

Output:

58 | P a g e
Exercise 13 #b
Question :
Write a program to work with below functions in os module i) name ii) getcwd() iii) listdir() –
Objective :
To learn and apply os modules and built in functions
Requirement Analysis:
 Import os module
 Call listdir,getcwd and name using os module
 Print the result

Program

import os
path = "/"
dir_list = [Link](path)
cwd = [Link]()
name=[Link]
print("Files and directories in '", path, "' :")
print(dir_list)
print("Current working directory:", cwd)
print("Operating system : ",name)

Output:

59 | P a g e
Exercise 13 # c
Question:
Write a program to work with below functions in statistics module
i)mean ii)median iii)mode
Objective :
To learn statistics module and built in functions
Requirement Analysis:
Import numpy and scipy
Initialize a list of values
Compute mean using [Link](list) and similarly median and mode
Display the result

Program
import numpy
from scipy import stats
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
print("Mean : ",[Link](speed))
print("Median : ",[Link](speed))
#The mode() method returns a ModeResult object that contains the mode number (86), and
#count (how many times the mode number appeared (3)).
print("Mode : ",[Link](speed))
Output:

60 | P a g e

You might also like