0% found this document useful (0 votes)
123 views

Assignment (Jatin)

The document contains a Python programming assignment with multiple questions and their solutions. Some key details: - The assignment contains questions on printing patterns, calculations with formulas, unit conversions, and more. - Each question includes the problem statement and the provided Python code solution. - There are over 20 questions in total across two chapters covering basic Python programming concepts.

Uploaded by

Vikas Bishnoi042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

Assignment (Jatin)

The document contains a Python programming assignment with multiple questions and their solutions. Some key details: - The assignment contains questions on printing patterns, calculations with formulas, unit conversions, and more. - Each question includes the problem statement and the provided Python code solution. - There are over 20 questions in total across two chapters covering basic Python programming concepts.

Uploaded by

Vikas Bishnoi042
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

ASSIGNMENT

NAME: JATIN
ROLL NO:APS21093
DANIEL LIANG BACK EXERCISES:
CHAPTER-1
Q-Write a program that displays Welcome to python,Welcome to computer science and
Programming is fun?

Ans-print(“Welcome to python”)
print(“Welcome to computer science”)
print(“Programming is fun”)

Q-Write a program that displays Welcome to python five times?

Ans-n=("Welcome to python")
for i in range(0,5):
print(n)

Q-Write a program that displays the following patterns?

FFFFFFF U U NN NN
FF U U NNN NN
FFFFFFF U U NN N NN
FF U U NN N NN
FF UUU NN NNN

Ans- N,U,F=””,””,””
P=””
i=1
while i<=5:
if i==1 or i==3:
f=”FFFFFFF”
else:
f=”FF “
if: i==4:
U=” U U “
elif:i==5:
U= ” UUU “
else:
U=”U U”
N=”NN”
J=1
while j<5:
if j==(i-1):
N=N+”N”
else:
N=N+” “
j=j+1
N=N+”NN”
P=F+” “+U+” “+N
print(str(p))
i=i+1

Q-Write a program that displays the following code?

a a**2 a**3
1 1 1
2 4 8
3 9 27
4 16 64

Ans-print("a","a**2","a**3")
for i in range(1,5):
print(i,i**2,i**3,sep=" ")
print("\r")

Q-Write a program that displays the result of?

9.5*4.5-2.5*3/45.5-3.5

Ans-m=9.5*4.5 #storing first half value of numerator

n=2.5*3 #storing second half value numerator

c=m-n #final value of numerator

v=45.5-3.5 #final value of denominator

b=c/v #final calculated value

print(b) #printing result

Q-Write a program that displays the result of 1+2+3+4+5+6+7+8+9?

Ans-m=0
for i in range(1,10):
m=m+i
print(m)

Q-Value of pie can be computed by using the following formula:

Value of pie=4*(1-1/3+1/5-1/7+1/9-1/11………)

Write a program that displays the result of 4*(1-1/3+1/5-1/7+1/9-1/11) and

4*(1-1/3+1/5-1/7+1/9-1/11+1/13-1/15) ?

Ans- t=int(input("enter number of terms"))


pi=0
n=4
d=1
for i in range(1,t+1):
a=2*(i%2)-1
pi=pi+a*n/d
d=d+2
print(pi)

Q-Write a program that displays the area and perimeter of a circle that has a radius of 5.5
using the following formulas:
area=radius*radius*pie
perimeter=2*radius*pie ?

Ans-radius=5.5
area=(radius**2)*3.14
perimeter=(2*3.14)*radius
print(“area of circle”,area)
print(“perimeter of circle”,perimeter)

Q-Write a program that displays the area and perimeter of a rectangle with the width of 4.5
and height of 7.9 using the following formula:

Area=height*width

Ans-width=4.5
height=7.9
area=height*width
perimeter=2*(height + width)
print(“area of rectangle”,area)
print(“perimeter of rectangle”,perimeter)

Q-Assume a runner runs 14 kilometers in 45 minutes and 30 seconds.Write a program that


displays the average speed in miles per hour.(Note that 1 mile is 1.6 kilometers.)?

Ans-kilometers=14
miles=kilometers/1.6
minutes=45
seconds=30
hours=(minutes/60) + (seconds/3600)
speed=miles/hours
print(“speed in miles per hour is”,speed)
Q-The US census bureauprojects population based on the following assumptions:

One brith every 5 sceonds


one death every 13 seconds
one immigrant every 45 seconds

Write a program to display the population for each of the next five years. Assume the
current population is 312032486 and one year has 365 days.

Hint: in Python, you can use integer division operator // to perform division. The result is an
integer.
For example, 5 // 4 is 1 (not 1.25) and 10 // 4 is 2 (not 2.5).

Ans- p=312032486
b=(365*24*60*60)//5
d=(365*24*60*60)//13
m=(365*24*60*60)//45
for i in range(1,6):
r=i*(b+m-d)+p
print(r)

CHAPTER 2
Q- Write a program that reads a Celsius degree from the console and converts it to
Fahrenheit and displays the result. The formula for the conversion is as follows: Fahrenheit
= (9 / 5) * Celsius + 32
Here is a sample run of the program:

Enter a degree in Celsius: 43

43 Celsius is 109.4 Fahrenheit

Ans-n=int(input(“enter a degree in Celsius ”))


f=((9/5)*n)+32
print(n,” Celsius is ”,f,” Fahrenheit)

Q- Write a program that reads in the radius and length of a cylinder and computes the area
and volume using the following formulas:
area=radius*radius*pie
volume=area*length
Here is a sample run:
enter the radius and length of a cylinder:5.5,12
the area is 95.0331
the volume is 1140.4

