0% found this document useful (0 votes)
211 views10 pages

FPP Imp Questions (Unit I & II) by Mks

The document contains Python exercises divided into two units. Unit I includes simple programs and exercises related to basic Python concepts like strings, numbers, functions etc. Unit II focuses on functions, coding exercises and important programs related to Unit I concepts like date calculations, pattern printing, Fibonacci series etc.
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)
211 views10 pages

FPP Imp Questions (Unit I & II) by Mks

The document contains Python exercises divided into two units. Unit I includes simple programs and exercises related to basic Python concepts like strings, numbers, functions etc. Unit II focuses on functions, coding exercises and important programs related to Unit I concepts like date calculations, pattern printing, Fibonacci series etc.
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
You are on page 1/ 10

PYTHON EXERCISES (UNIT-I & UNIT-II)

SIMPLE PROGRAMS AND EXERCISES:


UNIT-I
1. What is the result of this expression: “*” * 10
2. What are the primitive built-in types in Python?
3. When should we use “”” (tripe quotes) to define strings?
4. Assuming (name = “John Smith”), what does name[1] return?
5. What about name[-2]?
6. What about name[1:-1]?
7. How to get the length of name?
8. What are the escape sequences in Python?
9. What is the result of f“{2+2}+{10%3}”?
10. Given (name = “john smith”), what will name.title() return?
11. What does name.strip() do?
12. What will name.find(“Smith”) return?
13. What will be the value of name after we call name.replace(“j”, “k”)?
14. How can we check to see if name contains “John”?
15. What is the difference between 10 / 3 and 10 // 3?
16. What is the result of 10 ** 3?
17. Given (x = 1), what will be the value of after we run (x += 2)?
18. How can we round a number?
19. What is the result of float(1)?
20. What is the result of bool(“False”)?
21. What is the result of 10 == “10”?
22. What is the result of “bag” > “apple”?
23. What is the result of not(True or False)?

UNIT-II
1. What does range(1, 10, 2) return?
2. Name 3 iterable objects in Python.
Functions
1. What is the difference between a parameter and an argument?
2. All functions in Python by default return …?
3. What are keyword arguments and when should we use them?
4. How can we make a parameter of a function optional?
5. What happens when we prefix a parameter with an asterisk (*)?
6. What is scope?
7. What is the difference between local and global variables?
8. Why is using the global statement a bad practice?

Coding Exercises
1. Write a function that returns the maximum of two numbers.
2. Write a function called fizz_buzz that takes a number.
1. If the number is divisible by 3, it should return “Fizz”.
2. If it is divisible by 5, it should return “Buzz”.
3. If it is divisible by both 3 and 5, it should return “FizzBuzz”.
4. Otherwise, it should return the same number.
3. Write a function for checking the speed of drivers. This function should have one parameter: speed.
1. If speed is less than 70, it should print “Ok”.
2. Otherwise, for every 5km above the speed limit (70), it should give the driver one demerit point and print
the total number of demerit points. For example, if the speed is 80, it should print: “Points: 2”.
3. If the driver gets more than 12 points, the function should print: “License suspended”
4. Write a function called showNumbers that takes a parameter called limit. It should print all the numbers
between 0 and limit with a label to identify the even and odd numbers. For example, if the limit is 3, it should
print:
o 0 EVEN
o 1 ODD
o 2 EVEN
o 3 ODD
5. Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if
limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
6. Write a function called show_stars(rows). If rows is 5, it should print the following:
o *
o **
o ***
o ****
o *****
7. Write a function that prints all the prime numbers between 0 and limit where limit is a parameter.

Important programs and solutions(UNIT-I)


Q1) Write a Python program to get the Python version you are using.:
Solution:
import sys
print("Python version")
print (sys.version)

Q2) Write a Python program to print the calendar of a given month and year.
import calendar
y = int(input("Input the year : "))
m = int(input("Input the month : "))
print(calendar.month(y, m))

Q3) Write a Python program to calculate number of days between two dates.
from datetime import date
f_date = date(2014, 7, 2)
l_date = date(2014, 7, 11)
delta = l_date - f_date
print(delta.days)

Q4) Write a Python program to get the the volume of a sphere with radius 6.
pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the sphere is: ',V)

Q5) Write a Python program to find whether a given number (accept from the user) is even or odd, print out an
appropriate message to the user.
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")

Q6) Write a Python program to test whether a passed letter is a vowel or not.
x=input(“enter an alphabet”)
if x in “aeiou”:
print(“vowel”)
else:
print(“consonant”)

