University of Portsmouth Python Programming Questions the questions are in the file exersise attached and the material is in the other file File: WEEK_FIVE

University of Portsmouth Python Programming Questions the questions are in the file exersise attached and the material is in the other file File: WEEK_FIVE_EXERCISES
UPDATED: JUN 14 2020
These exercises are for Week Five of the Programming Concepts module.
They are not intended to be homework but instead material to attempt (when
prompted to) during the Zoom class. They will be based upon the ideas
presented in the separate Week Five notes on Moodle. You should save your
work as a Word file which you can upload to a Turnitin link. You can of course
add more material to your work after the Zoom class before uploading. (If you
wish you can work by hand and then scan your sheets of paper into a Word
document which you subsequently upload.) As these examples are based
upon the material in the Week 5 notes on Moodle make sure that you study
these notes carefully.
These exercises will be marked but do NOT contribute to your overall module
result, which is determined solely by the Week 4, Week 6 and Week 8 multichoice answer tests, the coursework assignment and the final exam.
EXERCISE 1 (Approximately 15 minutes class time)
Write a short essay (50 -150 words) explaining why it is important to become
used to the concept of using functions when programming.
EXERCISE 2 (Approximately 10 minutes class time)
Write a Python program, containing the functions weight() and main(), which
asks the user to enter their weight and will then say “That sounds healthy” or
“Perhaps you should diet”. The function weight() will include print, input, if and
else. The function main() will call the function weight(). It does not need to
contain any further lines of code.
EXERCISE 3 (Approximately 10 minutes class time)
Write a Python program containing functions called main(), david() and mary().
If David runs the program he should see a message from his mother ordering
him to wash the family car. If Mary runs the program she should see a
message asking her to do an additional hour of maths homework every
evening to make up for her poor score in the class exam. The function main()
should include raw_input and if instructions. It will call either david() or mary().
The other two functions, david() and mary(), should only include print.
EXERCISE 4 (Approximately 15 minutes class time)
Rewrite this Python program to use three functions, main(), upstairs() and
downstairs().
# Summer holiday program
print(“Hi there! I hope you are having”)
print(“a great summer.”)
answer = raw_input(“Are you keen on travelling?”)
if (answer == “YES”):
print(“I believe it’s really”)
print(“exciting to visit”)
print(“upstairs and even”)
print(“have a look at the attic.”)
else:
print(That’s okay.”)
print(“The kitchen is fun.”)
main()
EXERCISE 5 (Approximately 15 minutes class time)
Write a Python program which will calculate the area of a hexagon. Your
program should contain two functions, main() and hexagon(A). A is a local
variable in the function hexagon(A). In main the user is prompted to enter a
value for a variable called side. This variable is then passed to the function
hexagon(A). In this function the area of the hexagon is calculated and
displayed immediately using print. (Assume that the area of a hexagon is
given by the expression 2.6 * side * side, where side is the length of one side
of the hexagon.)
EXERCISE 6 (Approximately 15 minutes class time)
Write a Python program which will calculate the area of a circle. Your program
should contain two functions, main() and a function called area(A) which will
perform the calculation itself. The variable A will be a local variable in the
function area(A). In main() the user will enter a value for the radius of the
circle. This value is then passed by main() to area(A). The function area(A)
returns the value of the circle’s area to main(). The result is finally displayed
by main() using print. Assume that the area of a circle is calculated, with an
approximate value for pi, by area = 3.14 * radius * radius.
EXERCISE 7 (Approximately 20 minutes class time)
Study this program and then answer the questions which follow it,
# Polishing program
def floor(A, B):
C=A*B
return C
def rug(A):
B = 3.14 * A * A
return B
def main():
print(“This program will”)
print(“calculate the area”)
print(“of floor you have”)
print(“to polish.”)
X = input(“How long is the room?”)
Y = input(“How wide is the room?”)
Z = input(“What is the radius of the rug?”)
print(“The area you have to polish is”),
print floor(X,Y) – rug(Z)
main()
a) What are the variables entered by the user?
b) What are the local variables in the function called floor?
c) What are the local variables in the function called rug?
d) What variable is returned by the function called floor?
e) What variable is returned by the function called rug?
f) Write a short essay explaining in detail what precisely is happening in the
final line of main(), print floor(X,Y) – rug(Z)
1
File: NEW_FIVE
JIM’S BITS
NEVER FIT…
UPDATED: JUN 13 2019
Why functions are
important
Functions in Python: def
Calling a function
Passing values to a
function
Local variables
Returning values from a
function
Helping Frank Drake
Exercises
ONE – WHY FUNCTIONS ARE IMPORTANT
Exercises
One of the most important concepts in programming is working with
functions. This is the way in which code can be divided up into separate
sections which operate almost in complete isolation from one another.
One particular section has its own ‘job’ which it gets on with independently
of whatever the rest of the program code is about. These sections of code
only communicate with each other when they need to. Of course they do
occasionally have to do this, when they pass on a result which is required
somewhere else or to acquire some data which is needed, but most of the
time they are concentrating on the specific thing they are designed to do.
This is really very much like the way people organise themselves… After
dinner you go upstairs to do your homework while Dad does the washing
up and Mum phones Grandma. You’d never get to university if you had to
wear rubber gloves and talk about price of cat food while learning how to
do integration by parts…
It is vital therefore that everybody becomes familiar with using functions.
The problem, though, is that initially they look really peculiar. Functions
seem to make programming more difficult although in reality they make it
much simpler. It just takes a while to notice that it’s actually getting easier!
2
TWO – WRITING A FUNCTION IN PYTHON: def
Probably the best way to get started with using functions is to write a short
program and then rewrite it in a functional format. Here is a very simple
program which is using hardly any Python at all, just a comment,
raw_input and print:
This of course is the sort of thing this program can do:
Now the program is written in this more complicated way
This second version of the program behaves in exactly the same way as
the first. It also appears unnecessarily complicated. Nevertheless this is
the way that anything, except the very simplest of code, should be written.
The second version is using functions.
What is happening is this:
3
When the program is executed the function main() is called. It then calls
in turn the function greeting(). Doing it this way might seem completely
pointless but it allows a complicated problem-solving task to be divided up
into simpler chunks of code. This allows a greater clarity in the way the
code is written. If functions are used, main() is always the ‘starting point’.
In Python a functions is always written beginning with the word def. After
this is the function name. (You can choose any name you like provided
that you avoid reserved Python words like print, input, if etc.) After the
function name there must be a pair of brackets. These are followed by a
colon. (You will understand the significance of the brackets later.) The
separate lines of the function which form the function body must be
indented by four character spaces. (IDLE will do this for you, but does
sometimes get indentation wrong!)
A function is called by using its name.
Here is another example of a program being rewritten to include functions.
In the first version functions are not employed. (The program gives advice
to pet owners.)
# Pets program
# This program helps people
# look after their pet properly
pet = “octopus”
while (pet != “cat” and pet != “dog”):
pet = raw_input(“Enter what pet you look after “)
if (pet == “cat”):
4
print(“Make sure your cat is happy.”)
print(“Give it lots of food.”)
print(“A comfortable cardboard box is essential.”)
print(“Cats like having a tree handy”)
print(“so they can keep an eye on what’s”)
print(“going on in the world.”)
if (pet == “dog”):
print(“Dogs love running about”)
print(“and barking.”)
print(“Frequently they bite you!”)
print(“Don’t worry!”)
print(“It’s just their idea of a joke.”)
print(“Program over”)
Here is the code shown in Python:
This is the result of running the program:
5
Here the program is now written in functional form. Most of the code is
unaltered. It is just rearranged into three separate functions, main(),
pussycat() and nicedoggie():
# Pets program
# This program helps people
# look after their pet properly
def pussycat():
print(“Make sure your cat is happy.”)
print(“Give it lots of food.”)
print(“A comfortable cardboard box is essential.”)
print(“Cats like having a tree handy”)
print(“so they can keep an eye on what’s”)
6
print(“going on in the world.”)
def nicedoggie():
print(“Dogs love running about”)
print(“and barking.”)
print(“Frequently they bite you!”)
print(“Don’t worry!”)
print(“It’s just their idea of a joke.”)
def main():
pet = “octopus”
while (pet != “cat” and pet != “dog”):
pet = raw_input(“Enter what pet you look after “)
if (pet == “cat”):
pussycat()
if (pet == “dog”):
nicedoggie()
print(“Program over”)
main()
Here is the code now shown in Python:
7
You can see here that the program still works:
THREE – PASSING VALUES TO A FUNCTION
These first two examples of programs using functions do not actually show
the tremendous power of programming in this way. Functions only
become important when they can be passed values from another function
and also return values to the function which is calling them. This permits
very complex data processing to be achieved with remarkably compact
program code.
A function which is passed a value is shown in the next example. This
program calculates the area of a rectangle. (Nothing complicated yet!) It
has two functions main() and rectangle(). In main() values are entered for
the length and width of the rectangle. These are assigned to variables
called length and width. The two variables are then passed to the separate
function rectangle() when it is called by main(). This is done by placing the
two variables between the brackets in this line rectangle(length, width).
A lot is happening in this one line. The function rectangle() is being called,
ie program execution jumps here from main() to rectangle(). In addition
the values of the two variables length and width are given to the function
rectangle(). When they get there they are reassigned to two separate
8
variables called A and B. These are local variables in the function
rectangle(). They only exist in rectangle(). The function main() is beyond
their scope. If you attempted to print out the value of A or B in main() it
would lead to an error. Become familiar with the concept of local variables.
They are important in programming with functions.
A and B in rectangle() have the values entered in main(). So multiplying
them together will give the correct area of the rectangle. This is displayed
by the use of print A * B in the function rectangle().
Here is the code:
# Rectangle program
def rectangle(A, B):
print A * B
def main():
length = input(“Enter length of rectangle “)
width = input(“Enter width of rectangle “)
print(“The area of your rectangle is”),
rectangle(length, width)
main()
The code now looks like this in IDLE:
Finally the result of a typical program execution is shown in the Python
shell:
9
FOUR – RETURNING A VALUE FROM A FUNCTION
The next example extends the idea of local variables in a function. This is
how the program works. In main() the user enters values for the height
and base of a triangle. These variables are (imaginatively!) called height
and base. (They could of course have been called tom and jerry.) Their
values are then passed to a function called triangle() by this section of
code: triangle(height, base) Inside the triangle() function the values are
assigned to two local variables, A and B. A third local variable is
introduced. This is C. It is given the value of the area of the triangle by the
code: C = A * B / 2 (Note that the math used in this programming module
is not particularly mind-blowing, but feel free to ask the person next to you
if you’re not sure…)
The important bit now happens. The calculated value of C is returned to
the function which has called triangle, ie the function main(). The code
which does this is return C.
Once this takes place the value of the triangle() function itself in main() is
the returned value of C. This will probably seem rather strange. But if you
want to see what the area of the triangle is you just use print
triangle(height, base)
So this one line of code is doing a lot! It is calling the function triangle(). It
is passing values to it. It is this displaying the returned value.
# Triangle program
def triangle(A, B):
C=A*B/2
return C
def main():
height = input(“Enter height of triangle “)
base = input(“Enter base of triangle “)
10
print(“The area of your triangle is”),
print triangle(height, base)
main()
Here is the code in IDLE:
Here is the program working:
FIVE – HELPING FRANK DRAKE
The program for Frank Drake is now rearranged to use functions. (To
follow the next bit you will probably need to look at last week’s notes as
well.) The program now has three functions, main(), analyse() and
picture().
11
# Helping Frank Drake
# Version 3
def analyse(A):
# Array holds prime numbers
primes = [0.0] * 5
primes[0] = 2.0
primes[1] = 3.0
primes[2] = 5.0
primes[3] = 7.0
primes[4] = 11.0
# Discover if message is product of two primes
# Boolean variable initially assumes it is not
B = False
C=0
D=0
for i in range(5):
cofactor = A / primes[i]
for j in range(5):
# Condition checks if product of two primes
if (primes[j] == cofactor):
C = int(primes[j])
D = int(primes[i])
B = True
return B, C, D
def picture(A, B, C):
for i in range(A):
for j in range(B):
c=i*B+j
print C[c],
print
print
def main():
# Acquire data
message = raw_input(“Enter alien message “)
# Find number of digits in message
signal = len(message)
print(“Number of digits in message is”), signal
found, rows, columns = analyse(signal)
12
# Display decoded picture
if found:
print(“Message is product of two primes”), rows, “and”,
columns
# Show first orientation
picture(columns, rows, message)
# Show second orientation
swap = rows
rows = columns
columns = swap
picture(columns, rows, message)
else:
print(“Message is not product of two primes”)
main()
The role of the function analyse() is to determine whether the length of the
signal is the product of two prime numbers. It is passed one variable which
is the length itself. This code in main() does it: analyse(signal). In
analyse() the value of signal is assigned to the local variable A by this line:
def analyse(A).
The function analyse() has three other local variables, B, C and D. By the
time analyse() has finished chomping away at the numbers the three local
variables have specific values. B has a Boolean value indicating whether
two primes have been found or not. C might then be the number of rows.
D might be the number of columns. These three values are all returned to
main() by: return B, C, D. In main() they are assigned to variables called
found, rows and columns by: found, rows, columns = analyse(signal)
You will see therefore that in Python multiple returned values are possible.
This is rather useful!
The function picture() draws the rectangle. It has three local variables, A,
B and C. These are NOT the same as the ones in analyse(). Remember
that local variables are confined, by their scope, to the function in which
they occur. In picture() A is the number of columns. B is the number of
rows. C is the string representing the message itself. So picture() is called
by: picture(columns, rows, message)

Purchase answer to see full
attachment

Don't use plagiarized sources. Get Your Custom Essay on
University of Portsmouth Python Programming Questions the questions are in the file exersise attached and the material is in the other file File: WEEK_FIVE
For $10/Page 0nly
Order Essay
admin

Recent Posts

Economic Debate #3- Progressive Income Tax – The Homework Helper

Economic Debate- Progressive Income Tax For this Economic Debate, we are going to discuss the…

2 years ago

MKT 6120 – Marketing Management – Davis Learning Engagement #7

TOPIC: Going Global Discussion Thread 1 (initial post due Wednesday for full credit) Please note:…

4 years ago

jvjvjhvjhvhjvj

Assignment Topic This week will culminate in the creation of a narrated PowerPoint to create…

4 years ago

Students are supposed to select a technological organization of their choice.

The Assignment must be submitted on Blackboard (WORD format only) via allocated folder. Assignments submitted…

4 years ago

Increases the risk of wildfires

you need to post your 2-page information flier to share with your Final Project Group.…

4 years ago

Statistics for Technology management

discussion: Discuss the methods used at your company to measure and ensure quality products and…

4 years ago