Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
49 views26 pages

Chapter 1-12 Merged

The document contains a series of programming exercises in Python, each with a specific task and solution. It covers topics such as conditional statements, loops, functions, data structures, and input/output handling. Each question includes example outputs to demonstrate the expected results of the provided solutions.

Uploaded by

chikbhandary2810
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)
49 views26 pages

Chapter 1-12 Merged

The document contains a series of programming exercises in Python, each with a specific task and solution. It covers topics such as conditional statements, loops, functions, data structures, and input/output handling. Each question includes example outputs to demonstrate the expected results of the provided solutions.

Uploaded by

chikbhandary2810
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/ 26

Type C: Programming Practice/Knowledge based

Questions

Question 1

Write a program to print one of the words negative, zero, or


positive, according to whether variable x is less than zero, zero, or
greater than zero, respectively.

Solution

x = int(input("Enter x: "))

if x < 0:
print("negative")
elif x > 0:
print("positive")
else:
print("zero")

Output

Enter x: -5
negative

Enter x: 0
zero

Enter x: 5
positive

Question 2

Write a program that returns True if the input number is an even


number, False otherwise.

Solution

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


if x % 2 == 0:
print("True")
else:
print("False")

Output

Enter a number: 10
True

Enter a number: 5
False

Question 3

Write a Python program that calculates and prints the number of


seconds in a year.

Solution

days = 365
hours = 24
mins = 60
secs = 60
secsInYear = days * hours * mins * secs
print("Number of seconds in a year =", secsInYear)

Output

Number of seconds in a year = 31536000

Question 4

Write a Python program that accepts two integers from the user
and prints a message saying if first number is divisible by second
number or if it is not.

Solution

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


b = int(input("Enter second number: "))
if a % b == 0:
print(a, "is divisible by", b)
else:
print(a, "is not divisible by", b)

Output

Enter first number: 15


Enter second number: 5
15 is divisible by 5

Enter first number: 13


Enter second number: 7
13 is not divisible by 7

Question 5

Write a program that asks the user the day number in a year in the
range 2 to 365 and asks the first day of the year — Sunday or
Monday or Tuesday etc. Then the program should display the day
on the day-number that has been input.

Solution

dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",


"SATURDAY", "SUNDAY"]

dayNum = int(input("Enter day number: "))


firstDay = input("First day of year: ")

if dayNum < 2 or dayNum > 365:


print("Invalid Input")
else:
startDayIdx = dayNames.index(str.upper(firstDay))
currDayIdx = dayNum % 7 + startDayIdx - 1

if currDayIdx >= 7:
currDayIdx = currDayIdx - 7

print("Day on day number", dayNum, ":", dayNames[currDayIdx])


Output

Enter day number: 243


First day of year: FRIDAY
Day on day number 243 : TUESDAY

Question 6

One foot equals 12 inches. Write a function that accepts a length


written in feet as an argument and returns this length written in
inches. Write a second function that asks the user for a number of
feet and returns this value. Write a third function that accepts a
number of inches and displays this to the screen. Use these three
functions to write a program that asks the user for a number of feet
and tells them the corresponding number of inches.

Solution

def feetToInches(lenFeet):
lenInch = lenFeet * 12
return lenInch

def getInput():
len = int(input("Enter length in feet: "))
return len

def displayLength(l):
print("Length in inches =", l)

ipLen = getInput()
inchLen = feetToInches(ipLen)
displayLength(inchLen)

Output

Enter length in feet: 15


Length in inches = 180

Question 7
Write a program that reads an integer N from the keyboard
computes and displays the sum of the numbers from N to (2 * N) if
N is nonnegative. If N is a negative number, then it's the sum of the
numbers from (2 * N) to N. The starting and ending points are
included in the sum.

Solution

n = int(input("Enter N: "))
sum = 0
if n < 0:
for i in range(2 * n, n + 1):
sum += i
else:
for i in range(n, 2 * n + 1):
sum += i

