Python Finals Short Answers
Python Finals Short Answers
Module 01
1. What are the basic components of a computer and what do they do?
A processor (CPU) which can execute basic instructions
Memory to store data and instructions that are in use
Storage for ongoing retention of data and programs
Input and output devices to communicate/interact with users
3. Describe the two main methods of translating high-level source code into machine code.
Compilation: The entirety of the source code is translated into machine code and
an executable file of it is produced.
Interpretation: An interpreter translates and executes each source code statement
one at a time as the program is run.
Get value in
meters Start
Feet = float(value)*
3.281
Display value
in meters
End
Variable
Comment
Comments are descriptive or informative text that can be added to source code to
assist humans reading the code.
Function
Functions are the commands of a language that you can use to do things.
9. What is concatenation, and what are some of the differences between how it is
implemented in different languages?
Concatenation means joining two or more things together in a series or chain.
In python for concatenation, we simply use “+”, but in some languages use “.” for
concatenation also.
10. Summarise what the "input()" function does, including what it does with the text that you
can specify between the opening and closing parenthesis.
input() shows a prompt and then waits for user input.
o The parentheses let you provide data for the function.
11. Give an example of how you can control the spacing between things that you are printing
using the print() function. (refer to Reading 1.2)
12. Which high-level language was the first to be used for scientific applications, and which
high-level language was the first to be used for business applications? Are either of them
still in use today? (refer to Reading 1.4)
Scientific application – Fortran
Business application – COBO
Yes, both of them are still in use these days.
13. Summarise the concepts of writability, readability, reliability and cost with regards to
programming languages.
Module 02
1. Name the four common data types, describe what they can contain, and give an example
of each.
String, Float, Integer, Boolean
2. Describe, with examples, some things that can be done with integer values and some
things that can be done with string values.
String value
String methods – eg; len(“Python”) = 6
Indexing – “Python”[0] = P
Integers
3. Define the concept of a weakly typed language and a strongly typed language.
weakly typed languages mostly focused on being convenient. And it is achieved
by making it easier to mix different data types together.
Strongly typed languages focus on being safe. Generally achieved by limiting the
ability to mix different data types together.
5. What would you get if you converted the integer of 42 to a float, to a string, and to a
boolean? (i.e. always converting from an integer)
Float – 42.0
Boolean – True
6. What would you get if you converted the integer of 42 to a float, then to a string, and then
to a boolean? (i.e. converting from the previous data type each time)
True
7. List three values that evaluate to True in Python, and three values that evaluate to False in
Python.
True – non-zero numbers, non-empty strings, non-empty collections (2,56,84)
False – Zero numbers, empty strings, empty collection (0, (), [])
8. Describe some of the approaches that different languages take regarding the
concatenation of strings and numbers.
JavaScript always coerces both values to strings and concatenate them.
PHP avoids ambiguity by using “.” for concatenation.
9. Why is it important to always know what data types you are using in a program?
Because identifying the data type that we use helps to have a clear idea about how
the program behaves when mixing types. Therefor failing to do so can result in
bugs and vulnerabilities.
Logical Operator
or || True if either of them are True, False if both of them are False.
14. Draw truth tables illustrating the outcomes of "and" and "or" comparisons.
15. What is a string method, and how does their usage differ from using a built-in function?
String methods are a functions that can only be performed on strings or string
variables.
Module 03
1. Define the concept of a "data structure", and how it differs from that of a "data type".
Data structure allows to store multiple pieces of data types in a well-organized
structure.
Data type depicts the type of the data but data structure stores multiple pieces of
data types.
2. What is an array, and what sorts of things can be achieved by using one?
An array is an ordered collection of values.
Sort the values, count them or identify duplicate values.
Determine the maximum or minimum value.
Determine if a certain value exists in the array.
3. If you have a list variable named "colours" that contains 5 items, what are two ways that
you could refer to the last item?
Print(colours[4])
Print(colours[-1])
5. Write code to create a list variable named "nums" that contains the numbers 1, 2, and 3.
Append 4 to the end of the list. Insert 0 at the start of the list.
nums = [1, 2, 3]
nums.append(4)
nums.insert(0, 0)
print(nums)
6. If you had a string variable named "word" which contained "Paradox", how could you
refer to just the three middle letters - "rad"?
word = 'Paradox'
print(word[2:5])
9. Describe the differences in syntax between a while loop in Python and a while loop in
most other languages.
In most languages they use curly brackets “{}” but in python they do not use
curly brackets.
10. Draw flowcharts of a while loop and a do-while loop that show how they differ.
12. Provide an example to demonstrate how a do-while loop can be replicated using a while
loop, if statement and break statement.
13. Describe the two main styles of for loops.
A counter-controlled loop which works its way through a sequence.
o Eg- Fortran, Ruby, Python
A generic condition-controlled loop which is usually used in a counter-controlled
fashion.
o Eg- C, C++, Java, Javascript, PHP
14. Describe what the "range()" function in python does, and write three examples of using it
to generate different ranges.
range of numbers refers to going from a starting number to an ending number.
15. Write code that uses a loop to print every second number between 2 and 10, i.e. 2, 4, 6,
8,10. Try to write several versions of the loop, e.g. one using a range and one using
continue.
num = 1
while num <= 10:
num += 1
if num % 2 != 0:
continue
print(num)
Module 04
1. What is a "function"?
Functions are the commands of a language that you can use to do things.
4. Describe some of the benefits that writing functions can have in a long or complex
program.
Code reuse
More readable code
Better testing
Faster development
Easier teamwork
5. How should data be pass into and out of functions so that they remain independent of the
program in which they are defined?
Use parameters to pass data into functions.
Returning data from function.
Avoiding global variables.
6. Write Python code for a function named "increment" which takes a parameter, adds 1 to
it, and returns the result. Assume that the parameter is a number.
def increment(number):
result = number + 1
return result
7. Write/Draw examples of pseudocode and a flowchart that involve a function call.
10. Describe the role that parameters and return statements play in functions.
Parameters – it defines what data can be passed into tge function when it is called.
Return – return statement allows to return data d=from a function back to the code
that called it.
11. Programming languages are made up of built-in functions, standard library modules and
external modules. Describe each of these things.
built-in functions - Functions that are core to the language and are always
available without needing to “import” anything.
Standard library modules - Specialised packages of functionality that are
always included with the language but need to be imported to be used in a
program.
External modules - Specialised packages of functionality that are not included
with the language and often made by third parties. Need to be downloaded and
imported.
13. Write Python code that imports the random module and uses the "randint()" function
from it to generate a random number between 1 and 20, then print the number.
import random
14. Outline the process that often results in the creation of an external module, beginning
with a user needing a specific piece of functionality that is not already available.
User needs specific functionality.
User writes code to achieve it.
User generalizes and polishes code.
User releases module to public.
15. What are some of the things you should consider when using an external module?
Ensure the module is compatible with the version of the programming language
you are using.
Determine if the module is still needed or relevant in your version of the
programming language.
Check for bugs, security vulnerabilities and code efficiency.
Module 05
1. Define the terms "source code", "statement" and "syntax".
Source code is a set of instructions written by a programmer. The code of a program
which is written in a high-level language.
A statement is an “instruction” that tells the program to do something and must be
written using correct syntax.
syntax refers to the set of rules that define the structure and arrangement of elements
within a programming language.
3. Give some examples of situations where the data type of a variable influences how it can
be used.
4. Describe the concept of "control structures” and give examples of selection and iteration
statements.
Allows to detect and respond to errors or exceptions in a program.
11. Describe the general steps that you should follow when presented with a problem that
you need to create a program to solve.
Begin with a problem description.
Write a pseudocode to design the program.
Code the program based on the pseudocode.
Finally enhance the program by adding more features.
12. Why is it helpful to plan/design a program using pseudocode or flowcharts before writing
any code?
It helps to plan it out before worrying about code.
Module 06
1. Briefly describe the ways in which files are used in various programs/pieces of software.
To retail files, to receive inputs and to store output data.
2. What are the two main types of files that programs can use, and how do they differ?
Text files and Binary files
Binary files - are not text-based and are designed to only be opened by a program that
can use the data in that format.
3. List and describe the three most common modes that can be specified when
opening/creating files.
4. Describe, with at least one code example, the process/code needed to open a file in most
programming languages.
f = open(“filne_name”, “r”)
f.close()
5. Why is it important to close a file once you have finished using it in a program?
Not closing a file can result in losing the data that you wrote.
Will locked the file which will be unable to use by other programs.
6. Describe the different ways that you can read data from a file in Python.
Read data mode read() / readline()
7. What considerations need to be made when reading and writing numbers from/to files in
Python?
Number Formatting
Error Handling
Data conversion to strings (integer to strings)
Exception Syntax
It occurs during execution It occurs before execution
Raised by the program itself Raised by the python interpreter
Do not prevent the program from running Prevent the program from running
10. What happens if an exception occurs in a program and there is no exception handler to
handle it?
It crashes the program.
The data that was being processed at the time of the exception might not be saved
or properly handled.
11. Write code samples to demonstrate an exception handler that terminates a program and an
exception handler that continues a program.
while True:
try:
number = int(input("Enter a number: "))
break
except ValueError:
print("number required! ")
continue
12. Describe what causes the following Python exceptions: NameError, TypeError,
ValueError and IndexError.
13. How do you create a "catch-all" exception handler that will handle all possible
exceptions?
In Python, you can use a try block with a generic except clause to catch all
exceptions.
14. Why is it important to carefully consider whether a catch-all exception handler is
appropriate?
useful if various things could go wrong and it is appropriate to handle them all in
the same way.
Termination ;
The program may be unable to continue, hence the response will be to display an error
message and end in a clean manner.
Continuation :
The program may be able to continue, e.g. re-prompting for input or performing some
other action to work around the exception.
Module 07
1. What happens if you multiply a string in Python? e.g. 'ABC' * 3
ABCABCABC, it repeats the string 3 times.
2. Describe some things you can do with a list, but cannot do with a string, remembering
that lists are mutable, and strings are immutable.
Can add items, can remove items.
3. Name and present an example of two string methods used to test the content of a string.
isuppercase = FALSE
islowercase = TRUE
names = “shehani”
4. Name and present an example of two string methods used to search the content of a
string.
num = “Hi yall my name is Shehani Silva.”
num.startswith(“Hi”) = TRUE
num.find(“i”) = 1
5. Name and present an example of two string methods used to manipulate the content of a
string.
num = “Hi yall my name is Shehani Silva.”
name = num.upper()
name = num.lower()
6. Write one line of Python code which turns a string into uppercase, replaces any "E"s with
"3"s, and strips whitespace from both ends.
names = " shehani ranudi silva "
num = names.upper().replace("E", "3").strip(" ")
print(num)
7. What are some of the names that dictionaries are known by in other languages?
Associative Arrays, Maps, Hash tables
9. What happens if you try to refer to a key that does not exist in a dictionary?
It shows KeyError message.
10. Write Python code that defines a list of dictionaries. The list should contain at least 2
dictionaries, each one containing at least 2 details about a thing, e.g. the title and runtime
of movies.
thing = [{"Name": "Blueberry Soap", "Colour": "Blue"},
{"Name": "Pizza", "Colour": "Red"}]
for items in thing:
print(items["Name"] + "-"+ items["Colour"])
11. What is a set, and how does it differ from a list and a dictionary?
A set is an unordered collection of values.
In sets there no index or keys.
12. What does the union of two sets contain, and what does the intersection of two sets
contain?
union of two sets contain – combination of two sets.
Intersection of two sets – Items in both sets.
13. Show with examples how curly braces ("{" and "}") can be used to create both
dictionaries and sets.
num = {“Shehani”: 2005, “Hasindi”: 2004, “Oshani”: 3654}
set_one = {“Blue”, “Pink”, “Purple”}
set_two = {12, 6, 10, 3}
15. Describe how Python behaves when using a "for" loop to iterate through a string, a list, a
dictionary and a set, including what the target variable is set to on each iteration of the
loop.
For a string, the target variable is each character.
For a list, the target variable is each element.
For a dictionary, the target variable can be each key, value, or key-value pair
depending on the method used.
For a set, the target variable is each element, with no guaranteed order.
Module 08
1. Outline the main differences between procedural programming and object-oriented
programming.
Procedural programming is a linear approach and OOP is abstract approach. And
procedural programming is a program which is broken down to procedures while
OOP is a program which is broken down to objects.
6. Why is it useful to have getter and setter methods rather than public attributes in a class?
7. How do you make an attribute or method private (instead of public) in Python?
In python to make a tribute or method private we only need to add two
underscores “__” to the start of the attribute or method.
8. What does the "__str__" method do in a class in Python?
It allows you to define what will generate if you convert an object to a string.
9. How do the names of constructors differ between Python and other languages such as
Java and C++?
In python constructor name as “_init_”.
In Java the constructor has the same name as the class.
Similar to Java, in C++ the constructor has the same name as the class.
10. Use a real-world analogy to describe an object, attributes of that object, and methods of
that object.
Object – Pile of dice
Attributes – quantity of dice, sides of dice, results of roll
Methods – roll dice, get results
Module 09
1. What is a Graphical User Interface (GUI) and how does it differ from a Command Line
Interface (CLI)?
GUI is an event driven user interface. In a GUI program the user can interact with
the active part of the GUI at any time.
Interaction method
o GUI used to interact with buttons and menus which are done by through
touchscreen or mouse.
o But in CLI they use text-based commands through keyboard interaction.
4. Name and briefly describe 5 widgets available in the "tkinter" module (i.e. Tk).
Basic window interaction – Button, Scrollbar, Menu
Display text and graphics – Canvas, Label, Message
To enter input box – Text, Entry
Form elements – Checkbuttons, Rdiobuttons, Scale
Layout of a widget in a window – Frame
5. Write code that creates a "Label" widget with the text "Hello" and packs it to the bottom
side of a window named "main".
import tkinter
class ProgramGUI:
def __init__(self):
self.main = tkinter.Tk()
tkinter.mainloop()
gui = ProgramGUI()
7. How do you specify a function or method to call when a "Button" widget is clicked?
self.show_box
8. Describe some of the message boxes types that can be shown using the
"tkinter.messagebox" module.
Information box with ok button - showinfo()
Error message box with ok button - showerror()
Warning message box with ok button – showwarning()
Confirmation box with ok/cancel button or Yes/No button – askyesno(),
askcancel(), askretrycancel()
10. Why is it useful to create a mockup of a GUI before trying to implement it?
It is useful since it can be tedious to repeatedly implement and modify a GUI.