Assignment 1
Assignment 1
Fall 2023
Programming Fundamentals (CS-116T)
Assignment # 1
Q1. Discuss how programming errors can be classified into three distinct types: syntax errors, runtime
…...errors, and logic errors, and explain the key characteristics of each. Provide a Python code snippet
…...that demonstrates each of these error types.
Q2. Rewrite the following Python code to convert it into the preferred format for handling multiple
……alternatives.
# Compute BMI
weightInKilograms = weight * KILOGRAMS_PER_POUND
heightInMeters = height * METERS_PER_INCH
bmi = weightInKilograms / (heightInMeters * heightInMeters)
# Display result
print("BMI is", format(bmi, ".2f"))
Q3. Identify and list some common built-in Python functions that are frequently used within for loop
…...scenarios for data processing and manipulation.
Page | 1
Name: Muhammad Izhaan Humayun Roll No: 021
ANSWERS
ANS (1)
1. SYNTAX ERROR:
In Python Syntax Error occurs when the interpreter encounters invalid syntax in code. When
Python code is executed, the interpreter parses it to convert it into bytecode. If the interpreter
finds any invalid syntax during parsing stage, a Syntax Error is thrown.
Example:
print(‘example of Syntax Error.)
This code will not be executed and give syntax error because I have forgotten the quotation mark
before closing the bracket.
2. RUNTIME ERROR:
A runtime error is a type of error that occurs during program execution. The Python
interpreter executes a script if it is syntactically correct. However, if it encounters an issue at
runtime, which is not detected when the script is parsed, script execution may halt
unexpectedly.
Example:
var1= input('enter any number: ')
var2= int(input('enter any number: '))
a= var1 + var2
print(a)
This code will be executed without error. But when the user inputs string value instead of integer, it
will give the type error, which means runtime error.
3. LOGICAL ERROR:
A logical error occurs in Python when the code runs without any syntax or runtime errors but
produces incorrect results due to flawed logic in the code. These type of errors are often
caused by incorrect assumptions, an incomplete understanding of the problem, or the
incorrect use of algorithms or formulas.
Example:
x = float(input(‘enter any number: ’))
y = float(input(‘enter any number: ’))
z=x+y/2
print(‘The average of two numbers is: ’, z)
The example above should calculate the average of the two numbers the user enters. But, because of
the order of operations in arithmetic (the division is evaluated before addition) the program will not
give the correct answer.
Page | 2
Name: Muhammad Izhaan Humayun Roll No: 021
ANS (2)
CODE:
def calculate_bmi(weight, height):
KILOGRAMS_PER_POUND = 0.45359237 # Constant
METERS_PER_INCH = 0.0254 # Constant
return bmi
def interpret_bmi(bmi):
if bmi < 18.5:
return "Underweight"
elif bmi < 25:
return "Normal"
elif bmi < 30:
return "Overweight"
else:
return "Obese"
def main():
weight = eval(input("Enter weight in pounds: "))
height = eval(input("Enter height in inches: "))
# Display result
print("BMI is", format(bmi, ".2f"))
# Interpret BMI
category = interpret_bmi(bmi)
print(category)
if __name__ == "__main__":
main()
Page | 3
Name: Muhammad Izhaan Humayun Roll No: 021
In this code,
I have separated the code into functions for calculating BMI and interpreting BMI, improving
modularity.
I have used descriptive variable names following the snake_case convention.
I have removed unnecessary indentation to make the code cleaner.
I have added a ‘main’ function to enclose the main logic of the program.
I have checked if the script is being run directly using ‘if __name__==”__main__”: ’ to prevent
execution if the script is imported elsewhere.
I have replaced nested ‘if-else’ statements with ‘elif’ for better readability.
ANS (3)
Python provides a rich set of built-in functions that are commonly used within for loops for data
processing and manipulation. Here are some common built-in functions:
1. range(start, stop, step):
Used to generate a sequence of numbers. Commonly used with for loops for iterating over a
range of values.
Example:
for i in range(5):
print(i)
2. enumerate(iterable, start=0):
Yields pairs of indices and elements from an iterable. Useful for obtaining both the index and
the value during iteration.
Example:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
4. len(iterable):
Returns the length of an iterable (number of elements). Useful for determining the size of a
collection.
Example:
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
print(numbers[i])
Page | 4
Name: Muhammad Izhaan Humayun Roll No: 021
5. sum(iterable, start=0):
Calculates the sum of elements in an iterable. Handy for computing cumulative values.
Example:
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
8. filter(function, iterable):
Filters elements of an iterable based on a function. The function should return True or False.
Example:
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))
9. map(function, iterable):
Applies a function to all items in an iterable and returns an iterator with the results.
Example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
print(list(squared_numbers))
These functions, when used within for loops, provide versatile tools for iterating,
filtering, and transforming data in Python.
Page | 5