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

Python Finals Short Answers

Uploaded by

lohansag101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python Finals Short Answers

Uploaded by

lohansag101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Python Short answer questions

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

2. What are machine code and assembly language?


 Machine code is the lowest-level programming language understood directly by
the computer’s hardware.
 Assembly language is a low-level programming language that bridges the gap
between machine code and high-level languages.

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.

4. What is pseudocode, and why is it useful?


 Pseudocode does not have defined standards, rules or syntax that need to be adhered
to – focus upon internal consistency, not external consistency.
 illustrate and communicate your design in a clear way.
 are valuable design tools that experienced programmers use.
 are designed to be read by people, not parsed by a computer
 follow the conventions of programming, e.g. selection & iteration
 often omit minor, insignificant and assumed statements

5. Draw and define the main symbols used in flowcharts.


6. Write pseudocode and draw a flowchart for a program which prompts the user to input a
value in metres, then calculates and displays the value in feet.

value = int(input("Enter an value: "))


feet = float(value) * 3.281
print(value, 'meters is', feet, 'feet')

Get value in
meters Start

Feet = float(value)*
3.281

Display value
in meters
End

7. Briefly describe the key design goals and philosophy of Python.


 Python supports many different “styles” (paradigms) of programming; object-
oriented, procedural, functional.
8. Write brief definitions of the following programming terms: Statement, Variable,
Comment, Function.
Statement
 Each line in the program is a statement.

Variable

 A variable allows you to associate a value with a name.

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

 Arithmetic Operations – addition (5+5), subtraction (8-3)


 Comparison Operations – (X ==5), (6 != 9)

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.

4. Describe the difference between static typing and dynamic typing.


 Static type requires you to declare the data type of every variable you create while
Dynamic type determines the data type of a variable by the current value.

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.

10. Describe the concept of if-then, if-then-else and else-if statements.


 If-then – Statement will run a block of codes only if the condition is true.
 If-then-else - statement runs one block of code if the Boolean expression is true,
and another block if it is false.
 Else-if - Only the code following the first condition that is True. To chain multiple
comparisons together

11. What is a boolean expression (give examples)?


 An expression that result in either True or False.
Eg; 7 < 4 = False

12. Describe and list relational operators and logical operators.

Logical Operator

and && True if both comparisons are true.

or || True if either of them are True, False if both of them are False.

not ! Revers true /false


13. Write and annotate a code sample to demonstrate how the syntax of an if-then-else
statement differs between Python and a language that uses curly brackets.

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])

4. Describe the differences between lists and tuples in Python.


Lists Tuples
Mutable Immutable
Use [] brackets Use () brackets

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])

7. What does the "in" comparison operator do?


 The “in” comparison operator allows you to check if a value exists in a data
structure.
8. Python offers two basic looping (iteration) statements. Name and describe them.
 While – condition controlled
o It repeats the loop body while the loop condition is True.
o If the condition is wrong the loop body never runs.
 For – counter controlled
o It repeats the loop a number of times.

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.

11. What do the "break" and "continue" statements do?


 Break - ends the loop right away, moving on to the next statement after the loop.
 Continue - skips the rest of the loop body and then continues with the next
iteration.

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.

For num in range(2, 11, 2):


Print(num)

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.

2. Name and describe the purpose of 4 of Python's built-in functions.


 input() , print() for input and output
 str() to convert data to a string
 int() to convert a data to a integer
 len() to return the length of an object

3. What characteristics should functions have?


 A function should perform a well-defined task or process.
 Data the function needs should be passed in via parameters.
 If the function produces a result, it should return the result.
 Code inside a function should be independent of calling code.

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.

Define "get_grade" function, receives mark parameter


If mark is >= 80
Return 'HD'
Otherwise, if mark is >= 70
Return 'D'
Otherwise, if mark is >= 60
Return 'CR'
Otherwise, if mark is >= 50
Return 'P'
Otherwise
Return 'F'

8. What are "local variables" and "global variables"?


 Local variables are variables that are within the function.
 Global variables are variables that are outside the function.

