Python Chapter 2
Python Chapter 2
Answer:
Membership operators in Python, namely 'in' and 'not in', are crucial for checking the existence of an element in sequences like strings,
tuples, lists, or dictionaries. These operators streamline the process of searching within a sequence.
1. **'in' Operator:**
- Returns True if the specified value is found in the sequence (list, string, tuple, etc.).
- Returns False if the item is not present in the sequence.
3. **Additional Point:**
- Membership operators significantly reduce the effort required for element searches in lists or sequences.
Example:
x = "Hello World"
print('H' in x) # True
x = "Hello World"
print("Hello" not in x) # False
2. How to use short- hand if-else statement in python. Explain with example.
Answer:
Example 1 (2 marks):
Shows the flow of control in the program, indicating the decision-making process for both examples.
[Input] --> [Decision: num >= 0] --> [Output: Absolute value]
[Input] --> [Decision: num_check % 2 == 0] --> [Output: Even or Odd]
Answer:
Is
Is not
4. Explain two membership and two logical operators in python with appropriate examples
Answer:
1. **Membership Operators:**
- *In Operator:*
- Checks if a value exists in a sequence.
- Example:
```python
x = [1, 2, 3]
result = 2 in x
# Output: True
```
- *Not In Operator:*
- Checks if a value does not exist in a sequence.
- Example:
```python
y = ('apple', 'banana', 'cherry')
result = 'orange' not in y
# Output: True
```
2. **Logical Operators:**
- *AND Operator:*
- Returns True if both conditions are true.
- Example:
```python
a=5
b = 10
result = (a > 0) and (b > 5)
# Output: True
```
- *OR Operator:*
- Returns True if at least one condition is true.
- Example:
```python
c = 15
d = 20
result = (c > 10) or (d < 5)
# Output: True
5. Explaindifferent loops available in python with suitable example. Explain different loops
available in python with suitable example.
Answer:
In Python, there are three main types of loops: "for loop," "while loop," and "nested loop."
1. **For Loop:**
- Syntax: `for variable in iterable:`
- Example:
```python
for i in range(1, 5):
print(i)
```
- Explanation: This loop iterates over a sequence (here, the range from 1 to 5) and executes the block of code for each element.
2. **While Loop:**
- Syntax: `while condition:`
- Example:
```python
count = 0
while count < 3:
print(count)
count += 1
```
- Explanation: The loop continues to execute the block of code as long as the given condition is True.
3. **Nested Loop:**
- Example:
```python
for i in range(1, 3):
for j in range(1, 3):
print(i, j)
```
- Explanation: Nested loops are loops within loops. In this example, the outer loop runs twice, and for each iteration, the inner loop runs
twice.
6. Loop
Answer:
Loop: A loop in programming is a control structure that allows a set of instructions to be repeated until a specific condition is met. It helps
in efficient execution of repetitive tasks.
7. Operator
Answer:
Correctly define operator: An operator in programming is a symbol or keyword that performs operations on operands. It is used to
manipulate data and variables.
9. Control Flow
Answer:
Control Flow in programming refers to the order in which statements are executed. It is determined by control structures like loops and
conditional statements.
10.
11. Write a program to generate students result. Accept mARKS OF FIVE SUBJECT.
Answer:
# Program to generate student result
# Calculate percentage
percentage = calculate_percentage(total_marks)
# Determine grade
grade = determine_grade(percentage)
# Display result
print(f"Total Marks: {total_marks}")
print(f"Percentage: {percentage}%")
print(f"Grade: {grade}")
Answer:
# Program to find factorial of a given number
Answer:
# Program to print multiplication of the given number
14. Write a program to find out whether the input number is perfect number or not.
Answer:
# Program to check whether the input number is a perfect number or not
# Input
input_number = int(input("Enter a number: "))
# Output
if is_perfect_number(input_number):
print(f"{input_number} is a Perfect Number.")
else:
print(f"{input_number} is not a Perfect Number.")
15. Write a program to perform addition subtraction multiplication and division of two
number
Answer:
# Program to perform addition, subtraction, multiplication, and division of two numbers
# Input
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Addition
result_add = add(num1, num2)
print(f"Addition: {num1} + {num2} = {result_add}")
# Subtraction
result_sub = subtract(num1, num2)
print(f"Subtraction: {num1} - {num2} = {result_sub}")
# Multiplication
result_mul = multiply(num1, num2)
print(f"Multiplication: {num1} * {num2} = {result_mul}")
# Division
result_div = divide(num1, num2)
print(f"Division: {num1} / {num2} = {result_div}")
Answer:
# Program to check if a string is a palindrome
def is_palindrome(s):
# Convert the string to lowercase for case-insensitive comparison
s = s.lower()
# Input a string
user_input = input("Enter a string: ")
# Check if it is a palindrome
if is_palindrome(user_input):
print("The entered string is a palindrome.")
else:
print("The entered string is not a palindrome.")
Answer:
# Program to check whether a number is a palindrome or not
Answer:
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def get_prime_numbers(lst):
prime_numbers = [num for num in lst if is_prime(num)]
return prime_numbers
# Example:
numbers_list = [2, 5, 8, 11, 13, 16, 19, 23]
result = get_prime_numbers(numbers_list)
print("Prime Numbers:", result)