Computer Science Lab (CS083)
Introduction to Python Programming
OVERVIEW
his document is aimed at instructing students while they are
T
undertaking their lab work.
his lab work is presenting an introduction to thepython
T
programming language.
computer programis a sequence of instructions thatcontrol
A
the behaviour of a computer.
he instructions tell the computer when to perform tasks like
T
reading input and displaying results, and how to transform and
manipulate values to achieve a desired outcome.
nalgorithmmust be translated into a computer programbefore
A
a computer can be used to solve a problem.
he translation process is calledprogrammingandthe person
T
who performs the translation is referred to as aprogrammer.
tudents should use the concepts taught in the class to perform
S
the basic programming questions in python.
Prepared By: Sushil Singh 1
A QUICK RECAP OF INTRO TO PYTHON PROGRAMMING
Prepared By: Sushil Singh 2
Let’s apply all of these concepts in interesting programming questions.
Prepared By: Sushil Singh 3
EXERCISES
he exercises in this lab will allow you to put the concepts discussed
T
previously into practice.
olving these exercises is an important step toward the creation of
S
larger programs that solve more interesting problems.
xercise 1: Mailing Address
E
Create a program that displays your name and complete mailing
address. The address should be printed in the format that is normally
used in the area where you live. Your program does not need to read
any input from the user.
xercise 2: Hello
E
Write a program that asks the user to enter his or her name. The
program should respond with a message that says hello to the user,
using his or her name.
xercise 3: Area of a Room
E
Write a program that asks the user to enter the width and length of a
room.
nce these values have been read, your program should compute and
O
display the area of
the room.
The length and the width will be entered as floating-point numbers.
I nclude units in your prompt and output message; either feet or
metres, depending on which
unit you are more comfortable working with.
Prepared By: Sushil Singh 4
xercise 4: Area of a Field
E
Create a program that reads the length and width of a farmer’s field
from the user in feet. Display the area of the field in acres.
Hint: There are 43,560 square feet in an acre.
xercise 5: Bottle Deposits
E
In many jurisdictions a small deposit is added to drink containers to
encourage people to recycle them. In one particular jurisdiction, drink
containers holding one litre or less have a ₹8 deposit, and drink
containers holding more than one litre have a ₹20 deposit.
rite a program that reads the number of containers of each size from
W
the [Link] program should continue by computing and displaying
the refund that will be received for returning those containers.
ormat the output so that it includes a rupee sign and two digits to the
F
right of the decimal point.
xercise 6: Tax and Tip
E
The program that you create for this exercise will begin by reading
the cost of a meal ordered at a restaurant from the user.
Then your program will compute the tax and tip for the meal.
Use your local tax rate when computing the amount of tax owing.
Compute the tip as 18 percent of the meal amount (without the tax).
he output from your program should include the tax amount, the tip
T
amount, and the grand total for the meal including both the tax and
the tip.
ormat the output so that all of the values are displayed using two
F
decimal places.
Prepared By: Sushil Singh 5
xercise 7: Sum of the FirstnPositive Integers
E
Write a program that reads a positive integer,n,from the user and
then displays the sum of all of the integers from1ton.
he sum of the firstnpositive integers can be
T
computed using the formula:
xercise 8: Tax and Tip
E
An online retailer sells two products: widgets and gizmos.
ach widget weighs 75 grams.
E
Each gizmo weighs 112 grams.
rite a program that reads the number of widgets and the number of
W
gizmos from the user.
hen your program should compute and display the total weight of
T
the parts.
xercise 9: Compound Interest
E
Pretend that you have just opened a new savings account that earns 4
percent interest per year.
he interest that you earn is paid at the end of the year, and is added
T
to the balance of the savings account.
rite a program that begins by reading the amount of money
W
deposited into the account from the user.
hen your program should compute and display the amount in the
T
savings account after 1, 2, and 3 years.
Display each amount so that it is rounded to 2 decimal places.
Prepared By: Sushil Singh 6
xercise 10: Arithmetic
E
Create a program that reads two integers, a and b, from the user. Your
program should compute and display:
• The sum ofaandb
• The difference whenbis subtracted froma
• The product ofaandb
• The quotient whenais divided byb
• The remainder whenais divided byb
• The result of
𝑏
• The result of 𝑎
int: You will probably find the log10 function in the math module
H
helpful for computing the second last item in the list
xercise 11: Fuel Efficiency
E
In the United States, fuel efficiency for vehicles is normally expressed
in miles-per gallon (MPG).
I n India, fuel efficiency is normally expressed in litres-per-hundred
kilometres (L/100 km).
se your research skills to determine how to convert from MPG to
U
L/100 km.
hen create a program that reads a value from the user in American
T
units and displays the equivalent fuel efficiency in Indian units.
Prepared By: Sushil Singh 7
xercise 12: Distance Between Two Points on Earth
E
The surface of the Earth is curved, and the distance between degrees
of longitude varies with latitude.
s a result, finding the distance between two points on the surface of
A
the Earth is more complicated than simply using the Pythagorean
theorem.
Let (𝑡1,𝑔1) and (𝑡2, 𝑔2) be thelatitude and longitude of two points on
the Earth's surface.
he distance between these points, following the surface of the Earth,
T
in kilometres is:
he value 6371.01 in theprevious equation
T
wasn’t selected at random.It is the average
radius of the Earth inkilometres.
reate a program that allows the user to enter the latitude and
C
longitude of two points on the Earth in degrees.
our program should display the distance between
Y
the points, following the surface of the earth, in kilometres.
int: Python’s trigonometric functions operate in radians.
H
As a result, you will need to convert the user’s input from degrees to
radians before computing the distance with the formula discussed
previously. The math module contains a function named radians
which converts from degrees to radians.
Prepared By: Sushil Singh 8
xercise 13: Making Change
E
Consider the software that runs on a self-checkout machine. One task
that it must be able to perform is to determine how much change to
provide when the shopper pays for a purchase with cash.
rite a program that begins by reading a number of cents from the
W
user as an integer.
hen your program should compute and display the denominations of
T
the coins that should be used to give that amount of change to the
shopper.
he change should be given using as few coins as possible.
T
Assume that the machine is loaded withpennies,nickels,dimes,
quarters,looniesandtoonies.
one dollar coin was introduced in Canada in 1987. It is referred to
A
as a loonie because one side of the coin has a loon (a type of bird) on
it. The two dollar coin, referred to as a toonie, was introduced 9 years
later. It’s name is derived from the combination of the number two
and the name of the loonie.
xercise 14: Height Units
E
Many people think about their height in feet and inches, even in some
countries that primarily use the metric system.
rite a program that reads a number of feet from the user, followed
W
by a number of inches.
nce these values are read, your program should compute and display
O
the equivalent number of centimetres.
Hint: One foot is 12 inches. One inch is 2.54 centimetres.
Prepared By: Sushil Singh 9
xercise 15: Distance Units
E
In this exercise, you will create a program that begins by reading a
measurement in feet from the user.
hen your program should display the equivalent distance in inches,
T
yards and miles.
se the Internet to look up the necessary conversion factors if you
U
don’t have them memorised.
xercise 16: Area and Volume
E
Write a program that begins by reading a radius,r,from the user.
he program will continue by computing and displaying the area of a
T
circle with radiusrand the volume of a sphere withradiusr.
Use the pi constant in the math module in your calculations.
xercise 17: Volume of a Cylinder
E
The volume of a cylinder can be computed by multiplying the area of
its circular base by its height.
rite a program that reads the radius of the cylinder, along with its
W
height, from the user and computes its volume.
Display the result rounded to one decimal place.
xercise 18: Free Fall
E
Create a program that determines how quickly an object is travelling
when it hits the ground.
he user will enter the height from which the object is dropped in
T
metres (m). Because the object is dropped its initial speed is 0 m/s.
Prepared By: Sushil Singh 10
2
ssume that the acceleration due to gravity is 9.8𝑚/𝑠 . You can use
A
the formula to compute the final speed,𝑣𝑓, when the
initial speed,𝑣𝑖, acceleration,𝑎, and distance,𝑑, are known.
xercise 19: Heat Capacity
E
The amount of energy required to increase the temperature of one
gram of a material by one degree Celsius is the material’sspecific
heat capacity,C.
he total amount of energy,q, required to raisemgrams of a material
T
byΔTdegrees Celsius can be computed using the formula:
rite a program that reads the mass of some water and the
W
temperature change from the user.
our program should display the total amount of energy that must be
Y
added or removed to achieve the desired temperature change.
𝐽
Hint: The specific heat capacity of water is 4.186 ◦
.
𝑔 𝐶
ecause water has a density of1.0 grams per millilitre,you can use
B
grams and millilitres interchangeably in this exercise.
xtend your program so that it also computes the cost of heating the
E
water. Electricity is normally billed using units ofkilowatt hours
rather than Joules.
I n this exercise, you should assume that electricity costs ₹8.9 per
kilowatt hour.
Prepared By: Sushil Singh 11
se your program to compute the cost of boiling the water needed for
U
a cup of coffee.
int: You will need to look up the factor for converting between
H
Joules and kilowatt hours to complete the last part of this exercise.
xercise 20: Area of a Triangle
E
The area of a triangle can be computed using the following formula,
wherebis the length of the base of the triangle,andhis its height:
rite a program that allows the user to enter values forbandh.
W
The program should then compute and display the area of a triangle
with base length b and height h.
xercise 21: Area of a Triangle (Again)
E
In the previous exercise you created a program that computes the area
of a triangle when the length of its base and its height were known.
I t is also possible to compute the area of a triangle when the lengths
of all three sides are known.
ets1,s2ands3be the lengths of the sides. Lets = (s1 + s2 + s3)/2.
L
Then the area of the triangle can be calculated using the following
formula:
evelop a program that reads the lengths of the sides of a triangle
D
from the user and displays its area.
Prepared By: Sushil Singh 12
xercise 22: Ideal Gas Law
E
The ideal gas law is a mathematical approximation of the behaviour
of gases as pressure, volume and temperature change. It is usually
stated as:
herePis the pressure in Pascals,Vis the volumein litres,
w
nis the amount of substance in moles,Ris the idealgas constant,
𝐽
equal to 8.314 𝑚𝑜𝑙𝐾 , andTis the temperaturein degrees Kelvin.
rite a program that computes the amount of gas in moles when the
W
user supplies the pressure, volume and temperature.
est your program by determining the number of moles of gas in a
T
SCUBA tank.
typical SCUBA tank holds 12 litres of gas at a pressure of
A
20,000,000 Pascals (approximately 3,000 PSI).
oom temperature is approximately 20 degrees Celsius or 68 degrees
R
Fahrenheit.
int: A temperature is converted from Celsius to Kelvinby adding
H
273.15 to it. To convert a temperature from Fahrenheit to Kelvin,
5
deduct 32 from it, multiply it by 9 a nd thenadd 273.15 to it.
Prepared By: Sushil Singh 13
xercise 23: Area of a Regular Polygon
E
A polygon is regular if its sides are all the same length and the angles
between all of the adjacent sides are equal.
he area of a regular polygon can be computed using the following
T
formula, wheresis the length of a side andnisthe number of sides:
rite a program that readssandnfrom the user andthen displays the
W
area of a regular polygon constructed from these values.
xercise 24: Units of Time
E
Create a program that reads a duration from the user as a number of
days, hours, minutes, and seconds.
ompute and display the total number of seconds represented by this
C
duration.
Prepared By: Sushil Singh 14
xercise 25: Units of Time (Again)
E
In this exercise you will reverse the process described in Exercise 24.
Develop a program that begins by reading a number of seconds from
the user. Then your program should display the equivalent amount of
time in the formD:HH:MM:SS, whereD,HH,MM, andSS
representdays,hours,minutesandsecondsrespectively.The hours,
minutes and seconds should all be formatted so that they occupy
exactly two digits.
se your research skills determine what additional character needs to
U
be included in the format specifier so that leading zeros are used
instead of leading spaces when a number is formatted to a particular
width.
xercise 26: Current Time
E
Python’stimemodule includes several time-relatedfunctions.
ne of these is theasctimefunction which reads thecurrent time
O
from the computer’s internal clock and returns it in a human-readable
format.
se this function to write a program that displays the current time and
U
date.
Your program will not require any input from the user.
Prepared By: Sushil Singh 15
xercise 27: When is Easter?
E
Easter is celebrated on the Sunday immediately after the first full
moon following the spring equinox. Because its date includes a lunar
component, Easter does not have a fixed date in the Gregorian
calendar. Instead, it can occur on any date between March 22 and
April 25.
The month and day for Easter can be computed for a given year using
the Anonymous Gregorian Computus algorithm, which is shown
below.
➢
Setaequal to the remainder when year is dividedby 19
➢Setbequal to the floor of year divided by 100
➢Setcequal to the remainder when year is dividedby 100
➢Setdequal to the floor of b divided by 4
➢Seteequal to the remainder when b is divided by4
𝑏+8
➢Setfequal to the floor of 25
𝑏−𝑓+1
➢Setgequal to the floor of 3
➢Sethequal to the remainder when 19a + b − d − g+ 15 is
divided by 30
➢Setiequal to the floor of c divided by 4
➢Setkequal to the remainder when c is divided by4
➢Setlequal to the remainder when 32 + 2e + 2i − h− k is divided
by 7
𝑎+11ℎ+22𝑙
➢Setmequal to the floor of 451
ℎ+𝑙−7𝑚+114
➢Setmonthequal to the floor of 31
➢Setdayequal to one plus the remainder when h + l− 7m + 114
is divided by 31
rite a program that implements theAnonymous Gregorian
W
Computus algorithmto compute the date of Easter.
our program should read the year from the user and then display an
Y
appropriate message that includes the date of Easter in that year.
Prepared By: Sushil Singh 16
xercise 28: Body Mass Index
E
Write a program that computes the body mass index (BMI) of an
individual.
our program should begin by reading a height and weight from the
Y
user. Then it should use one of the following two formulas to compute
the BMI before displaying it.
I f you read the height in inches and the weight in pounds then body
mass index is computed using the following formula:
I f you read the height in metres and the weight in kilograms then body
mass index is computed using this slightly simpler formula:
xercise 29: Wind Chill
E
When the wind blows in cold weather, the air feels even colder than it
actually is because the movement of the air increases the rate of
cooling for warm objects, like people.
This effect is known aswind chill.
I n 2001, Canada, the United Kingdom and the United States adopted
the following formula for computing the wind chill index. Within the
formula Ta is the air temperature in degrees Celsius and V is the wind
speed in kilometres per hour.
Prepared By: Sushil Singh 17
similar formula with different constant values can be used for
A
temperatures in degrees Fahrenheit and wind speeds in miles per hour.
rite a program that begins by reading the air temperature and wind
W
speed from the user.
nce these values have been read your program should display the
O
wind chill index rounded to the closest integer.
he wind chill index is only considered valid for temperatures less
T
than or equal to 10 degrees Celsius and wind speeds exceeding 4.8
kilometres per hour.
xercise 30: Celsius to Fahrenheit and Kelvin
E
Write a program that begins by reading a temperature from the user in
degrees Celsius.
hen your program should display the equivalent temperature in
T
degrees Fahrenheit and degrees Kelvin.
he calculations needed to convert between different units of
T
temperature can be found on the Internet.
xercise 31: Units of Pressure
E
In this exercise you will create a program that reads a pressure from
the user in kilopascals.
nce the pressure has been read your program should report the
O
equivalent pressure in pounds per square inch, millimetres of mercury
and atmospheres.
Prepared By: Sushil Singh 18
se your research skills to determine the conversion factors between
U
these units.
xercise 32: Sum of the Digits in an Integer
E
Develop a program that reads a four-digit integer from the user and
displays the sum of its digits.
or example, if the user enters 3141 then your program should display
F
3+1+4+1=9.
xercise 33: Sort 3 Integers
E
Create a program that reads three integers from the user and displays
them in sorted order (from smallest to largest).
Use the min and max functions to find the smallest and largest values.
he middle value can be found by computing the sum of all three
T
values, and then subtracting the minimum value and the maximum
value.
xercise 34: Day Old Bread
E
A bakery sells loaves of bread for Rs. 250 each. Day old bread is
discounted by 60 percent.
rite a program that begins by reading the number of loaves of day
W
old bread being purchased from the user.
hen your program should display the regular price for the bread, the
T
discount because it is a day old, and the total price. Each of these
amounts should be displayed on its own line with an appropriate
label.
ll of the values should be displayed using two decimal places, and
A
the decimal points in all of the numbers should be aligned when
reasonable values are entered by the user.
Prepared By: Sushil Singh 19