Ans- radius, length = eval(input("Enter the radius and length of a cylinder: "))
area = radius * radius * 3.14159
volume = area * length
print("The area is", area)
print("The volume of the cylinder is", volume)
Q- Write a program that reads a number in feet, converts it into meters, and
displays the result. One foot is 0.305 meters.
Here is a sample run:
Enter a value for feet:16.5
16.5 feet is 5.0325 meters 

Ans-n=int(input(“enter a value for feet:”))


m=n*0.305
print(n,”feet is”,m,”meters”)

Q-Write a program that converts pounds into kilograms. The program prompts the user to
enter a value in pounds, converts it to kilograms, and displays the result. One pound is
0.454 kilograms.
Here is a sample run:

Enter a value in pounds:55.5


55.5 pounds is 25.197 kilograms

Ans- pounds= int(input("Enter a number in pounds: "))

kilograms = pounds * 0.454;

print(pounds, "pounds is", kilograms, "kilograms")

Q-Write a program that reads the subtotal and the gratuity rate and computes the gratuity
and total. For example, if the user enters 10 for the subtotal and 15% for the gratuity rate,
the program displays 1.5 as the gratuity and 11.5 as the total.
Here is a sample run:

Enter the subtotal and a gratuity rate: 15.69,15

The gratuity is 2.35 and the total is 18.04

Ans-subtotal, gratuityrate = eval(input("Enter the subtotal and a gratuity rate"))


gratuity=subtotal*(gratuityrate/100)
total=subtotal+gratuity
print("the gratuity is",gratuity,"and the total is",total)

Q-Write a program that reads an integer between 0 and 1000 and adds all the digits in the
integer. For example, if an integer is 932, the sum of all its digits is 14. (Hint: Use the %
operator to extract digits, and use the // operator to remove the extracted digit. For instance,
932 % 10 = 2 and 932 // 10 = 93.)

Here is a sample run: 999

Enter a number between 0 and 1000:

The sum of the digits is 27

Ans-number = eval(input("Enter an integer between 0 and 1000: "))


lastDigit = number % 10
remainingNumber = number // 10
econdLastDigit = remainingNumber % 10
remainingNumb = remainingNumber // 10
thirdLastDigit = remainingNumb % 10

sum = lastDigit + secondLastDigit + thirdLastDigit

print("The sum of all digits in", number, "is", sum)

Q-Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays
the number of years and days for the minutes. For simplicity, assume a year has 365 days.
Here is a sample run:

Enter the number of minutes:1000000000

1000000000 minutes is approximately 1902 years and 214 days


Ans-n=int(input(“enter number of minutes”)
m=n//60
d=m//24
y=d//365
s=d%365
print(n,”minutes is approximately”,y,”years and”,s,”days”)

Q-Write a program that calculates the energy needed to heat water from an initial
temperature to a final temperature. Your program should prompt the user to enter the
amount of water in kilograms and the initial and final temperatures of the water. The formula
to compute the energy is

Q = M * (finalTemperature – initialTemperature) * 4184

where M is the weight of water in kilograms, temperatures are in degrees Celsius,

and energy Q is measured in joules.

Here is a sample run:

Enter the amount of water in kilograms: 10.5

Enter the initial temperature: 3.5

Enter the final temperature: 55.5

The energy needed is 1625484.0

Ans- mass = int(input("Enter the amount of water in kilograms: "))

initialTemperature = int(input("Enter the initial temperature: "))

finalTemperature = int(input("Enter the final temperature: "))

energy = mass * (finalTemperature - initialTemperature) * 4184

print("The energy needed is", energy)

Q-How cold is it outside? The temperature alone is not enough to provide the answer. Other
factors including wind speed, relative humidity, and sunshine play important roles in
determining coldness outside. In 2001, the National Weather Service (NWS) implemented
the new wind-chill temperature to measure the coldness using temperature and wind speed.
The formula is given as follows:

twc = 35.74 + 0.6215ta - 35.75v0.16 + 0.4275tav0.16

where ta is the outside temperature measured in degrees Fahrenheit and v is the

speed measured in miles per hour.twc is the wind-chill temperature. The formula

cannot be used for wind speeds below 2 mph or for temperatures below -58F or

above 41°F.

Write a program that prompts the user to enter a temperature between -58F and

41°F and a wind speed greater than or equal to 2 and displays the wind-chill tem-

perature.

Here is a sample run:

Enter the temperature in Fahrenheit between -58 and 41: 5.3

Enter the win speed in miles per hour : 6

The wind chill index is -5.56707

Ans- n=eval(input("enter temperature in fahernheit between -58 and 41"))

if n<=41 and n>=-58:

m=eval(input("enter wind speed in miles per hour greater than 2 mph"))

if m>=2:

s=35.74 + 0.6215*n - 35.75*(m**0.16) + 0.4275*(n*(m**0.16))

print("the chill wind index is",s)

else:print("please enter wind above 2mph")


else:print("please enter value between -58 and 41")

Q- Given an airplane’s acceleration a and take-off speed v, you can compute the minimum
runway length needed for an airplane to take off using the following formula:

Length=v**2/2a

Write a program that prompts the user to enter v in meters/second (m/s) and the

acceleration a in meters/second squared and displays the minimum runway

length. Here is a sample run:

Enter speed and acceleration: 60,3

The minimum runway length for this airplane is 514.286 meters ?

Ans- v, a = eval(input("Enter speed and acceleration: "))

length = v * v / (2 * a)

print("The minimum runway length for this airplane is", length, "meters")

Q- Suppose you want to deposit a certain amount of money into a savings account with a
fixed annual interest rate.
What amount do you need to deposit in order to have $5,000 in the account after three
years?

The initial deposit amount can be obtained using the following formula:

INITIAL DEPOSIT AMOUNT:

FINAL ACCOUNT VALUE/(1+YEARLY INTREST RATE)*NUMBER OF YEARS

Write a program that prompts the user to enter final account value, annual interest rate in
percent, and the number of years, and displays the initial deposit amount.
Here is a sample run:
Enter final account value: 1000
Enter annual interest rate in percent: 4.25
Enter number of years: 5
Initial deposit value is 808.8639197424636
Ans- n=eval(input("enter final account value"))

m=eval(input("enter annual intrest rate in percent"))

s=eval(input("enter number of years"))

d=m/12

h=s*12

k=(1+d)*h

id=n/k

print("intial deposit value is",id)

Q- ) Write a program that displays the following table:

A b a ** b

1 2 1

2 3 8

3 4 81

4 5 1024

5 6 15625

Ans- print("a" , "b", "a*b")

for i in range(1,6):

print(i , i+1, i**(i+1))

Q- )Write a program that prompts the user to enter a four-digit integer and displays the
number in reverse order.
Here is a sample run:3125
Enter an integer: 

