Lab Exercises Solutions
Lab Exercises Solutions
Solutions To Lab
Exercises
Contents
Lab Exercises Chapter 2 Solutions........................................................................................................... 2
Lab Exercises Chapter 3 Solutions........................................................................................................... 4
Lab Exercises Chapter 4 Solutions........................................................................................................... 7
Lab Exercises Chapter 5 Solutions........................................................................................................... 8
Lab Exercises Chapter 6 Solutions........................................................................................................... 9
Lab Exercises Chapter 7 Solutions......................................................................................................... 11
Lab Exercises Chapter 9 Solutions......................................................................................................... 12
Lab Exercises Chapter 10 Solutions ...................................................................................................... 15
1
Lab Exercises Chapter 2 Solutions
What is the output produced by the following code fragment?
num1 = 2
num2 = 3
print (num1 + num2)
num 1 + num 2 = 5
Num1 = 2
num2 := 3 := not an operator
Sum = num1 + num2; Num 1 is declared above not num1
printf(sum) printf should be print and sum should be Sum
What is an identifier?
The name given to identify a variable, function, class, module or other object.
Which of the identifiers below is valid and which are invalid? Why?
Num1
time-of-day cant have a -
tax_rate
x5
int is a reserved word
7th_Rec can’t start with a number
yield reserved word
Use # or """
2
Why should you include comments?
A high-level language is one that is user-oriented and consists of ‘english like’ statements designed to make it easier for a
programmer write code. These statements are then compiled or interpreted. A low-level language is machine-oriented.
A computer programming model that is based around objects, rather than functions and logic.
3
Lab Exercises Chapter 3 Solutions
Write a program that accepts a length in inches and prints the length in centimeters (1 inch = 2.54cm).
Note use float() for real numbers instead of int() when casting the data type in line 1, and add {:.2f} in string place holder for
two decimal places
Write a program that accepts your forename, surname and year of birth and adds them to an array.
Write a program that adds some employee data to a dictionary. Use an employee number as the key.
employee = {
'100': 'Anne',
'101': 'John',
'102': 'Emma'
}
employee.update( {'103': 'John'} )
print (employee)
F = C × 9/5 + 32
4
Write a program that calculates the volume of a sphere
V = 4/3 πr3
import math
r = int(input('Enter the radius: '))
v = 4/3 * math.pi * r ** 3
print('Volume is {} '.format(v))
Write a program to calculate and display an employee’s gross and net pay. In this scenario, tax is deducted from the
gross pay at a rate of 20% to give the net pay.
Write a program that stores a shopping list of 10 items. Print the whole list to the screen, then print items 2 and 8.
coffee
pasta
shoppingList.append('ham')
Logic operator such as AND, NOT, OR. Commonly used to combine conditional statements (eg loops & if-else statements)
print (x < 10 and x < 20)
Compares on value with another. More commonly used in loops and if else statements
x = 10
y = 14
print (x > y) #prints false as x is not greater than y
5
What is data type casting? Why do we need it? Write a program to demonstrate.
Convert a variable data type from one to another. Python converts data type into another data type automatically (implicit)
depending on what value is assigned to the variable: string, int, etc. If you need to change the type using eg int(). This is
explicit.
6
Lab Exercises Chapter 4 Solutions
Write a program to print the numbers 1 - 10 to the screen.
lists = ['name 1', 'name 2', 'name 3', 'name 4', 'name 5', 'name 6']
for counter in lists:
print (counter)
Write a program to calculate and print the squares of the numbers from 1 to 10. Use \t if you want to display in a table.
Write a program that accepts a number from the user until a negative number is entered.
userinput = 1
while userinput > 0:
print ("Enter a number: ")
userinput = int(input())
print ("ok")
Write a program that accepts an integer and prints the specified range it belongs to.
Range 1: 0 to 10
Range 2: 11 to 20
Range 3: 21 to 30
Range 4: 31 to 40
7
Lab Exercises Chapter 5 Solutions
Write a program that gets a string from the user then writes it to a file along with the user’s name.
Modify the program from exercise 1 so that it appends the data to the file rather than overwriting.
• Binary files typically contain a sequence of bytes and are much smaller and faster than text files.
• Text files store data in ASCII format and are plain text meaning they have no formatting and are human readable.
For example .txt, .py, .HTML, etc.
• Binary files store data in binary format and are usually Images, Word and Excel documents, Videos, Applications
(exe), etc.
8
Lab Exercises Chapter 6 Solutions
Write a program that accepts a number from the user and uses a function to square the number then return the result.
Print the result to the screen.
def sq(a):
return a * a
num = int(input("Enter a number: "))
print (sq(num))
Write a function that returns the largest of two numbers. Test the function and print the results to the screen.
Global is accessible from anywhere, local is only accessible within the function.
Write a program that prints first 10 positive numbers using a recursive function.
def display(num):
if(num) :
display(num-1)
else :
return
print("{}".format(num))
A parameter is a variable in the function definition. An argument is a value passed during a function call.
A function that has been defined within the python programming language
9
What is a user defined function?
Recursive programs allow programmers to write efficient functions using a minimal amount of code and is useful technique
that can reduce the length of code and make it easier to read and write. However, if performance is vital, it is better to use
iteration, as recursion can be a lot slower.
10
Lab Exercises Chapter 7 Solutions
Write a program that accepts a number from the user and uses a function to square the number then return the result.
def sq(num1):
return num1 * num1
myfunctions.py
import myfunctions
11
Lab Exercises Chapter 9 Solutions
Declare a new class called Vehicle without any attributes and methods
class Vehicle :
Add some attributes to the Vehicle class such as Name, Speed, Mileage
class Vehicle :
def __init__(self, name, speed, mileage):
self.name = name
self.speed = speed
self.mileage = mileage
class Vehicle :
def __init__(self, name, speed, mileage):
self.name = name
self.speed = speed
self.mileage = mileage
def getName(self):
return self.name
Add a method to the Taxi class to collect the fare. For example, fare is calculated by mileage * 0.20
Get the data from the user and assign to variables rn and mil
12
Create object then pass data we captured from the user (name, speed, mileage)
Call object method to calculate fare, pass the mileage captured from user to the getFare() method
route.getFare(mil)
Print results
Use the getName() method to get return the name. We can just reference the attribute using the dot notation (route.mileage,
and route.fare)
class Person :
...
...
An instance of a class
13
What is __init__() used for? Show an example.
14
Lab Exercises Chapter 10 Solutions
Create a new program and import the turtle graphics module.
import turtle
Experiment with drawing different shapes using some of the turtle graphics methods. Use the turtle commands to draw
some shapes.
import turtle
turtle.pensize(6)
turtle.penup()
turtle.pendown()
for i in range(5):
turtle.forward(200)
turtle.right(144)
turtle.done()
15