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

Assignment 1

The document is a programming assignment that includes three questions. It provides information about the course, learning outcomes, and asks students to write code to demonstrate different types of errors, rewrite code to handle multiple alternatives, and identify common Python functions used in for loops.

Uploaded by

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

Assignment 1

The document is a programming assignment that includes three questions. It provides information about the course, learning outcomes, and asks students to write code to demonstrate different types of errors, rewrite code to handle multiple alternatives, and identify common Python functions used in for loops.

Uploaded by

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

Name: Muhammad Izhaan Humayun Roll No: 021

SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY


COMPUTER SCIENCE & INFORMATION TECHNOLOGY DEPARTMENT

Fall 2023
Programming Fundamentals (CS-116T)
Assignment # 1

Semester: 1st Batch: 2023F


Announced Date: 06-11-23 Due Date: 13-11-23
Total Marks: 30

CLO # Course Learning Outcomes PLO Mapping Bloom’s Taxonomy


(CLOs)
Describe basic problem-solving PLO_2
C2
CLO 1 steps and logic constructs. (Knowledge for solving
(Understanding)
Computing Problem)

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.

# Prompt the user to enter weight in pounds


weight = eval(input("Enter weight in pounds: "))

# Prompt the user to enter height in inches


height = eval(input("Enter height in inches: "))

KILOGRAMS_PER_POUND = 0.45359237 # Constant


METERS_PER_INCH = 0.0254 # Constant

# Compute BMI
weightInKilograms = weight * KILOGRAMS_PER_POUND
heightInMeters = height * METERS_PER_INCH
bmi = weightInKilograms / (heightInMeters * heightInMeters)

# Display result
print("BMI is", format(bmi, ".2f"))

if bmi < 18.5:


print("Underweight")
else: if bmi < 25:
print("Normal") else:
if bmi < 30:
print("Overweight")
else:
print("Obese")

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

weight_in_kilograms = weight * KILOGRAMS_PER_POUND


height_in_meters = height * METERS_PER_INCH

bmi = weight_in_kilograms / (height_in_meters * height_in_meters)

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: "))

bmi = calculate_bmi(weight, height)

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

3. zip(iterable1, iterable2, ...):


Combines multiple iterables element-wise. Useful for iterating over multiple sequences
simultaneously.
Example:
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)

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)

6. min(iterable) and max(iterable):


Return the minimum and maximum values in an iterable, respectively.
Example:
temperatures = [22, 18, 25, 30, 15]
min_temp = min(temperatures)
max_temp = max(temperatures)
print(min_temp, max_temp)

7. sorted(iterable, key=None, reverse=False):


Returns a new sorted list from the elements of an iterable. The key parameter allows custom
sorting.
Example:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

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

You might also like