0% found this document useful (0 votes)
124 views5 pages

HCA Python Exam Q&A Guide

1. The document describes an examination for a Python programming course, including instructions, sections on general questions and problems, and a case study on creating a class to calculate the greatest common divisor (GCD) of two numbers. 2. Section A includes multiple choice and open response questions testing Python concepts like modules, data types, and built-in functions. Section B provides a problem to write a GCD class with private properties and a method to compute the GCD. 3. The case study asks students to write a GCD class that takes two numbers in the constructor, normalizes negative values, computes the GCD privately, and provides a way to access the result from outside the class. It also

Uploaded by

ckiadj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views5 pages

HCA Python Exam Q&A Guide

1. The document describes an examination for a Python programming course, including instructions, sections on general questions and problems, and a case study on creating a class to calculate the greatest common divisor (GCD) of two numbers. 2. Section A includes multiple choice and open response questions testing Python concepts like modules, data types, and built-in functions. Section B provides a problem to write a GCD class with private properties and a method to compute the GCD. 3. The case study asks students to write a GCD class that takes two numbers in the constructor, normalizes negative values, computes the GCD privately, and provides a way to access the result from outside the class. It also

Uploaded by

ckiadj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SEMESTER:1: HCA EXAMINATION

SPECIALTY: BTECH LEVEL: 3


COURSE TITLE: PROGRAMMING USING COURSE
PYTHON A CODE:
SEIT413A
AUTHORISED DOCUMENTS: YES  or NO  Time: 2 Hours Lecturer Name’s: AZOBOU KIADJEU CEDRIC

Instructions
1. The answers must be clear as possible to avoid any misunderstanding.
2. Any types of documents rather than the ones given by the invigilators are prohibited
3. In the MCQ part, each question has one (01) and only one good answer. Draw a table with 02 entries one for
question number and the other one for the letter corresponding to your good answer.
4. In the open answer questions, give a clear answer for each question with the maximum details according to the
total number of marks given
5. In the case study, your answers need to be oriented on practice. Give answers that can permit a technician to
achieve the goal. not just for the comprehension.

SECTION A: GENERAL QUESTIONS (20 marks)


PART 1: MCQ 10 Marks
1. What is the name of the GUI that comes in-built as an interactive shell with Python?
a. PGUI
b. PyShell
c. IDLE
d. PythonSH
2. The function to display a specified message on the screen is?
a. print
b. display
c. run
d. output
3. A user-specified value can be assigned to a variable with this function?
a. user
b. enter
c. input
d. value
4. What will be the value of the following Python expression?
(4 + 3) % 5
a. 7
b. 2
c. 4
d. 1
5. What will be the output of the following Python code?
i = 1
while True:
if i%3 == 0:
break
print(i)
 
i += 1

1/3
a. 1 2 3
b. 2
c. 1 2
d. None of the mentioned
6. What will be the output of the following Python expression if x=56.236??
a. 56.236
b. 56.23
c. 56.0000
d. 56.24
7. What will be the output of the following Python function?
len(["hello",2, 4, 6])

a. Error.
b. 6
c. 4
d. 3
8. Which function is called when the following Python program is executed?
f = foo()
print(f)
a. str()
b. format()
c. __str__()
d. __init__()
9. Which function is called when the following Python program is executed?
f = foo()
a. str()
b. __str__()
c. init()
d. __init__()
10. What will be the output of the following Python program?
i = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)

a. Error.
b. 0 1 2 0
c. 0 1 2
d. None of the above

2/3
PART 2: OPEN ANSWER QUESTIONS 10 Marks
1. What are modules and packages in Python 02 marks
 Modules, in general, are simply Python files with a .py extension and can have a set of
functions, classes, or variables defined and implemented. They can be imported and
initialized once using the import statement. If partial functionality is needed, import the
requisite classes or functions using from foo import bar.
 Packages allow for hierarchical structuring of the module namespace using dot
notation. As, modules help avoid clashes between global variable names, in a similar
manner, packages help avoid clashes between module names.
Note: Creating a package is easy since it makes use of the system's inherent file structure. So
just stuff the modules into a folder and there you have it, the folder name as the package name.
Importing a module or its contents from this package requires the package name as prefix to
the module name joined by a dot.
2. What are the key features of Python in your opinion? give 02 of them 02 marks
 Python is an interpreted language.
 Python is dynamically typed: this means that you don’t need to state the types of