Q7)Write a Python program to compute the future value of a specified principal amount, rate of interest, and a
number of years.
amt = 10000
int = 3.5
years = 7

future_value = amt*((1+(0.01*int)) ** years)


print(round(future_value,2))

Q8) Write a Python program to calculate body mass index.


height = float(input("Input your height in meters: "))
weight = float(input("Input your weight in kilogram: "))
print("Your body mass index is: ", round(weight / (height * height), 2))

Q9) Write a Python program to get the command-line arguments (name of the script, the number of arguments,
arguments) passed to a script.
import sys
print("This is the name/path of the script:"),sys.argv[0]
print("Number of arguments:",len(sys.argv))
print("Argument List:",str(sys.argv))

Q10) Write a Python program to get the size of an object in bytes.


import sys
str1 = "one"
str2 = "four"
str3 = "three"
print()
print("Memory size of '"+str1+"' = "+str(sys.getsizeof(str1))+ " bytes")
print("Memory size of '"+str2+"' = "+str(sys.getsizeof(str2))+ " bytes")
print("Memory size of '"+str3+"' = "+str(sys.getsizeof(str3))+ " bytes")
print()

Q11) Write a Python program to concatenate N strings.


list_of_colors = ['Red', 'White', 'Black']
colors = '-'.join(list_of_colors)
print()
print("All Colors: "+colors)
print()

Q12) Write a Python program to count the number of occurrence of a specific character in a string.
s = "The quick brown fox jumps over the lazy dog."
print()
print(s.count("q"))
print()

Q13) Write a Python program to create a copy of its own source code.
print()
print((lambda str='print(lambda str=%r: (str %% str))()': (str % str))())
print()

Q14) Write a Python program to swap two variables.


a = 30
b = 20
print("\nBefore swap a = %d and b = %d" %(a, b))
a, b = b, a
print("\nAfter swaping a = %d and b = %d" %(a, b))
print()

Q15) Write a Python program to clear the screen or terminal.


import os
import time
# for windows
# os.system('cls')
os.system("ls")
time.sleep(2)
# Ubuntu version 10.10
os.system('clear')

Q16) Write a Python program to check if a number is positive, negative or zero.


num = float(input("Input a number: "))
if num > 0:
print("It is positive number")
elif num == 0:
print("It is Zero")
else:
print("It is a negative number")

Q17) Write a Python program to print Unicode characters.


str = u'\u0050\u0079\u0074\u0068\u006f\u006e \u0045\u0078\u0065\u0072\u0063\u0069\u0073\u0065\u0073 \u002d
\u0077\u0033\u0072\u0065\u0073\u006f\u0075\u0072\u0063\u0065'
print()
print(str)
print()

Q18) Write a Python program to determine the largest and smallest integers, longs, floats.
import sys
print("Float value information: ",sys.float_info)
print("\nInteger value information: ",sys.int_info)
print("\nMaximum size of an integer: ",sys.maxsize)

Q19) Write a Python program to check if lowercase letters exist in a string.


str1 = 'A8238i823acdeOUEI'
print(any(c.islower() for c in str1))

Q20) Write a Python program to convert true to 1 and false to 0.


x = 'true'
x = int(x == 'true')
print(x)
x = 'abcd'
x = int(x == 'true')
print(x)

Q21) Write a Python program to convert an integer to binary keep leading zeros.
x = 12
print(format(x, '08b'))
print(format(x, '010b'))
output:
00001100
0000001100

Q22) Write a Python program to create any possible string by using 'a', 'e', 'i', 'o', 'u'. Use the characters exactly
once.
import random
char_list = ['a','e','i','o','u']
random.shuffle(char_list)
print(char_list)

Q23) Write a Python program to find the operating system name, platform and platform release date.
import os, platform
print("Operating system name:")
print(os.name)
print("Platform name:")
print(platform.system())
print("Platform release:")
print(platform.release())

Q24) Write a Python program to construct the following pattern, using a nested for loop.
*
**
***
****
*****
****
***
**
*

n=5;
for i in range(n):
for j in range(i):
print ('* ', end="")
print('')

for i in range(n,0,-1):
for j in range(i):
print('* ', end="")
print('')

Q25) Write a Python program that accepts a word from the user and reverse it.
word = input("Input a word to reverse: ")

for char in range(len(word) - 1, -1, -1):


print(word[char], end="")
print("\n")
Q26) Write a Python program to count the number of even and odd numbers from a series of numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)