1
2

Ans-n=int(input(“enter any integer”))


n1=n%10
n=n//10
n2=n%10
n=n//10
n3=n%10
n=n//10
n4=n%10
print(n4)
print(n3)
print(n2)
print(n1)

Q- Write a program that prompts the user to enter the three points (x1, y1), (x2, y2), and (x3,
y3) of a triangle and displays its area.
The formula for computing the area of a triangle is 

s = (side1 + side2 + side3) / 2

area = 2(s(s - side1)(s - side2)(s - side3))**1/2

Here is a sample run:

Enter three points for a triangle: (1.5, -3.4),( 4.6, 5),( 9.5, -3.4)

The area of the triangle is 33.6

Ans-x1, y1, x2, y2, x3, y3 = eval(input("Enter three points for a triangle: "))

side1 = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5

side2 = ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3)) ** 0.5

side3 = ((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2)) ** 0.5

s = (side1 + side2 + side3) / 2;


area = (s * (s - side1) * (s - side2) * (s - side3)) ** 0.5

print("The area of the triangle is", area)

Q-Write a program that prompts the user to enter the side of a hexagon and displays its
area. The formula for computing the area of a hexagon is

Area = (3 *(3**1/2)/2)S**2 where S is length of a side.


here is sample run:
Enter the side: 5.5
The area of the hexagon is 78.5895

Ans-side=float(input(“enter the side”))


area=(3*3**0.5*side**2)/2
print(“the area of the hexagon is “,area)

Q-) Average acceleration is defined as the change of velocity divided by the time taken to
make the change, as shown in the following formula:

A= (V1-V0)/T

Write a program that prompts the user to enter the starting velocity V0 in

meters/second, the ending velocity in V1 meters/second, and the time span T in

seconds, and displays the average acceleration.

Here is a sample run:

Enter v0, v1, and t: 5.5, 50.9, 4.5


The average acceleration is 10.0889

Ans-v0, v1, t = eval(input("Enter v0, v1, and t: "))

a = (v1 - v0) / t

print("The average acceleration is", a)

Q-Body mass index (BMI) is a measure of health based on weight. It can be calculated by
taking your weight in kilograms and dividing it by the square of your height in meters. Write
a program that prompts the user to enter a weight in pounds and height in inches and
displays the BMI.
Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters.

Here is a sample run:

Enter weight in pounds: 50

Enter height in inches:  95.5

BMI is 26.8573

Ans-n=eval(input(“enter waight in pounds”))


m=eval(input(“enter height in inches”))
s=0.45359237*n
k=0.0254*m
a=s/(k**2)
print(“BMI is”,a)

CHAP 1 MURACH BACK EXERCISE

ANS 1.1 import locale

# set the locale for use in currency formatting

locale.setlocale(locale.LC_ALL, 'en_US')

# display a welcome message

print("Welcome to the Future Value Calculator")

print()

choice = "y"

while choice.lower() == "y":

# get input from the user


monthly_investment = float(input("Enter monthly investment:\t"))