variables when you declare them or anything like that.
 Python is well suited to object orientated programming in that it allows the definition of
classes along with composition and inheritance.
 In Python, functions are first-class objects. This means that they can be assigned to
variables, returned from other functions and passed into functions. Classes are also
first-class objects
 Writing Python code is quick but running it is often slower than compiled languages.
 Python finds use in many spheres – web applications, automation, scientific modeling,
big data applications and many more.
3. What is Scope in Python? Give 03 examples 02 marks
 Every object in Python functions within a scope. A scope is a block of code where an
object in Python remains relevant. Example: Local, global, module-level and outermost-
level scope. In OOP we can add public, protected and private scope
4. What are Keywords in Python? Give 03 of them 02 marks
Keywords in python are reserved words that have special meaning. They are generally used to
define type of variables. Keywords cannot be used for variable or function names. E.g.: And, Or,
Not, If, Elif, Else, For, While, Break, As, Def, Lambda, Pass, Return, True, False, Try, With, Assert,
Class, Continue, Del, Except, Finally, From, Global, Import, In, Is, None, Nonlocal, Raise, Yield
5. Give a function used for: 02 marks
a. Convert string to integer: int ()
b. Convert int to string: str ()
c. Convert any data type to list type: list ()
d. Allow the user to enter a value in the console: input ()

3/3
Section B: PROBLEMS (10 marks)
GCD stands for Greatest Common Divisor and it is applied on 02 integers to return the GCD of
these 02 numbers. Due to the regular use of this notion, we want to write a python class allowing us to
calculate the GCD of 02 numbers. Our class needs 02 positive attributes and 01 method which
calculates the GCD of these 02 numbers.
Note: Comment your code to avoid any misunderstanding.
1. Write a class called GCD with 02 private properties and make sure that during instantiation if a
user defines a negative integer the constructor just uses the opposite of that negative number.
04 marks

class Gcd:
def __init__(self, nbre1, nbre2):
if(nbre1!=0 and nbre2!=0):
if(nbre1 < 0)
nbre1 = -1 * nbre1
if(nbre2 < 0)
nbre2 = -1 * nbre2
self.__nbre1 = nbre1
self.__nbre2 = nbre2
self.__gcd = nbre1
else:
raise TypeError("Only integers different than 0 are acceptable")
2. Write a private method that calculates the GCD of 02 private properties 02 marks
def __GcdComputation(self):
n1 = [Link](self.__nbre1)
n2 = [Link](self.__nbre2)
while (n1 != n2):
if (n1 > n2):
n1 = n1 - n2;
else:
if (n1 < n2):
n2 = n2 - n1
return n1
1. Explain how we will call the above function in another class or in the main function since it is
private 02 marks

