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

PYTHON1

Uploaded by

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

PYTHON1

Uploaded by

avosehsamuel500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

QUESTION ONE

1a. What is python.

Answer:

Python is a high-level, interpreted programming language known for its simplicity and readability.
Python emphasizes code readability and allows programmers to express concepts in fewer lines of
code.

1b. Name 5 of the features of python and write short note on them.

Answer:

i. Easy to read and learn: Python's syntax is known for being clear and concise,
resembling natural language more than some other programming languages.
ii. Free and Open-Source: Python is an open-source language, meaning its development
is freely available for anyone to contribute to.
iii. Extensive Libraries: Python boasts a vast collection of standard libraries and third-
party packages. These libraries provide pre-written code for various tasks like data
analysis (NumPy, Pandas), web development (Django, Flask), machine learning
(TensorFlow, PyTorch), and more.
iv. Interpreted Language: Unlike compiled languages, Python code doesn't need to be
translated into machine code before execution. Instead, an interpreter reads and
executes the code line by line, making development faster and more flexible
v. Object-Oriented Programming (OOP): Python supports OOP concepts like classes,
objects, inheritance, and polymorphism.

1c. Write a python programming to print out your name, age, sex, matriculation number
and year of admission

Answer:

name = "John Doe"

age = 20

sex = "Male"
matriculation_number = "12345678"

year_of_admission = 2022

print("Name:", name)

print("Age:", age)

print("Sex:", sex)

print("Matriculation Number:", matriculation_number)

print("Year of Admission:", year_of_admission)

QUESTION TWO

2a. List the two types of comments in python and write short note on each of them

Answer:

