[go: up one dir, main page]

0% found this document useful (0 votes)
9 views7 pages

Question 1

The document discusses various programming concepts, including differences between traditional programming and machine learning, data conversion types, and error handling in Python. It also covers control structures, data types, and provides examples of Python programs for tasks such as calculating sums, handling user input, and reading CSV files. Additionally, it highlights the distinctions between tuples and lists, as well as the principles of object-oriented programming.

Uploaded by

gracejamu4
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)
9 views7 pages

Question 1

The document discusses various programming concepts, including differences between traditional programming and machine learning, data conversion types, and error handling in Python. It also covers control structures, data types, and provides examples of Python programs for tasks such as calculating sums, handling user input, and reading CSV files. Additionally, it highlights the distinctions between tuples and lists, as well as the principles of object-oriented programming.

Uploaded by

gracejamu4
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
You are on page 1/ 7

Question 1:

a.
i. Differences between traditional programming and machine language:
Traditional Programming: Traditional programming involves writing code that follows
a set of instructions to perform specific tasks.
Real-life Example of Traditional Programming: Consider a simple program that
calculates the average of a list of numbers. In traditional programming, you would write
code that iterates through the list, sums up the numbers, and then divides by the total
count to find the average. The steps to achieve this are explicitly defined in the code, and
the program follows these instructions to compute the result.
Machine Learning in Python: On the other hand, machine learning in Python involves
creating algorithms that allow computers to learn from data and make predictions or
decisions without being explicitly programmed for each task.
Real-life Example of Machine Learning in Python: An example of machine learning
in Python is building a spam email filter. Instead of explicitly programming rules for
identifying spam emails, you can use machine learning algorithms to analyze large sets of
labeled emails (spam or non-spam) and learn patterns that distinguish between the two.
Once trained, the model can predict whether new emails are spam or not based on the
learned patterns.

Machine learning suits undefined traditional programming suits clear rules


problems or complex data, and limited inputs/outputs.

Machine learning can be complex to Traditional programming provides easily


interpret, especially with large datasets understandable and explainable results.

ii. Differences between explicit data conversion and implicit data conversion
Implicit data conversion is the conversion in which a derived class is converted into a
base class eg. Int into a float type. Whereas Explicit conversion is the conversion that
may cause data loss, it also converts base class into derived class
b. Write a python program to find a given number that accepts number from user and shows
whether its an even number or not.
x=int(input("Enter number"))
if x%2 == 0:
print("Even number")
else:
print("Odd number")
c. Consider the names below and consider whether the variable names are valid or not.
i. My Name
It is not valid because it contains space between my and name
ii. 3Name
It is not valid because a variable cannot start with a number.
iii. _Name
It is valid because a variable can start with an underscore character or letter.
d.
i. Give one difference between runtime error and compilation error
compilation errors are related to syntax and occur before the program runs, while runtime
errors occur during program execution due to unexpected conditions or logical mistakes.
ii. Identify the error and correct the line throwing the error
The corrected code has the following changes:
The indentation of the second line has been corrected.
The comparison operator in the if statement has been changed from < to >.
The spelling of result has been corrected in the last line.
iii. Correct the above code to output the largest number
def large(arr):
max_ = arr[0]
for ele in arr:
if(ele > max_):
max_ = ele
return max_

list1 = [1, 4, 5, 2, 6]
result = large(list1)
print(result)
Question 2:
a. Using an example, explain the use of the following in a loop
i. Break
The break statement is used to terminate a loop prematurely. When the break statement
is encountered inside a loop, the loop is immediately terminated and the program
execution continues with the next statement after the loop.
for i in range(1, 11):
if i == 5:
break
print(i)
ii. Continue
The continue statement is used to skip an iteration of a loop. When
the continue statement is encountered inside a loop, the current iteration of the loop is
skipped, and the program execution continues with the next iteration of the loop.
for i in range(1, 11):
if i == 5:
continue
print(i)
b. Briefly describe the following terms as used in programming and give examples where
necessary:
i. Translator
a translator is a computer program that converts the programming instructions written in
human-readable form into machine language codes that computers can understand and
process.
For example, a Python interpreter converts Python code into machine code that the
computer can execute.
ii. Function argument
a function argument is a value that is passed to a function when it is called.
Example
def add_numbers(a, b):
sum = a + b
return sum
In this function, a and b are the arguments that are passed to the function. When the
function is called with two values, the values are assigned to a and b, and the function
returns their sum.

c. Determine the output of the program explaining all the data type conversion happening.
Number1 = 10
Number2 = 5.78
Print(Number1)
Print(Number1 + Number2)
Here’s what’s happening in the program:
Two variables Number1 and Number2 are defined with values 10 and 5.78 respectively.
The value of Number1 is printed using the print() function. Since Number1 is an integer, it will
be printed as 10.
The sum of Number1 and Number2 is printed using the print() function. Since Number1 is an
integer and Number2 is a float, Python will perform an implicit type conversion and
convert Number1 to a float before adding it to Number2. The result of the addition is 15.78,
which is a float. Therefore, it will be printed as 15.78.
d. Write a python program that calculates sum of a list, example given a list [1,5,7,3] output
must be 16
e. State and explain the most suitable data types for the following data
i. “I am a student”
"I am a student" is a string of characters. Therefore, the most suitable data type for
this data is a string.
ii. 204.78
204.78 is a decimal number. Therefore, the most suitable data type for this data is
a floating-point number.
iii. ‘A’
'A' is a single character. Therefore, the most suitable data type for this data is
a character.

