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

Python Chapter 2

This document discusses various Python programming concepts like operators, control flow, loops, functions and provides examples of programs to check palindromes, find factorials, calculate student results and more. Membership, logical and identity operators are explained along with for, while and nested loops. Shorthand if-else statements and functions are demonstrated with examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
9 views8 pages

Python Chapter 2

This document discusses various Python programming concepts like operators, control flow, loops, functions and provides examples of programs to check palindromes, find factorials, calculate student results and more. Membership, logical and identity operators are explained along with for, while and nested loops. Shorthand if-else statements and functions are demonstrated with examples.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 8

Python Chapter 2

1. Explain membership operator and identify operators in Python with example.

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.

2. **'not in' Operator:**


- Returns True if the specified value is not found in the sequence.
- Returns False if the item is 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:

# Using short-hand if-else statement in Python

# Example 1: Absolute value of an input number


num = int(input("Enter an Integer number: "))
result = num if num >= 0 else -num
print("Absolute value of", num, "is:", result)

# Example 2: Checking if a number is even or odd


num_check = int(input("Enter any number: "))
result_str = "even" if num_check % 2 == 0 else "odd"
print("Entered number is", result_str)

# Control Flow Diagram:


# [Input] --> [Decision: num >= 0] --> [Output: Absolute value]
# [Input] --> [Decision: num_check % 2 == 0] --> [Output: Even or Odd]

Example 1 (2 marks):

A user is prompted to enter an integer (num).


The short-hand if-else statement is used to find the absolute value (result) of the entered number.
The result is then printed.
Example 2 (2 marks):

Another user input (num_check) is taken.


The short-hand if-else statement is used to determine if the entered number is even or odd (result_str).
The result is printed.
Control Flow Diagram (1 extra point):

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]

3. List Identity operator

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

# Function to calculate total marks


def calculate_total(marks):
return sum(marks)

# Function to calculate percentage


def calculate_percentage(total):
return (total / 500) * 100

# Function to determine grade


def determine_grade(percentage):
if percentage >= 90:
return 'A'
elif 80 <= percentage < 90:
return 'B'
elif 70 <= percentage < 80:
return 'C'
elif 60 <= percentage < 70:
return 'D'
else:
return 'F'

# Accept marks for five subjects


subject_marks = []
for i in range(5):
marks = int(input(f"Enter marks for Subject {i + 1}: "))
subject_marks.append(marks)

# Calculate total marks


total_marks = calculate_total(subject_marks)

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

12. Write a program to find factorial of given number

Answer:
# Program to find factorial of a given number

# Input: Take the number from the user


num = int(input("Enter a number: "))

# Initialize factorial variable


factorial = 1

# Loop to calculate factorial


for i in range(1, num + 1):
factorial *= i

# Output: Display the factorial of the given number


print(f"The factorial of {num} is: {factorial}")

13. Write a program to print multiplication of the given number.

Answer:
# Program to print multiplication of the given number

# Input: Accept a number from the user


num = int(input("Enter a number: "))

# Processing: Multiplication logic


result = num * 2

# Output: Display the result


print("Multiplication of the given number by 2 is:", result)

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

# Function to find the sum of divisors of a number


def sum_of_divisors(num):
sum_div = 1 # Start with 1 as all numbers are divisible by 1
i=2
while i * i <= num:
if num % i == 0:
sum_div += i
if i != num // i:
sum_div += num // i
i += 1
return sum_div

# Function to check if a number is a perfect number


def is_perfect_number(num):
return num == sum_of_divisors(num)

# 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

# Function to add two numbers


def add(x, y):
return x + y

# Function to subtract two numbers


def subtract(x, y):
return x - y

# Function to multiply two numbers


def multiply(x, y):
return x * y

# Function to divide two numbers


def divide(x, y):
if y != 0:
return x / y
else:
return "Cannot divide by zero"

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

16. Write a program to check whether a string is a palindrome or not.

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

# Remove spaces from the string


s = s.replace(" ", "")
# Compare the original string with its reverse
if s == s[::-1]:
return True
else:
return False

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

17. Write a program to check whether a number is a palindrome or not.

Answer:
# Program to check whether a number is a palindrome or not

# Function to check palindrome


def is_palindrome(num):
original_num = num
reversed_num = 0

# Reverse the number


while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10

# Check if original and reversed numbers are equal


if original_num == reversed_num:
return True
else:
return False

# Input from the user


num = int(input("Enter a number: "))

# Check and display the result


if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")

18. Write a program to return prime number from a list.

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)

You might also like