9. Why should global variables not be referenced from within a function?


 It prevents functions from being independent of the code that calls them, making
them harder to reuse in other programs
 It makes errors hard to track down, since a variable’s value may be changed from
anywhere in the program
 It makes programs hard to follow and understand
 So, it is appropriate to use parameters to pass data into a function if needed.

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.

12. Summarise what a module typically contains.


 Functions
 Variables
 Classes

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

num = random.randint(1, 20)


print(num)

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.

2. Provide brief descriptions of the following programming concepts: Variables,


Comments, Built-In Functions.
 Variables, to store and refer to values via a name.
 Comments, for descriptive and informative text in a program.
 Built-In Functions, such as input() to get input, float() to convert values to
floats and print() to display output.

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.

5. What is an "expression" in programming? Give examples of an expression that results in


a number, and an expression that results in a boolean value.
6. Draw flowcharts that outline the differences between "If", "If, Else" and "If, Else-If"
statements.
7. How do data structures differ from data types, and in which ways are they similar?
Data type Data structure
Defines the kind of data Organize and store multiple types of data
Integer, float, string, boolean Tuple, array, lists

8. Outline the differences between "counter-controlled loops" and "condition-controlled


loops", and what types of situations they are best suited to.
 Counter controlled (for loop) – Repeat number of times.
 Condition controlled (while) – Continue to execute as long as the condition is
true.
9. What is "process abstraction" and how does it relate to the concept of functions in
programming languages?
 Process Abstraction is the practice of hiding the complex details of how a task is
performed, allowing you to focus on what the task does and how to use it.

10. What does a "module" in a programming language typically contain?


Functions, Classes, Variables

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.

Read mode ‘r’ – to read data from a file.


Write mode ‘w’ – to write data into the file.

Append ‘a’ – to add data in to end of the file.

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)

8. What is an exception, and what is exception handling?


Exception,
is an error or condition that occurs while a program is running, causing it to
“crash” or otherwise end.
Exception Handling,
the process of responding to exceptions when they occur.

9. Describe the difference between an exception and a syntax error.

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

print("You typed", number)

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.

15. What do the "else" and "finally" blocks do in exception handling?


 expand the capabilities of exception handling.

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

8. How do dictionaries differ from lists?


 How refer to the items.

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}

14. Why are sets not supported in many languages?


 They are only useful in fairly specific situations, and most of their functionality
can be achieved using other data structures.

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.

2. What does the concept of "encapsulation" refer to in object-oriented programming?


 Encapsulation refers to combining data and procedures into a single object.

3. Describe how a class and an object relate to one another.


 Class is a blueprint of an object or in other words class is the code which defines
the attributes and methods it has.
 Object is an instance of a class.
 Class is a combination of objects.

4. Define the terms "constructor", "attribute" and "method" in relation to object-oriented


programming.
 Constructor
It is also known as the initialiser method. Constructor automatically runs
when the object of a class is created. (Constructor method controls the
creation of objects. )
 Attribute
Attribute refers to the data that is stored in an object.
 Method

Method refers to the procedures of an object.

5. What is the difference between a private and a public attribute?


 Public attributes are accessible from outside of the object while privet attributes
are accessible from within the object.

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.

2. Outline the concept of event-driven programming?


 Event driven programs refers to the codes which handles events that are triggered
by users interacting with the GUI.

3. Define the terms "main loop", "event" and "event handler".


 Main loop – constantly listening to events.
 Event - refers to an action or occurrence detected by the program that may be
handled by the program
 Event-handler – refers to when an event occurs, it may trigger a function which
has been set to handle the particular event.

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()

self.hello_message = tkinter.Label(self.main, text="Hello")


self.hello_message.pack()

tkinter.mainloop()

gui = ProgramGUI()

6. What are "Frame" widgets used for?


 For layout of widget in a window.

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()

9. What do "tkinter.INSERT" and "tkinter.END" reference in an "Entry" widget?


 It allows to delete from or insert into the field by using these indices.

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.

You might also like