yearly_interest_rate = float(input("Enter yearly interest rate:\t")

years = int(input("Enter number of years:\t\t"))

# convert yearly values to monthly values

monthly_interest_rate = yearly_interest_rate / 12 / 100

months = year * 12

# calculate the future value

future_value = 0

for i in range(months):

future_value = future_value + monthly_investment

monthly_interest_amount = future_value * monthly_interest_rate

future_value = future_value + monthly_interest_amount

# format and display the result

print("Future value:\t\t\t" + locale.currency(

future_value, grouping=True))

print()

# see if the user wants to continue

choice = input("Continue? (y/n): ")

print()

print("Bye!")
MURACH’S LAST EXERCISE
CHAPTER 2
ANS 2.1- miles_driven=float(input(“enter miles driven:\t\t”))
gallons_used=float(input(“enter gallons of gas used:\t\t”))
costpergallon=float(input(“enter cost per gallon”))
mpg=miles_driven/gallons_used
mpg=round(mpg,2)
totalgascost=costpergallon*gallons_used
costpermile=totalgascost/miles_driven
print()
print(“miles per gallon:\t\t” + str(mpg))
print(“total gas cost:”,totalgascost)
print(“cost per mile:”,costpermile)

Output

enter miles driven: 150


enter gallons of gas used:15
enter cost per gallon:3

Miles per gallon: 10.0


total gas cost:45.0
cost per mile:0.3

Ans-2.2 counter=0
score_total=0
test_score=0
while test_score!=999:
test_score=int(input(“enter test score”))
if test_score>=0 and test _score<=100:
t= str(test_score)
print(t,sep=” “)
score_total += test_score
counter += 1
average_score= round(score_total/counter
print(“total score:” + str(score_total))
print(“average score:”+ str(average_score))

Ans-2.3

print(“the area and perimeter program”)


l=int(input(“please enter the length:”))
b=int(input(“please enter the width:”))
area=l*b
perimeter=2*(l+b)
print(“area=”,area)
print(“perimeter=”,perimeter)
print(“thank you for using this program!”)

output

the area and perimeter program

please enter the length:15


please enter the width:10
area=150
perimeter=50

thank you for using this program!


CH 3 MURACH BACK EXERCISE
ANS3.1 #display a welcome message
print("The Miles Per Gallon program")
print()
# get input from the user
miles_driven=float(input("Enter miles driven:”))
gallons_used=float(input("Enter gallons of gas
used”))

if miles_driven <= 0:
print("Miles driven must be greater than zero.
Please try again”)
elif gallons_used <= 0:
print("Gallons used must be greater than zero.
Please try again”)
else:
# calculate and display miles per gallon
mpg = round(miles_driven / gallons_used, 2)
print("Miles Per Gallon: ", mpg)

print()
print("Bye!")

ANS3.2 # display a welcome message


print("The Test Scores application")
print()
print("Enter test scores")
print("Enter 999 to end input")
print("======================")

# initialize variables
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = int(input("Enter test score: "))
if test_score >= 0 and test_score <= 100:
score_total += test_score
counter += 1
elif test_score == 999:
break
else:
print(f"Test score must be from 0 through
100. "f"Score discarded. Try again.")

# calculate average score


average_score = round(score_total / counter)
# format and display the result
print("======================")
print(f"Total Score: {score_total}"
f"\nAverage Score: {average_score}")
print()
print("Bye!")

ANS3.3 print("Welcome to the Future Value Calculator")


print()
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = float(input("Enter monthly
investment:\t"))
yearly_interest_rate = float(input("Enter yearly
interest rate:\t"))
years = int(input("Enter number of years:\t\t"))

# convert yearly values to monthly values


monthly_interestrate=yearly_interest_rate/12/100
months = years * 12

# calculate the future value


future_value = 0
for i in range(months):
future_value += monthly_investment
monthly_interest_amount=future_value*
monthly_interest_rate
future_value += monthly_interest_amount

# display the result


print(f"Future value:\t\t\t{round(future_value,
2)}")
print()

# see if the user wants to continue


choice = input("Continue (y/n)? ")
print()

print("Bye!")
CH 4 MURACH BACK EXERCISE
ANS4.1 def calculate_future_value(monthly_investment,
yearly_interest, years):
# convert yearly values to monthly values
monthly_interest_rate=
yearly_interest/12/100
months = years * 12

# calculate future value


future_value = 0.0
for i in range(months):
future_value += monthly_investment
monthly_interest=future_value*
monthly_interest_rate
future_value += monthly_interest
return future_value

def main():
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = float(input("Enter monthly
investment:\t"))
yearly_interest_rate = float(input("Enter
yearly interest rate:\t"))
years = int(input("Enter number of
years:\t\t"))
# get and display future value
future_value = calculate_future_value(
monthly_investment,yearly_interest_rate,years)
print(f"Future value:\t\t\t{round(future_value,
2)}")
print()
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
CH 7 MURACH BACK EXERCISE
ANS 7.1

import csv

FILENAME = "trips.csv"

def write_trips(trips):

with open(FILENAME, "w", newline="") as file:

writer = csv.writer(file)

writer.writerows(trips

def read_trips():

trips = []

reader = csv.reader(file)

for row in reader:

trips.append(row)

return trips

def get_miles_driven():

while True:

miles_driven = float(input("Enter miles driven : "))

if miles_driven > 0:

return miles_driven

else:

print("Entry must be greater than zero. Please try again.\n

continue
def get_gallons_used():

while True:

gallons_used = float(input("Enter gallons of gas: "))

if gallons_used > 0:

return gallons_used

else:

print("Entry must be greater than zero. Please try again.\n")

continue

def list_trips(trips):

print("Distance\tGallons\tMPG")

for i in range(len(trips)):

trip = trips[i]

print(str(trip[0]) + "\t\t" + str(trip[1]) + "\t\t" + str(trip[2]))

print()

def main():

print("The Miles Per Gallon application")

trips = read_trips()

list_trips(trips)

more = "y"

while more.lower() == "y":

miles_driven = get_miles_driven()
gallons_used = get_gallons_used()

mpg = round((miles_driven / gallons_used), 2)

print("Miles Per Gallon:\t" + str(mpg))

print()

trip = []

trip.append(miles_driven)

trip.append(gallons_used)

trip.append(mpg)

trips.append(trip)

write_trips(trips)

list_trips(trips)

more = input("More entries? (y or n): ")

print("Bye")

if __name__ == "__main__":

main()

ANS7.2

import csv

FILENAME = "trips.csv"

def write_trips(trips):

with open(FILENAME, "w", newline="") as file:

writer = csv.writer(file)

writer.writerows(trips)
def get_miles_driven():

while True:

miles_driven = float(input("Enter miles driven : "))

if miles_driven > 0:

return miles_driven

else:

print("Entry must be greater than zero. Please try again.\n")

continue

def get_gallons_used():

while True:

gallons_used = float(input("Enter gallons of gas: "))

if gallons_used > 0:

return gallons_used

else:

print("Entry must be greater than zero. Please try again.\n")

continue

def main():

print("The Miles Per Gallon application")

print()

trips = []

more = "y"
while more.lower() == "y":

miles_driven = get_miles_driven()

gallons_used = get_gallons_used()

mpg = round((miles_driven / gallons_used), 2)

print("Miles Per Gallon:\t" + str(mpg))

print()

trip = []

trip.append(miles_driven)

trip.append(gallons_used)

trip.append(mpg)

trips.append(trip)

more = input("More entries? (y or n): ")

write_trips(trips)

print("Bye K. Zoom")

if __name__ == "__main__":

main()

ANS7.3

import pickle

FILENAME = "trips.bin"

def write_trips(trips):

with open(FILENAME, "wb") as file:

pickle.dump(trips, file)
def get_miles_driven():

while True:

miles_driven = float(input("Enter miles driven : "))

if miles_driven > 0:

return miles_driven

else:

print("Entry must be greater than zero. Please try again.\n")

continue

def get_gallons_used():

while True:

gallons_used = float(input("Enter gallons of gas: "))

if gallons_used > 0:

return gallons_used

else:

print("Entry must be greater than zero. Please try again.\n")

continue

def main():

print("The Miles Per Gallon application")

print()

trips = []

more = "y"

while more.lower() == "y":


miles_driven = get_miles_driven()

gallons_used = get_gallons_used()

mpg = round((miles_driven / gallons_used), 2)

print("Miles Per Gallon:\t" + str(mpg))

print()

trip = []

trip.append(miles_driven)

trip.append(gallons_used)

trip.append(mpg)

trip.append(trip)

more = input("More entries? (y or n): ")

write_trips(trips)

print("Bye K. Zoom")

if __name__ == "__main__":

main()

CH 8 MURACH BACK EXERCISE


ANS 8.1

import csv
import sys

FILENAME = "movies.csv"

def exit_program():

    print("Terminating program.")

    sys.exit()

def read_movies():

    try:

        movies = []

        with open(FILENAME, newline="") as file:

            reader = csv.reader(file)

            for row in reader:

                movies.append(row)

        return movies

    except FileNotFoundError as e:

        print(f"Could not find {FILENAME} file.")

        exit_program()

    except Exception as e:

        print(type(e), e)

        exit_program()

def write_movies(movies):

    try:

        with open(FILENAME, "w", newline="") as file:


            writer = csv.writer(file)

            writer.writerows(movies)

    except Exception as e:

        print(type(e), e)

        exit_program()

def list_movies(movies):

    for i, movie in enumerate(movies, start=1):

        print(f"{i}. {movie[0]} ({movie[1]})")

    print()

    

def add_movie(movies):

    name = input("Name: ")

    year = input("Year: ")

    movie = [name, year]

    movies.append(movie)

    write_movies(movies)

    print(f"{name} was added.\n")

def delete_movie(movies):

    while True:

        try:

            number = int(input("Number: "))


        except ValueError:

            print("Invalid integer. Please try again.")

            continue

        if number < 1 or number > len(movies):

            print("There is no movie with that number. Please try again.")

        else:

            break

    movie = movies.pop(number - 1)

    write_movies(movies)

    print(f"{movie[0]} was deleted.\n")

def display_menu():

    print("The Movie List program")

    print()

    print("COMMAND MENU")

    print("list - List all movies")

    print("add - Add a movie")

    print("del - Delete a movie")

    print("exit - Exit program")

    print()    

def main():

    display_menu()
    movies = read_movies()

    while True:        

        command = input("Command: ")

        if command.lower() == "list":

            list_movies(movies)

        elif command.lower() == "add":

            add_movie(movies)

        elif command.lower() == "del":

            delete_movie(movies)

        elif command.lower() == "exit":

            break

        else:

            print("Not a valid command. Please try again.\n")

    print("Bye!")

if __name__ == "__main__":

    main()

ANS8.2

def get_number(prompt, low, high):


while True:
number = float(input(prompt))
if number > low and number <= high:
is_valid = True
return number
else:
print(f"Entry must be greater than {low} "
f"and less than or equal to {high}.")
def get_integer(prompt, low, high):
while True:
number = int(input(prompt))
if number > low and number <= high:
is_valid = True
return number
else:
print(f"Entry must be greater than {low} "
f"and less than or equal to {high}.")

def calculate_future_value(monthly_investment, yearly_interest, years):


# convert yearly values to monthly values
monthly_interest_rate = yearly_interest / 12 / 100
months = years * 12

# calculate future value


future_value = 0.0
for i in range(months):
future_value += monthly_investment
monthly_interest = future_value * monthly_interest_rate
future_value += monthly_interest

return future_value

def main():
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = get_number("Enter monthly investment:\t", 0, 1000)
yearly_interest_rate = get_number("Enter yearly interest rate:\t", 0, 15)
years = get_integer("Enter number of years:\t\t", 0, 50)

# get and display future value


future_value = calculate_future_value(
monthly_investment, yearly_interest_rate, years)
print()
print(f"Future value:\t\t\t{round(future_value, 2)}")
print()

# see if the user wants to continue


choice = input("Continue? (y/n): ")
print()

print("Bye!")
if __name__ == "__main__":
main()

CH 13 MURACH BACK EXERCISE


ANS13.1
def fib(n):

   if n == 0:

     return 0

   elif n == 1:

     return 1

   else:

      return fib(n - 1) + fib(n - 2)

def main():

   for i in range(16):

     print(fib(i), end=", ")

    print("...")

if __name__ == "__main__":
    main()

ANS 13.2
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
n1 = 0
n2 = 1
fib = 0
for i in range(2, n+1):
fib = n1 + n2
n1 = n2
n2 = fib
return fib

def main():
for i in range(16):
print(fib(i), end=", ")
print("...")

if __name__ == "__main__":
main()

ANS13.3
def move_disk(n, src, dest, temp):
if n == 0:
return
else:
move_disk(n-1, src, temp, dest)
print("Move disk", n, "from", src, "to", dest)
move_disk(n-1, temp, dest, src)
def main():
print("**** TOWERS OF HANOI ****")
print()
num_disks = int(input("Enter number of disks: "))
print()
move_disk(num_disks, "A", "C", "B")
print()
print("All disks have been moved.")

if __name__ == "__main__":
main()

CH 14 MURACH BACK EXERCISE


ANS14.1
from dice import Dice, Die

def main():

    print("The Dice Roller program")

    print(" _____ \n" + \

          "| |\n" + \

          "| o |\n" + \

          "|_____|")

    print(" _____ \n" + \

          "|o |\n" + \

          "| |\n" + \

          "|____o|")    

    print(" _____ \n" + \

          "|o |\n" + \

          "| o |\n" + \

          "|____o|")

    print(" _____ \n" + \


          "|o o|\n" + \

          "| |\n" + \

          "|o___o|")          

    print(" _____ \n" + \

          "|o o|\n" + \

          "| o |\n" + \

          "|o___o|")

    print(" _____ \n" + \

          "|o o|\n" + \

          "|o o|\n" + \

          "|o___o|")

    print()

    # get number of dice from user

    count = int(input("Enter the number of dice to roll: "))

# create Die objects and add to Dice object

    dice = Dice()

    for i in range(count):

        die = Die()

        dice.addDie(die)

choice = "y"

  while choice.lower() == "y":        

        # roll the dice


        dice.rollAll()

#display to user

        print("YOUR ROLL: ", end="")

        for die in dice.list:

            print(die.value, end=" ")

        print("\n")

choice = input("Roll again? (y/n): ")

         print("Bye!")

if __name__ == "__main__":

    main()

import random

from dataclasses import dataclass

@dataclass

class Die:

    __value:int = 1

@property

    def value(self):

        return self.__value

    @value.setter

    def value(self, value):

        if value < 1:

            raise ValueError("Die value can't be less than 1.")


        else:

            self.__value = value

    def roll(self):

        self.__value = random.randrange(1, 7)

class Dice:

    # use explicit initializer because @dataclass doesn't allow

    # attributes with a default value that's mutable (like list)

    def __init__(self):

        self.__list = []

def addDie(self, die):

        self.__list.append(die)

@property

  def list(self):

        return tuple(self.__list)

 def rollAll(self):

        for die in self.__list:

            die.roll()

ANS14.2
def list(movie_list):
if len(movie_list) == 0:
print("There are no movies in the list.\n")
return
else:
for i, row in enumerate(movie_list, start=1):
print(f"{i}. {row[0]} ({row[1]})")
print()
def add(movie_list):
name = input("Name: ")
year = input("Year: ")
movie = [name, year]
movie_list.append(movie)
print(f"{movie[0]} was added.\n")

def delete(movie_list):
number = int(input("Number: "))
if number < 1 or number > len(movie_list):
print("Invalid movie number.\n")
else:
movie = movie_list.pop(number-1)
print(f"{movie[0]} was deleted.\n")
def display_menu():
print("COMMAND MENU")
print("list - List all movies")
print("add - Add a movie")
print("del - Delete a movie")
print("exit - Exit program")
print()

def main():
movie_list = [["Monty Python and the Holy
Grail", 1975]
["On the Waterfront", 1954],
["Cat on a Hot Tin Roof", 1958]]
display_menu()
while True:
command = input("Command: ")
if command == "list":
list(movie_list)
elif command == "add":
add(movie_list)
elif command == "del":
delete(movie_list)
elif command == "exit":
break
else:
print("Not a valid command. Please try
again.\n")
print("Bye!")

if __name__ == "__main__":
main()

ANS14.3
def to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
return celsius

def to_fahrenheit(celsius):
fahrenheit = celsius * 9/5 + 32
return fahrenheit
# the main function is used to test the other functions
# this code isn't run if this module isn't the main module
def main():
for temp in range(0, 212, 40):
print(temp, "Fahrenheit equals",
round(to_celsius(temp), 2), "Celsius")
for temp in range(0, 100, 20):
print(temp, "Celsius equals",
round(to_fahrenheit(temp), 2),
"Fahrenheit")
# if this module is the main module, call the main function
# to test the other functions
if __name__ == "__main__":
main()

# TEMPRATURE CONVERTER

import temperature as temp


def display_menu():

    print("The Convert Temperatures program")

    print()

    print("MENU")

    print("1. Fahrenheit to Celsius")

    print("2. Celsius to Fahrenhit")

    print()

def convert_temp():

    option = int(input("Enter a menu option: "))

    if option == 1:

        f = int(input("Enter degrees Fahrenheit: "))

        c = temp.to_celsius(f)

        c = round(c, 2)

        print("Degrees Celsius:", c)    

    elif option == 2:

        c = int(input("Enter degrees Celsius: "))

        f = temp.to_fahrenheit(c)

        f = round(f, 2)

        print("Degrees Fahrenheit:", f)

    else:

        print("You must enter a valid menu number.")

def main():

    display_menu()
    again = "y"

    while again.lower() == "y":

        convert_temp()

        print()

        again = input("Convert another temperature? (y/n): ")

        print()

        print("Bye!")

if __name__ == "__main__":

    main()

Pearson Chapter 2nd Back Exercise Questions

ANS1.

math.ceil(65.65) : 66

math.fabs(-67.58) : 67.58

math.exp(2.7) : 14.8797

math.log10(1000) : 3.0

math.sqrt(121) : 11.0
math.degree(math.pi/2): 90.0

math.ceil(65.47) : 66

math.fabs(3) : 3.0

math.log(45,2) : 5.491

math.pow(4,1/2) : 2.0

math.radians(30) : 0.5235

ANS2.

Value of x can lie between [5,6)

ANS3.

abs(-5.4) : 5.4

abs(15) : 15

chr(72) : 'H'

round(-24.9) : -25

float(57) : 57.0

complex('1+2j') : (1+2j)

divmod(5,2) : (2,1) (divmod(x,y) returns (x//y,x%y))

float(57) : 57.0

pow(9,2) : 81

max(97, 88, 60) : 97

min(55, 29, 99) : 29

max('a', 'b', 'AB') : 'b'


ANS4.

a) def pattern1():

print("\t\t*")

print("\t*\t*\t*)

print("*\t*\t*\t*\t*")

print("\t*\t*\t*")

print("\t\t*")

b) def pattern2():

print("$ $ $ $ $")

print("$ $")

print("$ $")

print("$ $")

print("$ $ $ $ $")

ANS5.

a) nMultiple(5) : 5

nMultiple(5,6) : 30

nMultiple(num=7) : 0

nMultiple(num=6,a=5): 30

nmultiple(5,num=6) : 30

ANS6.

a) a= 8

b= 5

b) None
ANS7.

import math

def areaTriangle(side1,side2,side3):

s=(side1+side2+side3)/2

d=s*(s-side1)*(s-side2)*(s-side3)

a=math.sqrt(d)

return a

def main():

side1=eval(input("Enter first side of triangle"))

side2=eval(input("Enter second side of triangle")

side3=eval(input("Enter third side of triangle"))

assert ((side1+side2)>side3) or ((side1+side3)>side2) or ((side2+side3)>side1)

ans=areaTriangle(side1,side2,side3)

print("Area: ",ans)

main()

(Unit iv) Inbuilt Data Structures


Pearson Chapter 6thBackExercise Questions

ANS1.
def replacstar(stri):

strr=''

for i in range(0,len(stri)):

if stri[i]==stri[i-1]:

strr=strr[:i+1]+'*'

else:

strr+=stri[i]

return strr

ANS2.

def checkanagrams(s1, s2):

if(sorted(s1)== sorted(s2)):

print("The strings are anagrams.")

else:

print("The strings aren't anagrams.")

ANS3.

def numberofwords(s):

count=1

for i in s:

if i==" ":

count+=1
print("number of words are :",count)

ANS4.

def convert(s):

ch = list(s)

for i in range(len(s)):

if (i == 0 and ch[i] != ' ' or

ch[i] != ' ' and

ch[i - 1] == ' '):

if (ch[i] >= 'a' and ch[i] <= 'z'):

ch[i] = chr(ord(ch[i]) - ord('a') +

ord('A'))

elif (ch[i] >= 'A' and ch[i] <= 'Z'):

ch[i] = chr(ord(ch[i]) + ord('a') -

ord('A'))

st = "".join(ch)

return st;

if __name__=="__main__":

s = "gEEks fOr GeeKs"

print(convert(s));

ANS5.

def numberofwords(s):
count=1

for i in s:

if i==" ":

count+=1

print("number of words are :",count)

ANS6.

a) 22

b) ' Delhi'

c) 'B-6, Lodhi road, Delhi'

d) 'B-6, Lodhi road, Delhi'

e) -1

f) 'b-6, lODHI ROAD, dELHI'

g) ['B-6', 'Lodhi road', 'Delhi']

h) False

ANS7.

a) 2

b) 15

c) 27

d) 'Good morning. have a good day!!'

e) 'good morning. have a good day!!'

f) 'GOOD MORNING. HAVE A GOOD DAY!!'


g) 'gOOD mORNING. hAVE A gOOD dAY!!'

h) False