print("Sum =", sum)

Output

Enter N: 5
Sum = 45

Enter N: -5
Sum = -45

Question 8

Write a program that reads a date as an integer in the format


MMDDYYYY. The program will call a function that prints print out
the date in the format <Month Name> <day>, <year>.

Sample run :
Enter date : 12252019
December 25, 2019

Solution

months = ["January", "February", "March", "April", "May", "June",


"July", "August", "September", "October", "November", "December"]

dateStr = input("Enter date in MMDDYYYY format: ")


monthIndex = int(dateStr[:2]) - 1
month = months[monthIndex]
day = dateStr[2:4]
year = dateStr[4:]

newDateStr = month + ' ' + day + ', ' + year


print(newDateStr)

Output

Enter date in MMDDYYYY format: 12252019


December 25, 2019

Question 9

Write a program that prints a table on two columns — table that


helps converting miles into kilometers.

Solution

print('Miles | Kilometres')
print(1, "\t", 1.60934)
for i in range(10, 101, 10):
print(i, "\t", i * 1.60934)

Output

Miles | Kilometres
1 1.60934
10 16.0934
20 32.1868
30 48.2802
40 64.3736
50 80.467
60 96.5604
70 112.6538
80 128.7472
90 144.8406
100 160.934
Question 10

Write another program printing a table with two columns that helps
convert pounds in kilograms.

Solution

print('Pounds | Kilograms')
print(1, "\t", 0.4535)
for i in range(10, 101, 10):
print(i, "\t", i * 0.4535)

Output

Pounds | Kilograms
1 0.4535
10 4.535
20 9.07
30 13.605
40 18.14
50 22.675
60 27.21
70 31.745
80 36.28
90 40.815
100 45.35

Question 11

Write a program that reads two times in military format (0900, 1730)
and prints the number of hours and minutes between the two
times.

A sample run is being given below :


Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes

Solution

ft = input("Please enter the first time : ")


st = input("Please enter the second time : ")

# Converts both times to minutes


fMins = int(ft[:2]) * 60 + int(ft[2:])
sMins = int(st[:2]) * 60 + int(st[2:])

# Subtract the minutes, this will give


# the time duration between the two times
diff = sMins - fMins;

# Convert the difference to hours & mins


hrs = diff // 60
mins = diff % 60

print(hrs, "hours", mins, "minutes")

Output

Please enter the first time : 0900


Please enter the second time : 1730
8 hours 30 minutes

Please enter the first time : 0915


Please enter the second time : 1005
0 hours 50 minutes
Type C: Programming Practice/Knowledge based
Questions

Question 1

Write a program that prompts for a phone number of 10 digits and


two dashes, with dashes after the area code and the next three
numbers. For example, 017-555-1212 is a legal input.
Display if the phone number entered is valid format or not and
display if the phone number is valid or not (i.e., contains just the
digits and dash at specific places).

Solution

phNo = input("Enter the phone number: ")


length = len(phNo)
if length == 12 \
and phNo[3] == "-" \
and phNo[7] == "-" \
and phNo[:3].isdigit() \
and phNo[4:7].isdigit() \
and phNo[8:].isdigit() :
print("Valid Phone Number")
else :
print("Invalid Phone Number")

Output

Enter the phone number: 017-555-1212


Valid Phone Number

=====================================

Enter the phone number: 017-5A5-1212


Invalid Phone Number

Question 2
Write a program that should prompt the user to type some
sentence(s) followed by "enter". It should then print the original
sentence(s) and the following statistics relating to the sentence(s):

 Number of words
 Number of characters (including white-space and punctuation)
 Percentage of characters that are alpha numeric

Hints

 Assume any consecutive sequence of non-blank characters in a


word.

Solution

str = input("Enter a few sentences: ")


length = len(str)
spaceCount = 0
alnumCount = 0

for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1

alnumPercent = alnumCount / length * 100

print("Original Sentences:")
print(str)

print("Number of words =", (spaceCount + 1))