4/3
We need to add a private property for GCD values in the class and write public
accessors to recover the value.
2. Write a main class which requests 02 integers from a user, instantiate the GCD class and
display the GCD of the specified numbers. 02 marks
try:
t=Gcd(10,16)
print(t)
print([Link]())
except:
print("Check if there is no null value because there are not
allowed")
print("or your are trying to access a private method out of a class")

5/3

Common questions

Powered by AI

A Python module is a file containing Python definitions and statements, typically with a .py extension. Modules allow for defining functions, classes, or variables in a single file and can be imported using the 'import' statement . On the other hand, a package is a collection of modules that are organized under a single directory hierarchy, which allows for better namespace management using dot notation. The use of packages helps avoid naming collisions among modules by organizing them in a structured directory . Whereas modules help avoid clashes between global variable names, packages assist in managing the module namespace hierarchy. Organizing code into modules and packages makes large-scale applications more manageable, as it categorizes functionalities logically according to tasks or areas .

Providing public accessors for private properties in a Python class is critical for maintaining encapsulation, a fundamental principle of object-oriented programming (OOP) that restricts direct access to an object's internal state. By using public getter and setter methods, classes can control how attributes are accessed and modified, ensuring data integrity and hiding internal implementation details . This adherence to OOP principles promotes code robustness, simplifies maintenance, and reduces the risk of unintended side effects caused by external modification of private attributes. Public accessors provide a controlled interface, allowing the internal structure of a class to change without affecting external code that interacts with it, which enhances modularity and facilitates future code evolution .

Python, as an interpreted language, executes code line-by-line, which provides significant flexibility during development by allowing interactive testing and debugging . This feature permits rapid code prototyping and iteration as changes do not require recompilation, which is beneficial for developers who need to adapt code quickly. However, interpreted languages often run slower than compiled languages like C++ or Java, as they do not undergo the optimization processes utilized during compilation. Compiled languages translate code into machine language before execution, allowing for more efficient use of resources and generally faster execution speeds. Thus, the interpreted nature of Python prioritizes developer productivity and ease of use over raw execution speed, making it suitable for a wide range of applications where development speed is more critical than runtime performance .

Python's simplicity and readability have a significant educational impact on beginners learning to program as its syntax closely resembles human language . This accessible design lowers the barrier to entry, enabling students to focus on understanding fundamental programming concepts rather than complex syntax. Python's intuitive structure promotes learning by making program logic more transparent and less error-prone, which is crucial for building confidence in beginners. Its extensive library support and community resources provide valuable tools for exploration and experimentation, helping learners to engage with more complex projects early in their education. Overall, Python serves as an excellent gateway for novices to enter the coding world, providing a strong foundation for understanding advanced concepts in computer science .

In Python, scope refers to the visibility and lifespan of variables within different parts of a code. There are several scopes: local, global, module-level, and outermost level. For example, a variable defined within a function has a local scope and is accessible only within that function . In contrast, a global variable is accessible throughout the module or program unless shadowed by a local variable within a function. Proper scope usage ensures that variables do not interfere with each other, thus maintaining code correctness. Using scopes effectively prevents unintentional modifications or access to variables that could lead to bugs, especially in larger programs where variables are reused across different modules or functions .

First-class functions in Python mean that functions are treated as first-class citizens; they can be assigned to variables, passed as arguments, and returned from other functions . This feature enhances Python's programming capabilities by allowing more flexible and powerful program design patterns, such as higher-order functions and functional programming. First-class functions enable developers to use functions as building blocks, leading to more modular and reusable code. They facilitate advanced programming techniques like decorators, closures, and callback functions, ultimately contributing to the language's flexibility and expressive nature. This characteristic is crucial in supporting Python's adaptability in various domains such as web development, data analysis, and artificial intelligence .

Python's support for multiple programming paradigms, such as procedural, object-oriented, and functional programming, benefits developers by offering flexibility in solving problems using the most appropriate style . This versatility allows developers to choose paradigms that best fit their problem domain, leading to more efficient and effective solutions. For instance, procedural programming can be used for straightforward scripting tasks, while object-oriented programming is suitable for complex systems that require encapsulation and inheritance. Functional programming features like first-class functions and lambda expressions enable concise and expressive code for data transformations. By not being confined to a single paradigm, Python empowers developers to leverage a combination of approaches, encouraging innovative solutions and fostering a comprehensive understanding of different programming techniques .

Python's dot notation and hierarchical structuring allow packages to manage modules by organizing them in directory-like structures. This method helps prevent naming conflicts by creating a namespace hierarchy where modules can be accessed using their package name as a prefix, thus reducing potential clashes in module names . For instance, two modules named 'utils' in different packages can be distinctly referenced as 'package1.utils' and 'package2.utils'. This design provides clarity and structure, enabling developers to manage and navigate complex codebases more efficiently. The system's inherent file structure, combined with dot notation, facilitates logical organization and modularization of code, promoting scalability and maintainable software architecture .

Reserved keywords in Python are predefined words that have specific meanings defined by the language syntax. They cannot be used as variable or function names as they serve a unique purpose in defining the language's structure and behavior . Keywords such as 'if', 'elif', 'else', 'for', and 'while' are used for flow control, while 'try', 'except', 'finally', and others facilitate error handling. The deliberate design of reserved keywords ensures consistency and predictability in the language's behavior, thus aiding developers in writing clear and maintainable code. By maintaining a limited set of reserved words, Python achieves a balance between language simplicity and expressive power .

Python's dynamic typing allows variables to be assigned without explicitly declaring their type, which increases flexibility and speed of writing code as developers can focus on logic rather than types . This feature promotes rapid development and prototyping by reducing the boilerplate code associated with type declarations. However, dynamic typing can impact performance negatively compared to statically typed languages because type errors may only become apparent at runtime, potentially leading to more runtime errors and challenging debugging . Additionally, the lack of type enforcement can result in slower execution since the Python interpreter must handle variable datatype operations dynamically. This results in an inherent trade-off between ease of development and performance efficiency .

You might also like