i) 'Sweet Morning. Have a Good Day!!'

j) 'Good Morning. Have a Good Day!!'

k) ['Good', 'Morning.', 'Have', 'a', 'Good', 'Day!!']

l) ('Good Morning', '.', ' Have a Good Day!!')

m) False

n) True

Pearson Chapter 7thBackExercise Questions

ANS1.

def removeduplicates(lst1):

s=set(lst1)

lst2=list(lst1)

return lst2

ANS2.

def cumulativelist(lst1):

lst2=[]

sum1=0

for i in lst:
sum1=sum1+i

lst2.append(sum1)

return lst2

ANS3.

def main():

freq={}

letters='abcdefghijklmnopqrstuvwxyz'

sentence=input("enter a sentence")

sentence1=sentence.lower()

for i in sentence1:

if i in letters:

if i in freq:

freq[i]+=1

else:

freq[i]=1

print(freq)

ANS4.

a) [0, 1, 2, 3, 4]

[3, 4, 5, 6, 7]

b) [3, 1, 5, 3, 7]

[0, 4, 2, 6, 4]
ANS5.

a) 30

b) 25

c) omputerc

d) 219

e) [2, 4, 18, 12, 16, 45, 24, 28, 72, 34]

ANS6.

def funclist(n):

lst=[]

