0% found this document useful (0 votes)
21 views34 pages

Unit 2 Question Bank & Answer

The document explains various ways to take user input in Python, including strings, integers, and floats, and how to handle multiple inputs. It also covers control flow using if, elif, and else statements, while loops, and for loops, along with their applications in decision-making and list manipulations. Additionally, it discusses list methods, tuple properties, and provides examples for discount calculations and conditional statements.

Uploaded by

abithhussain033
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)
21 views34 pages

Unit 2 Question Bank & Answer

The document explains various ways to take user input in Python, including strings, integers, and floats, and how to handle multiple inputs. It also covers control flow using if, elif, and else statements, while loops, and for loops, along with their applications in decision-making and list manipulations. Additionally, it discusses list methods, tuple properties, and provides examples for discount calculations and conditional statements.

Uploaded by

abithhussain033
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/ 34

UNIT 2

1. Explain different ways to take user input in Python. Provide examples


showing how to input integers, floats, and strings, and how to handle
multiple inputs in a single line.

ANSWER:

In Python, there are several ways to take user input depending


on the type of data you want to handle.

1. Taking String Input

The input() function reads a line from the standard input as a


string.

2. Taking Integer Input

You can convert the input string to an integer using int().

3. Taking Float Input

Similarly, use float() to convert the input to a floating-point


number.
You can use the split() method to handle multiple inputs.

a. Multiple String Inputs

b. Multiple Integer Inputs

c. Mixed Inputs

2. Write a Python program that demonstrates the use of if, elif, and else
statements. Explain how each part works and how conditions are
evaluated in a decision-making process.

ANSWER:
Explanation of Components

1. if Statement:

o The if block checks the first condition.

o If the condition is True, the corresponding block of


code is executed, and the program skips all
subsequent elif and else blocks.

o Example: If age = -1, the if age < 0: condition


evaluates to True, and the program prints "Age cannot
be negative."

2. elif Statements:

o The elif blocks provide additional conditions.

o Each condition is evaluated sequentially, only if the


previous conditions were False.

o Example: If age = 15, the first if condition is


False, but the elif age < 20: condition is True, so
"You are a teenager." is printed.

3. else Statement:
o The else block is executed if none of the if or elif
conditions are True.

o Example: If age = 65, all if and elif conditions


fail, so the else block executes, and the program
prints "You are a senior citizen."

Key Points about the Decision-Making Process

1. Sequential Evaluation:

o Conditions are evaluated from top to bottom. The


first True condition stops further checks.

2. Mutually Exclusive Blocks:

o Only one block (if, elif, or else) will execute in a


single run, depending on the conditions.

3. Logical Structure:

o Conditions should be arranged logically to ensure


correct and efficient evaluation.

4. Invalid Input Handling:

o The program accounts for unexpected inputs (like


negative numbers) to handle edge cases.

3. Explain how a while loop works in Python. Write a program that


calculates the sum of natural numbers up to a given limit using a while
loop. Include a discussion on loop control (e.g., break and continue
statements).

ANSWER:

A while loop repeatedly executes a block of code as long as the


specified condition evaluates to True. The condition is checked
before executing the loop body each time. If the condition
becomes False, the loop terminates.
break Statement:

Exits the loop immediately, regardless of the condition.

Key Observations:

1. The break statement:

o The break statement is at the same indentation level


as the if block, so it will execute on the first
iteration of the while loop, regardless of the
condition if a[i] == 'e' or a[i] == 's'.

2. What happens:

o On the first iteration (i = 0), the while loop is


entered, and the break statement immediately exits
the loop, regardless of the value of a[i].
3. Accessing a[i]:

o After exiting the loop, i is still 0, so the program


accesses a[0], which is 'g'.

4. Code after the loop:

o The program increments i by 1 after the print


statement, but this has no effect on the logic as it
is executed outside the loop.

Continue Statement:

Skips the rest of the current iteration and moves to the next
iteration.

4. Discuss lists in Python, including how to create, access, modify, and


delete list items. Write a Python program to demonstrate list operations
like appending, slicing, and sorting.