1. Single-Line Comments: Single-line comments in Python are created using the hash
symbol (#). Any text following the # on the same line is ignored by the Python interpreter.
Single-line comments are typically used for brief explanations or annotations within the
code.
2. Multi-Line Comments (Block Comments): Multi-line comments, or block comments,
are used to comment out multiple lines of code or to write longer comments that span
several lines. In Python, multi-line comments are often created using triple quotes (''' or
"""). Although this syntax is technically for multi-line strings, it is commonly used for
block comments when the content is not assigned to a variable.

2b. What are the values for the following python expression?

Answer:

i. 2**(3**2) = 512
ii. (2**3)**2 = 64
iii. 2**3**2 = 512
iv. 8/4/2 = 1.0
v. 8/(4/2) = 4.0

2c. Define the following with relevant examples

Answer:

a. Object: An object is a fundamental concept in object-oriented programming (OOP). It is


a concrete instance of a class, which encapsulates data and behavior (methods). Objects are
created from classes and represent specific instances of that class. Example
# Define a class called "Person"
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# Create an object (instance) of the class "Person"


person1 = Person("Alice", 30)

# Accessing object attributes


print(person1.name) # Output: Alice
print(person1.age) # Output: 30

b. Class: A class is a blueprint for creating objects in object-oriented programming. It defines


the attributes (data) and methods (functions) that the objects of the class will have. Classes
provide a way to organize and structure code by grouping related data and behavior
together. Example
# Define a class called "Car"
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car: {self.year} {self.make} {self.model}")

# Create objects (instances) of the class "Car"


car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Accord", 2018)

# Accessing object attributes and calling object methods


car1.display_info() # Output: Car: 2020 Toyota Camry
car2.display_info() # Output: Car: 2018 Honda Accord

2d. State the differences between object oriented programming and procedure oriented
programming

Answer:

1. Data and Functions:


 Procedural Programming:
o Focuses on functions (procedures) that operate on data.
o Data is separate from functions.
 Object-Oriented Programming:
o Focuses on objects that encapsulate data and behavior (methods).
o Data and functions (methods) are bundled together within objects.
2. Encapsulation:
 Procedural Programming:
o Typically lacks strong support for encapsulation.
o Data and functions may be accessible from anywhere in the program.
 Object-Oriented Programming:
o Emphasizes encapsulation, where data and methods are bundled together within
objects.
o Objects hide their internal state and only expose a controlled interface (methods) for
interacting with the data.
QUESTION THREE

3a. List the operators in python, and state their order of precedence

Answer:

1. Arithmetic Operators:
Exponentiation (**): Computes the power of a number.
Multiplication (*), Division (/), Floor Division (//), Modulo (%): Perform multiplication,
division, integer division, and modulo operation respectively.
Addition (+), Subtraction (-): Perform addition and subtraction.
2. Comparison Operators:

Greater Than (>), Greater Than or Equal To (>=), Less Than (<), Less Than or Equal To
(<=): Compare the values of two operands.

Equality (==), Inequality (!=): Check for equality and inequality between operands.

3. Logical Operators:

Logical AND (and): Returns True if both operands are true.

Logical OR (or): Returns True if either operand is true.

Logical NOT (not): Returns the opposite boolean value of the operand.

4. Assignment Operators:

Assignment (=): Assigns a value to a variable.

Compound Assignment (+=, -=, *=, /=, %=, //=, **=): Perform arithmetic operation and
assign the result to the variable.

5. Identity Operators:

Identity (is): Returns True if both operands refer to the same object.

Non-identity (is not): Returns True if both operands do not refer to the same object.
3b. write a python programming to compute the sum and average of ten numbers

Answer:

total_sum = 0

count = 10

for i in range(count):

num = float(input(f"Enter number {i+1}: "))

total_sum += num

average = total_sum / count

print(f"Sum of the numbers: {total_sum}")

print(f"Average of the numbers: {average}")

3c. define the following terms in python

Answer:

i. String: In Python, a string is a sequence of characters enclosed within either single


quotes (') or double quotes ("). Strings are immutable, meaning they cannot be changed
after they are created. Python provides a rich set of operations and methods to
manipulate strings, such as concatenation, slicing, and formatting.
ii. Variable: A variable in Python is a named storage location used to store data values.
Variables allow programmers to manipulate data dynamically during program
execution.
iii. Identifiers: Identifiers in Python are names used to identify variables, functions,
classes, modules, or any other objects in a program
QUESTION FOUR

4a. list and explain five of the supported data types in python, with examples

Answer:

1. Integer (int): Integers represent whole numbers, both positive and negative, without any
decimal point. Examples are 1,2,3,4,5.
2. Float (float): Floats represent real numbers with a decimal point. They can represent
fractional values. Examples are 2.3, 4.01.
3. String (str): Strings represent sequences of characters enclosed within single quotes (') or
double quotes ("). Strings are immutable in Python. Examples are “lola”, “hello”
4. Boolean (bool): Booleans represent the truth values True and False, which are used in
logical expressions and conditional statements.
5. List (list): Lists are ordered collections of items, which can be of mixed data types. Lists
are mutable, meaning their elements can be changed after creation.

4b. Define the following under object oriented programming:

Answer:

i. Inheritance: Inheritance is a mechanism in object-oriented programming that allows


a new class (subclass or derived class) to inherit attributes and methods from an existing
class (superclass or base class).
ii. Polymorphism: Polymorphism is the ability of different objects to respond to the same
message or method call in different ways.
iii. Encapsulation: Encapsulation is the bundling of data (attributes) and methods
(functions) that operate on the data into a single unit called a class.
iv. Abstraction: Abstraction is the process of hiding the complex implementation details
and showing only the essential features of an object or system.

4c. List five of the control structures and loops, and write on any two with relevant example

Answer:

1. Conditional Statements:
 if, elif, else: Used to perform different actions based on different conditions.
2. Loops:
 for loop: Used to iterate over a sequence (e.g., list, tuple, string) or other iterable
objects.
 while loop: Used to repeatedly execute a block of code as long as a specified condition
is true.
 break statement: Used to exit the loop prematurely.
 continue statement: Used to skip the rest of the code inside a loop for the current
iteration and continue to the next iteration.

QUESTION FIVE

5a. List the four types of inheritance and write short note on each of them

Answer:

1. Single Inheritance: Single inheritance is the simplest form of inheritance, where a


subclass inherits from only one superclass. It forms a single chain of classes.
2. Multiple Inheritance: Multiple inheritance occurs when a subclass inherits from multiple
superclasses. This allows the subclass to inherit attributes and methods from multiple
parent classes.
3. Multilevel Inheritance: Multilevel inheritance occurs when a subclass inherits from a
superclass, and then another subclass inherits from the first subclass, forming a chain of
inheritance.
4. Hierarchical Inheritance: Hierarchical inheritance occurs when multiple subclasses
inherit from the same superclass. Each subclass has its own set of additional attributes and
methods while sharing common attributes and methods from the superclass.
5b. State the basic differences between the “else” and “elif” statements in python program

Answer:

ELSE Statement:

 Purpose: The else statement is used to define a block of code that executes when the if
condition evaluates to False.
 Usage: The else statement comes after the if block and before any elif blocks (if present).
It does not take any condition, as it is the default block to execute when the preceding if
condition is not satisfied.
 Execution: The else block is executed only if none of the preceding if or elif conditions
evaluate to True.

ELIF Statement:

 Purpose: The elif statement is short for "else if" and is used to define additional conditions
to check after the initial if condition. It allows for the evaluation of multiple conditions in
sequence.
 Usage: The elif statement comes after the initial if statement and before the optional else
statement. It takes a condition that is evaluated only if the preceding if condition is not
satisfied.
 Execution: If the preceding if condition is not satisfied, the elif condition is evaluated. If
the elif condition evaluates to True, the corresponding block of code is executed. If the elif
condition is not satisfied, the next elif (if any) is evaluated, and so on.

5c. list 5 of the benefit of python for database programming

Answer:

1. Ease of Use.
2. Broad Database Support.
3. Integration Capabilities.
4. Abundance of Libraries and Tools.
5. Cross-Platform Compatibility.

You might also like