l=[0,0,0,0,0]

for i in range(1,n+1):

for j in range(1,6):

l[j-1]=i*j

lst.append(l[:])

ANS7.

def digit(n):

dicti={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten'}

reverse=0

while n>0:

remainder=n%10
reverse=reverse*10+remainder

n=n//10

while reverse>0:

digits=reverse%10

print(dicti[digits],end=" ")

reverse=reverse//10

ANS8.

a) Index Error

b) [1, 2, 3, 1, 2, 3]

c) Type Error

d) 3

e) ['B', '-', '6', ' ', 'L', 'o', 'd', 'h', 'i', ' ', 'r', 'o', 'a', 'd', ',', 'D', 'e', 'l', 'h', 'i']

f) ['a', 1, 'z', 26, 'd', 4, 'e', 5]

g) ['a', 1, 'z', 26, 'd', 4, 'e', 5, ['e', 5]]

h) ['gita', 'rohan', 'mohan']

i) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

j) [2]

k) [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]

l) Type Error

m) Attribute Error

n) Type Error

o) 'a, e, i, o, u'
p) [('apple', 'red'), ('orange', 'orange')]

q) ['english', 'physics', 'chemistry', 'maths']

r) {'X': ['eng', 'hindi', 'maths', 'science'], 'XII': ['english', 'physics', 'chemistry', 'maths', 'computer
science']}

s) False

t) [('apple', 'red'), ('mango', 'yellow'), ('orange', 'orange')]