print("Number of characters =", (length))
print("Alphanumeric Percentage =", alnumPercent)

Output

Enter a few sentences: Python was conceived in the late 1980s by


Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the
Netherlands. Its implementation began in December 1989. Python 3.0
was released on 3 December 2008.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI) in the Netherlands. Its implementation
began in December 1989. Python 3.0 was released on 3 December 2008.
Number of words = 34
Number of characters = 205
Alphanumeric Percentage = 80.48780487804879

Question 3

Write a program that takes any two lists L and M of the same size
and adds their elements together to form a new list N whose
elements are sums of the corresponding elements in L and M. For
instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4, 6,
13].

Solution

print("Enter two lists of same size")


L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []

for i in range(len(L)):
N.append(L[i] + M[i])

print("List N:")
print(N)

Output

Enter two lists of same size


Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]

Question 4

Write a program that rotates the elements of a list so that the


element at the first index moves to the second index, the element in
the second index moves to the third index, etc., and the element in
the last index moves to the first index.

Solution

l = eval(input("Enter the list: "))


print("Original List")
print(l)

l = l[-1:] + l[:-1]

print("Rotated List")
print(l)

Output

Enter the list: [8, 10, 13, 25, 7, 11]


Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]

Question 5

Write a short python code segment that prints the longest word in a
list of words.

Solution

my_list = eval(input("Enter the list : "))


longest_word = ""
max_length = 0

for word in my_list:


if len(word) > max_length:
max_length = len(word)
longest_word = word

print("Longest word:", longest_word)

Output
Enter the list : ['red', 'yellow', 'green', 'blue']
Longest word: yellow
Enter the list : ['lion', 'elephant', 'tiger', 'monkey',
'hippopotamus']
Longest word: hippopotamus

Question 6

Write a program that creates a list of all the integers less than 100
that are multiples of 3 or 5.

Solution

a = []
for i in range(0,100):
if (i % 3 == 0) or (i % 5 == 0) :
a.append(i)
print(a)

Output

[0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36,
39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72,
75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99]

Question 7

Define two variables first and second so that first = "Jimmy" and
second = "Johny". Write a short python code segment that swaps
the values assigned to these two variables and prints the results.

Solution

first = "Jimmy"
second = "Johny"
temp = first
first = second
second = temp
print("first =", first)
print("second =", second)
Output

first = Johny
second = Jimmy

Question 8

Write a python program that creates a tuple storing first 9 terms of


Fibonacci series.

Solution

lst = [0,1]
a = 0
b = 1
c = 0

for i in range(7):
c = a + b
a = b
b = c
lst.append(c)

tup = tuple(lst)

print("9 terms of Fibonacci series are:", tup)

Output

9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)

Question 9

Create a dictionary whose keys are month names and whose values
are the number of days in the corresponding months.

(a) Ask the user to enter a month name and use the dictionary to tell
them how many days are in the month.

(b) Print out all of the keys in alphabetical order.


(c) Print out all of the months with 31 days.

(d) Print out the (key-value) pairs sorted by the number of days in
each month.

Solution

days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}

m = input("Enter name of month: ")

if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)

print("Months in alphabetical order are:", sorted(days_in_months))

print("Months with 31 days:", end=" ")


for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")

day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()

month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])
sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)

Output

Enter name of month: may


There are 31 days in may
Months in alphabetical order are: ['april', 'august', 'december',
'february', 'january', 'july', 'june', 'march', 'may', 'november',
'october', 'september']
Months with 31 days: january march may july august october december
Months sorted by days: {'february': 28, 'april': 30, 'june': 30,
'november': 30, 'september': 30, 'august': 31, 'december': 31,
'january': 31, 'july': 31, 'march': 31, 'may': 31, 'october': 31}

Question 10

Write a function called addDict(dict1, dict2) which computes the


union of two dictionaries. It should return a new dictionary, with all
the items in both its arguments (assumed to be dictionaries). If the
same key appears in both arguments, feel free to pick a value from
either.