ANSWER:

A list in Python is an ordered, mutable, and iterable collection


that can store elements of different data types, including
numbers, strings, and even other lists. Lists are one of
Python’s most versatile and widely used data structures.

How to Create a List

Lists can be created by enclosing elements in square brackets


[].

Accessing List Items

You can access list items using their index. Python uses zero-
based indexing.

Modifying List Items

You can modify list items by assigning a new value to a specific


index.
Deleting List Items

You can remove items using the del statement, pop() method, or
remove() method.

Python Program Demonstrating List Operations Slicing , appending


& sorting.
5. Describe the use of for loops in Python. Provide examples showing how
to loop through a range of numbers, through lists, and how to use nested
for loops.

ANSWER:

Python For Loops

● A for loop is used for iterating over a sequence (that is


either a list, a tuple, a dictionary, a set, or a string).

● This is less like the for keyword in other programming


languages, and works more like an iterator method as found in
other object orientated programming languages.

● With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
loop through a range of numbers:

loop through List:


Nested Loops

Nested loops are loops inside loops. They are often used to work
with 2D data structures like matrices or to perform repeated
operations.

6. Describe how a for loop can be used to manipulate items in a list. Write
a Python program that takes a list of numbers and prints only the even
numbers, using a for loop and conditional statements.
ANSWER:

Using a for Loop to Manipulate Items in a List

A for loop can be used to iterate through each item in a list


and apply transformations, filtering, or calculations.

How It Works:

1. Iteration:

o The for loop iterates through each number in the


numbers list.

2. Conditional Check:

o For each number, the condition number % 2 == 0 checks


if the remainder when divided by 2 is 0, indicating
that the number is even.

3. Printing Even Numbers:

o If the condition evaluates to True, the print()


statement outputs the even number.

7. Create a program that helps a store decide if a customer qualifies for a


discount. The customer is eligible if they are either a senior (65+ years) or
have made purchases above $100. Write code to check these conditions
using Boolean expressions, and explain how Boolean logic aids in
decision-making.(hint: using conditional statements).

ANSWER:

Explanation:

1. User Input:

o The program asks the user to input their age and


total purchase amount.

o The input() function is used to gather the customer's


data, which is then converted to the appropriate data
types (int for age, float for the purchase amount).

2. Boolean Expression:

o We use the logical OR operator (or) to combine two


conditions:

▪ age >= 65 checks if the customer is 65 years or


older.

▪ purchase_amount > 100 checks if the total


purchase amount exceeds $100.

o The or operator returns True if either of the


conditions is true. If either the age condition or
the purchase condition is satisfied, the customer
will be eligible for the discount.
3. Conditional Statements:

o The if statement checks if the Boolean expression


(age >= 65 or purchase_amount > 100) is True.

o If the condition is True, the program prints "You


qualify for a discount!".

o If the condition is False, the program prints "You do


not qualify for a discount.".

8. a) "Nick is organizing a book club meeting where members are bringing


their favorite books to discuss. He needs your help to manage the list of
books effectively. Here's what he needs you to do:

Create an empty list called book_list.

John brings ""Wings of Fire"". Add this book to the book_list.

Zia brings ""Pride and Prejudice"". Add this book to the book_list.

Jack brings ""1921"". Add this book to the book_list.

Sort the book_list in alphabetical order.

Remove the book ""1921"" from the book_list.

Print the updated book_list.

Count how many times ""Wings of Fire"" appears in the book_list.

Print the total number of books in the book_list."


b) Explain what a list is in Python and describe its key features with
examples.

ANSWER:
Explanation of the Code:

1. Create an Empty List:

o We start by creating an empty list book_list to store


the books brought by the members.

2. Add Books to the List:

o Using the append() method, we add books one by one as


the members bring their books:

▪ John brings "Wings of Fire".

▪ Zia brings "Pride and Prejudice".

▪ Jack brings "1921".

3. Sort the List Alphabetically:

o We use the sort() method to arrange the books in


alphabetical order.

4. Remove the Book "1921":


o The remove() method is used to remove "1921" from the
list.