Q27) Write a Python program that prints each item and its corresponding type from the following list.
Sample List : datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}]

datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
for item in datalist:
print ("Type of ",item, " is ", type(item))

Q28) Write a Python program to get the Fibonacci series between 0 to 50.
x,y=0,1

while y<50:
print(y)
x,y = y,x+y

Q29) Write a Python program which iterates the integers from 1 to 50. For multiples of three print "Fizz" instead
of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five
print "FizzBuzz".
for fizzbuzz in range(50):
if fizzbuzz % 3 == 0 and fizzbuzz % 5 == 0:
print("fizzbuzz")
continue
elif fizzbuzz % 3 == 0:
print("fizz")
continue
elif fizzbuzz % 5 == 0:
print("buzz")
continue
print(fizzbuzz)

Q30) Write a Python program that accepts a string and calculate the number of digits and letters.
s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)

Q31) Write a Python program to check a triangle is equilateral, isosceles or scalene.


Note :
An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.
print("Input lengths of the triangle sides: ")
x = int(input("x: "))
y = int(input("y: "))
z = int(input("z: "))

if x == y == z:
print("Equilateral triangle")
elif x==y or y==z or z==x:
print("isosceles triangle")
else:
print("Scalene triangle")

Q32) Write a Python program to find the median of three values.


a = float(input("Input first number: "))
b = float(input("Input second number: "))
c = float(input("Input third number: "))
if a > b:
if a < c:
median = a
elif b > c:
median = b
else:
median = c
else:
if a > c:
median = a
elif b < c:
median = b
else:
median = c

print("The median is", median)

Q33) Write a Python program to construct the following pattern, using a nested loop number.
for i in range(10):
print(str(i) * i)
Q34) Check Armstrong number (for 3 digits)
# Python program to check if the number provided by the user is an Armstrong number or not

# take input from the user


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

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output 1
Enter a number: 663
663 is not an Armstrong number

Q35) to Find the Factorial of a Number

# Python program to find the factorial of a number provided by the user.

# change the value for a different result


num = 7
# uncomment to take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Q36) Python Program to Check Prime Number


# Python program to check if the input number is prime or not

num = 407

# take input from the user


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

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

37) Python Program to Print all Prime Numbers in an Interval


# Python program to display all the prime numbers within an interval

# change the values of lower and upper for a different result


lower = 900
upper = 1000

# uncomment the following lines to take input from the user


#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):


# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

38) Python Program to Find Numbers Divisible by Another Number


# Python Program to find numbers divisible by thirteen from a list using anonymous function
# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter


result = list(filter(lambda x: (x % 13 == 0), my_list))

# display the result


print("Numbers divisible by 13 are",result)

39) Python Program to Find HCF or GCD


# Python program to find the H.C.F of two input number

# define a function
def computeHCF(x, y):

# choose the smaller number


if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i

return hcf

num1 = 54
num2 = 24

# take input from the user


# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))

print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))

40) Python Program to Find Factors of Number


# Python Program to find the factors of a number

# define a function
def print_factors(x):
# This function takes a number and prints the factors

print("The factors of",x,"are:")


for i in range(1, x + 1):
if x % i == 0:
print(i)

# change this value for a different result.


num = 320

# uncomment the following line to take input from the user


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

print_factors(num)
OUTPUT:
The factors of 320 are:
1
2
4
5
8
10
16
20
32
40
64
80
160
320

Q41) Python Program to Add Two Matrices


# Program to add two matrices using nested loop

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]

for r in result:
print(r)

Q42) Python Program to Transpose a Matrix


# Program to transpose a matrix using nested loop

X = [[12,7],
[4 ,5],
[3 ,8]]

result = [[0,0,0],
[0,0,0]]

# iterate through rows


for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]

for r in result:
print(r)

Q43) Python Program to Multiply Two Matrices


# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

44) Python Program to Check Whether a String is Palindrome or Not


# Program to check if a string
# is palindrome or not

# change this value for a different output


my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")

45) Python Program to Sort Words in Alphabetic Order


# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result


my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

46) Python Program to Convert Decimal to Binary, Octal and Hexadecimal


# Python program to convert decimal number into binary, octal and hexadecimal number system

# Change this line for a different result


dec = 344

print("The decimal value of",dec,"is:")


print(bin(dec),"in binary.")
print(oct(dec),"in octal.")
print(hex(dec),"in hexadecimal.")

You might also like