Solution

def addDict(dict1, dict2):


union_dict = {}
for key, value in dict1.items():
union_dict[key] = value
for key, value in dict2.items():
union_dict[key] = value
return union_dict

dict1 = {'a': 1, 'b': 2}


dict2 = {'b': 3, 'c': 4}
result = addDict(dict1, dict2)
print("Union of dict1 and dict2:", result)

Output
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}

Question 11

Write a program to sort a dictionary's keys using Bubble sort and


produce the sorted keys as a list.

Solution

my_dict = eval(input("Enter the dictionary: "))


keys = list(my_dict.keys())
l = len(keys)
for i in range(l):
for j in range(0, l - i - 1):
if keys[j] > keys[j + 1]:
keys[j], keys[j + 1] = keys[j + 1], keys[j]
print("Sorted keys:",keys)

Output

Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}


Sorted keys: ['a', 'c', 'f', 'r']

Question 12

Write a program to sort a dictionary's values using Bubble sort and


produce the sorted values as a list.

Solution

my_dict = eval(input("Enter the dictionary: "))


values = list(my_dict.values())
l = len(values)
for i in range(l):
for j in range(0, l - i - 1):
if values[j] > values[j + 1]:
# Swap values
values[j], values[j + 1] = values[j + 1], values[j]
print("Sorted values:", values)

Output
Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]
Type C: Programming Practice/Knowledge based
Questions

Question 1

Write a function that takes amount-in-dollars and dollar-to-rupee


conversion price; it then returns the amount converted to rupees.
Create the function in both void and non-void forms.

Solution

def convert_dollars_to_rupees(amount_in_dollars, conversion_rate):


amount_in_rupees = amount_in_dollars * conversion_rate
return amount_in_rupees

def convert_dollars_to_rupees_void(amount_in_dollars,
conversion_rate):
amount_in_rupees = amount_in_dollars * conversion_rate
print("Amount in rupees:", amount_in_rupees)

amount = float(input("Enter amount in dollars "))


conversion_rate = float(input("Enter conversion rate "))

# Non-void function call


converted_amount = convert_dollars_to_rupees(amount, conversion_rate)
print("Converted amount (non-void function):", converted_amount)

# Void function call


convert_dollars_to_rupees_void(amount, conversion_rate)

Output

Enter amount in dollars 50


Enter conversion rate 74.5
Converted amount (non-void function): 3725.0
Amount in rupees: 3725.0

Enter amount in dollars 100


Enter conversion rate 75
Converted amount (non-void function): 7500.0
Amount in rupees: 7500.0

Question 2

Write a function to calculate volume of a box with appropriate


default values for its parameters. Your function should have the
following input parameters :

(a) length of box ;

(b) width of box ;

(c) height of box.

Test it by writing complete program to invoke it.

Solution

def calculate_volume(length = 5, width = 3, height = 2):


return length * width * height

default_volume = calculate_volume()
print("Volume of the box with default values:", default_volume)

v = calculate_volume(10, 7, 15)
print("Volume of the box with default values:", v)

a = calculate_volume(length = 23, height = 6)


print("Volume of the box with default values:", a)

b = calculate_volume(width = 19)
print("Volume of the box with default values:", b)

Output

Volume of the box with default values: 30


Volume of the box with default values: 1050
Volume of the box with default values: 414
Volume of the box with default values: 190

Question 3
Write a program to have following functions :

(i) a function that takes a number as argument and calculates cube


for it. The function does not return a value. If there is no value
passed to the function in function call, the function should calculate
cube of 2.

(ii) a function that takes two char arguments and returns True if
both the arguments are equal otherwise False.

Test both these functions by giving appropriate function call


statements.

Solution

# Function to calculate cube of a number


def calculate_cube(number = 2):
cube = number ** 3
print("Cube of", number, "is", cube)

# Function to check if two characters are equal


def check_equal_chars(char1, char2):
return char1 == char2