5. Print the Updated Book List:

o The updated list is printed after sorting and


removing the book.

6. Count Occurrences of "Wings of Fire":

o The count() method checks how many times "Wings of


Fire" appears in the list.

7. Total Number of Books in the List:

o The len() function is used to calculate the total


number of books remaining in the list.

A list in Python is a collection of ordered, mutable


(changeable) items, which can be of any data type. Lists are one
of the most versatile and frequently used data structures in
Python.

Key Features of Lists:

1. Ordered:

o Lists maintain the order of elements, meaning the


elements will be in the same sequence in which they
were added.

2. Mutable:

o You can modify the elements of a list after it has


been created (e.g., adding, removing, or changing
items).

3. Indexed:

o Lists are indexed, starting from index 0, which means


you can access elements using an index number.
4. Allows Duplicate Values:

o Lists can contain multiple instances of the same


value.

5. Heterogeneous:

o Lists can store items of different data types (e.g.,


integers, strings, floats, other lists).

Create a List:

Accessing List;

9. i)Define the any Six list method with the example?(6)

ii)How do you create an empty list in Python?(4)"

ANSWER:

I)

1. append()
Adds an element to the end of the list.

2.insert()

Inserts an element at a specific index in the list.

3. remove()

Removes the first occurrence of a specified element from the


list.

4. pop()

Removes and returns an element at a specified index. If no index


is provided, it removes the last item.
5. sort()

Sorts the elements of the list in ascending order by default.


You can pass the reverse=True argument for descending order.

6. count()

Returns the number of occurrences of a specified element in the


list.

7. clear()
Removes all elements from the list, leaving it empty.

8. index()

Returns the index of the first occurrence of a specified


element.

9. reverse()

Reverses the elements of the list in place.

10. copy()

Returns a shallow copy of the list (a new list with the same
elements).
12. join() (Not a list method, but a string method commonly used with
lists)

Joins elements of a list into a single string, separating them


with a specified delimiter.

ii)

n Python, you can create an empty list in two ways:

1. Using Square Brackets []:

This is the most common and simplest way to create an empty


list.

2. Using the list() Constructor:

You can also use the list() constructor to create an empty list.

10. i)What is the purpose of negative indexing in Python tuples?(5)

ii)How can you concatenate two tuples in Python and Discuss the
immutability property of tuples in Python.(5) "

ANSWER:
I)

Purpose of Negative Indexing in Python Tuples

Negative indexing in Python allows you to access elements from


the end of a tuple (or any sequence, such as a list or string),
rather than from the beginning. This can be useful when you want
to refer to elements starting from the last item, making it
easier to access the last few elements without needing to know
the exact length of the tuple

Examaple:

ii) Concatenating Two Tuples in Python

In Python, you can concatenate two tuples using the + operator.


This operation combines the elements of both tuples into a new
tuple.

Immutability of Tuples in Python


One of the key properties of tuples in Python is that they are
immutable. This means that once a tuple is created, its contents
cannot be changed. You cannot add, remove, or modify elements in
a tuple after it has been defined.

Key Points About Immutability:

1. No Modification of Elements:

2. No Adding or Removing Elements:

11. "Write a Python program that calculates and displays the


discount for a customer based on their total purchase amount.
The discount rules are as follows:

No Discount: If the purchase amount is less than $50.

10% Discount: If the purchase amount is $50 to $99.

15% Discount: If the purchase amount is $100 to $199.

20% Discount: If the purchase amount is $200 or more.

Additionally, your program should handle invalid input by


displaying an error message if the entered amount is not a
positive number."

ANSWER:
Explanation:

1. Input Handling:

o The program takes input from the user and attempts to


convert it to a float. If the input is not a valid
number (like text or symbols), a ValueError is
caught, and an error message is displayed.

2. Discount Calculation:

o The program then uses if, elif, and else to determine


the appropriate discount based on the purchase
amount:
▪ No discount for amounts less than $50.

▪ 10% discount for amounts between $50 and $99.

▪ 15% discount for amounts between $100 and $199.

▪ 20% discount for amounts $200 or more.