Question 3:
a. The following programs are incorrect. State what is wrong with each one, and then write is
correctly.
i. First number = 24
First_number = 24
ii. break = [2,4,8,3]
for i in break:
print(i)
iii. if 4>2:
print("Greater")
else:
print("Less")
if 4>2:
print("Greater")
else:
print("Less")
b. using example explain the try........ except........finally block
The try...except...finally block is a powerful tool for handling errors in Python. It
allows you to test code for errors and handle them gracefully.
# Try to divide two numbers
try:
result = 10 / 0

# If an error occurs, handle it here


except ZeroDivisionError:
print("Cannot divide by zero")

# The finally block is always executed, regardless of whether an error occurs


finally:
print("Done")
c. State and explain the output of the following
a = 13
b = 33
i. print(a>b)
False
ii. print(a<b)
True
iii. print(a==b)
False
iv. print(a!=b)
True
v. print(a>=b)
False
vi. print(a<=b)
True
Question 4:
a. At mcdonalds one can buy chicken nuggets in packages containing 6,9 or 20 pieces. Write a
python function that accepts an integer, num, as an argument and decides whether or not it
is possible to buy num nuggets at mcdonalds. Write also a program the call the function
accepting input from user.
def can_buy_nuggets(num):
if num % 6 == 0:
return True
elif num % 9 == 0:
return True
elif num % 20 == 0:
return True
else:
return False
def main():

# Get the number of nuggets from the user.


num = int(input("How many nuggets would you like to buy? "))

# Check if it is possible to buy that number of nuggets.


can_buy = can_buy_nuggets(num)

# Print the result to the user.


if can_buy:
print("Yes, you can buy {} nuggets at McDonald's.".format(num))
else:
print("No, you cannot buy {} nuggets at McDonald's.".format(num))

if __name__ == "__main__":
main()
b. Provide a python implementation of the function findSide specified below
def findSide():
"""asks the user to enter the area of a rectangle and the length of one side of the Rectangle.
Returns a floating point number that is the length of the adjacent side."""
def findSide():

# Get the area of the rectangle from the user.


area = float(input("Enter the area of the rectangle: "))

# Get the length of one side of the rectangle from the user.
side1 = float(input("Enter the length of one side of the rectangle: "))

# Calculate the length of the adjacent side.


side2 = area / side1

# Return the length of the adjacent side.


return side2
print(side2)
c. With aid of an example, explain what a control structure is
A control structure is a programming construct that allows you to control the flow of your
program. It allows you to decide which statements to execute and when to execute
them. There are three main types of control structures which are sequence, selection
and iteration.
# This is a sequence control structure.
# It executes the statements one after the other.
print("Hello, world!")
print("I am a computer program.")
# This is a selection control structure.
# It chooses between two paths of execution depending on the value of the
variable `age`.
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")

# This is an iteration control structure.


# It repeats the block of code until the variable `count` reaches 10.
count = 0
while count < 10:
print(count)
count += 1
d. Match the following words

High level language Machine code


Low level language break
Translator for
Loop interpreter
Reserved word python
solution

High level language Python


Low level language Machine code
Translator Interpreter
Loop For
Reserved word break
Question 5
a. Write a python program that read a file named myfile.csv to dataframe
import pandas as pd

# Read the CSV file to a DataFrame


df = pd.read_csv("myfile.csv")

# Print the DataFrame


print(df)

b. Write a program to print the first 4 rows of a dataframe


import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
"id": [1, 2, 3, 4, 5],
"name": ["Bob", "Mary", "Joe", "Alice", "Eve"],
"age": [25, 30, 35, 40, 45]
})

# Print the first 4 rows of the DataFrame


print(df.head(4))

c. With an aid of clear examples explain the following


i. Logical operator

ii. Comparison operator


iii. Assignment operator
d. List any 5 supported data types in python

Numeric: Integer, float, complex

String: str

Sequence: list, tuple, range

Mapping: dict

Set: set

e. State and explain 3 differences between tuple and list

. Mutability: Tuples are immutable, while lists are mutable. This means that tuples
cannot be changed once they are created, while lists can be changed.

2. Size: Tuples have a fixed size, while lists have a variable size. This means that
the number of elements in a tuple cannot be changed, while the number of elements
in a list can be changed.

3. Performance: Tuples are generally more performant than lists. This is because
tuples are immutable, so the Python interpreter does not need to worry about
checking if the tuple is being modified before performing any operations on it.

f. Explain OOP programming paradigm

You might also like