calculate_cube(3)
calculate_cube()

char1 = 'a'
char2 = 'b'
print("Characters are equal:", check_equal_chars(char1, char1))
print("Characters are equal:", check_equal_chars(char1, char2))

Output

Cube of 3 is 27
Cube of 2 is 8
Characters are equal: True
Characters are equal: False

Question 4
Write a function that receives two numbers and generates a
random number from that range. Using this function, the main
program should be able to print three numbers randomly.

Solution

import random

def generate_random_number(num1, num2):


low = min(num1, num2)
high = max(num1, num2)
return random.randint(low, high)

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))

for i in range(3):
random_num = generate_random_number(num1, num2)
print("Random number between", num1, "and", num2, ":",
random_num)

Output

Enter the first number: 2


Enter the second number: 78
Random number between 2 and 78 : 77
Random number between 2 and 78 : 43
Random number between 2 and 78 : 52

Enter the first number: 100


Enter the second number: 599
Random number between 100 and 599 : 187
Random number between 100 and 599 : 404
Random number between 100 and 599 : 451

Question 5

Write a function that receives two string arguments and checks


whether they are same-length strings (returns True in this case
otherwise False).

Solution
def same_length_strings(str1, str2):
return len(str1) == len(str2)

s1 = "hello"
s2 = "world"
s3 = "python"

print(same_length_strings(s1, s2))
print(same_length_strings(s1, s3))

Output

True
False

Question 6

Write a function namely nthRoot( ) that receives two parameters x


and n and returns nth root of x i.e., x^(1/n).
The default value of n is 2.

Solution

def nthRoot(x, n = 2):


return x ** (1/n)

x = int(input("Enter the value of x:"))


n = int(input("Enter the value of n:"))

result = nthRoot(x, n)
print("The", n, "th root of", x, "is:", result)

default_result = nthRoot(x)
print("The square root of", x, "is:", default_result)

Output

Enter the value of x:36


Enter the value of n:6
The 6 th root of 36 is: 1.8171205928321397
The square root of 36 is: 6.0
Question 7

Write a function that takes a number n and then returns a randomly


generated number having exactly n digits (not starting with zero)
e.g., if n is 2 then function can randomly return a number 10-99 but
07, 02 etc. are not valid two digit numbers.

Solution

import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)

n = int(input("Enter the value of n:"))


random_number = generate_number(n)
print("Random number:", random_number)

Output

Enter the value of n:2


Random number: 10

Enter the value of n:2


Random number: 50

Enter the value of n:3


Random number: 899

Enter the value of n:4


Random number: 1204

Question 8

Write a function that takes two numbers and returns the number
that has minimum one's digit.

[For example, if numbers passed are 491 and 278, then the function
will return 491 because it has got minimum one's digit out of two
given numbers (491's 1 is < 278's 8)].
Solution

def min_ones_digit(num1, num2):


ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
if ones_digit_num1 < ones_digit_num2:
return num1
else:
return num2

num1 = int(input("Enter first number:"))


num2 = int(input("Enter second number:"))
result = min_ones_digit(num1, num2)
print("Number with minimum one's digit:", result)

Output

Enter first number:491


Enter second number:278
Number with minimum one's digit: 491

Enter first number:543


Enter second number:765
Number with minimum one's digit: 543

Question 9

Write a program that generates a series using a function which


takes first and last values of the series and then generates four
terms that are equidistant e.g., if two numbers passed are 1 and 7
then function returns 1 3 5 7.

Solution

def generate_series(first, last):


step = (last - first) // 3
series = [first, first + step, first + 2 * step, last]
return series

first_value = int(input("Enter first value:"))


last_value = int(input("Enter last value:"))
result_series = generate_series(first_value, last_value)
print("Generated Series:", result_series)

Output

Enter first value:1


Enter last value:7
Generated Series: [1, 3, 5, 7]

Enter first value:10


Enter last value:25
Generated Series: [10, 15, 20, 25]

You might also like