3. Error Handling:

o The program checks if the entered amount is a valid


number and if it's positive. If not, it prints an
error message.

12. i. Formulate with an example program to find all the values in the list
that are greater than the specified number

ii. Write a program to find out the square root of two numbers"

ANSWER:

i)

Explanation:

• The function find_values_greater_than() takes two


arguments:

o lst: the list of numbers.

o num: the specified number.


• Inside the function, a list comprehension is used to
iterate over each value in the list and include only those
greater than the specified number.

• The result list contains all the values that meet this
condition, which is returned.

ii)

Explanation:

1. Input: The program asks the user to input two numbers.

2. Calculation: The math.sqrt() function calculates the square


root of each number.

3. Output: The square root of both numbers is printed.

13. Define conditional statements with example.

ANSWER:

Conditional Statements in Python:


Conditional statements in Python allow you to execute specific
blocks of code based on certain conditions. The main types of
conditional statements are:

1. if statement – Executes a block of code if the condition is


true.

2. elif statement – Short for "else if," it checks another


condition if the previous if condition was false.

3. else statement – Executes a block of code if all preceding


conditions were false.

Explanation:

• The program checks the value of age to determine whether


the person is an adult, teenager, or child.

• If age is greater than or equal to 18, the message "You are


an adult." is printed.

• If the first condition is false, the program checks if the


age is 13 or more, printing "You are a teenager."

• If both conditions are false (i.e., the age is less than


13), the else block is executed, printing "You are a
child."
14. Compare while loop & for loop and give example to print numbers
starting from 1 to 100 using both for & while loop.

ANSWER:

Comparison Between while Loop and for Loop:

Feature while Loop for Loop

Repeats a block of code


Iterates over a sequence
Purpose as long as a condition is
(e.g., range, list).
true.

Condition is checked at Iterates through items in a


Condition
the beginning of each predefined range or
Check
iteration. sequence.

When the number of


When the number of
When to iterations is fixed or you
iterations is unknown or
Use need to iterate over a
depends on a condition.
sequence.

May require manual


Automatically iterates
Structure updates of variables
through the sequence.
(e.g., incrementing).

Reading input until valid Iterating over a list of


Examples
input is given. items.

Examples to Print Numbers from 1 to 100 Using Both Loops

Using while Loop:


Using for Loop:

15. a) Define for loop with example. ( 4 marks)

b) Write a program to find factorial of n number using for loop. (6 marks)

ANSWER:

a)

For Loop in Python

A for loop in Python is used to iterate over a sequence (such as


a list, tuple, string, or range) and execute a block of code for
each element in the sequence. It is particularly useful when the
number of iterations is known in advance.

Example:

How It Works:

1. The for loop iterates over the sequence ["apple", "banana",


"cherry"].

2. In each iteration, the fruit variable takes the value of


the next item in the sequence.

3. The loop runs until all items in the sequence have been
processed.
b)

Explanation:

1. Input Handling:

o The program prompts the user to enter a positive


integer n.

o If n is negative, it prints a message saying


factorials are not defined for negative numbers.

2. Special Cases:

o If n is 0 or 1, the factorial is directly set to 1.

3. Using a for Loop:

o The loop iterates from 1 to n (inclusive) using


range(1, n + 1).

o In each iteration, the current value of i is


multiplied with the factorial variable to calculate
the factorial.

16. a) Explain nested if with flow chart. (5 marks)


b) Explain if-elif-else ladder with the help of flow chart & example. (5
Marks)

ANSWER:

a)

Nested if Statement in Python

A nested if statement is an if statement inside another if


statement. It allows you to test multiple conditions
sequentially. If the outer if condition evaluates to True, then
the inner if statement is executed.

Syntax of Nested if:

Flowchart of Nested If:


b)

If-Elif-Else Ladder in Python

The if-elif-else ladder is used when there are multiple


conditions to check sequentially. The program evaluates
conditions one by one from top to bottom and executes the block
of the first condition that evaluates to True. If none of the
conditions are True, the else block is executed.

Syntax:
Example:

You might also like