u) ['X', 'XII']

v) 'None'

w) {'apple': 'red', 'mango': 'yellow', 'orange': 'orange', 'kiwi': 'green'}

ANS9.

a) {'Bicycle', 'Scooter', 'Car', 'Bike', 'Rickshaw'}

b) {'Car', 'Truck', 'Bus'}

c) {'Car'}

d) {'Rickshaw', 'scooter', 'Bike', 'Bicycle', 'Truck', 'Bus'}

e) {'Rickshaw', 'scooter', 'Bike', 'Bicycle', 'Truck', 'Bus', 'Car'}

f) 'Bicycle'

'Scooter'

'Car'

'Bike'

'Truck'

'Bus'

'Rickshaw'
g) 7

h) 'Bicycle'

i) {'Bicycle', 'Scooter', 'Car', 'Bike', 'Truck', 'Bus', 'Rickshaw'}

Pearson Chapter 12thBackExercise Questions

ANS1.

def recSearch( arr, l, r, x):

if r < l:

return -1

if arr[l] == x:

return l

if arr[r] == x:

return r

return recSearch(arr, l+1, r-1, x)

arr = [12, 34, 54, 2, 3]

n = len(arr)

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

index = recSearch(arr, 0, n-1, x)

if index != -1:

print ("Element", x,"is present at index %d" %(index))


else:

print ("Element %d is not present" %(x))

ANS2.

def insertionSortRecursive(arr,n):

if n<=1:

return

insertionSortRecursive(arr,n-1)

'''Insert last element at its correct position

in sorted array.'''

last = arr[n-1]

j = n-2

while (j>=0 and arr[j]>last):

arr[j+1] = arr[j]

j = j-1

arr[j+1]=last

def printArray(arr,n):

for i in range(n):

print(arr[i],end=" ")
arr = [12,11,13,5,6]

n = len(arr)

insertionSortRecursive(arr, n)

printArray(arr, n)

ANS5.

def pivotedBinarySearch(arr, n, key):

pivot = findPivot(arr, 0, n-1);

if pivot == -1:

return binarySearch(arr, 0, n-1, key);

if arr[pivot] == key:

return pivot

if arr[0] <= key:

return binarySearch(arr, 0, pivot-1, key);

return binarySearch(arr, pivot + 1, n-1, key);

def findPivot(arr, low, high):

if high < low:

return -1
if high == low:

return low

mid = int((low + high)/2)

if mid < high and arr[mid] >arr[mid + 1]:

return mid

if mid > low and arr[mid] <arr[mid - 1]:

return (mid-1)

if arr[low] >= arr[mid]:

return findPivot(arr, low, mid-1)

return findPivot(arr, mid + 1, high)

def binarySearch(arr, low, high, key):

if high < low:

return -1

mid = int((low + high)/2)

if key == arr[mid]:

return mid

if key > arr[mid]:

return binarySearch(arr, (mid + 1), high,

key);
return binarySearch(arr, low, (mid -1), key);

arr1 = [5, 6, 7, 8, 9, 10, 1, 2, 3]

print(arr1)

n = len(arr1)

key = int(input('Enter value :'))

print("Index of the element is : ",

pivotedBinarySearch(arr1, n, key))

ANS6.

no=input("Enter the number of elements")

N=int(no)

L=[]

k=input("Enter an element")

L.append(k)

print(L)

print("This is the original list")

g=L[0]

L.pop(0)

L.append(g)

print(L)

print("This is the new list")

You might also like