Python
Python
///////////////////////////////////////////////////////////////////////////////////////
14. Write a python program to find given no. is prime or not.
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Output
Enter the number: 7
7 is a prime number
/////////////////////////////////////////////////////////////////////////////////////////
17. Write a python program to find factorial of a given number..
def factorial(n):
if n == 0:
return 1
else:
return n *factorial(n - 1)
output
Enter a number: 5
The factorial of 5 is: 120
////////////////////////////////////////////////////////////////////////////////
18. Write a python program to find sum of series upto 20
0+1+2+3+......+20
total_sum = 0
for i in range(21):
total_sum += i
print("The sum of the series from 0 to 20 is:", total_sum)
output
The sum of numbers from 0 to 20 is: 210
////////////////////////////////////////////////////////////////////////////////////////////
10 Mark
1.Describe the structure of While and For statement in python with example .
while Loop
The while loop is used to repeatedly execute a block of code as long as a given
condition is true. The condition is evaluated before executing the loop body, so if
the condition is initially False, the loop is not executed at all.
Syntax
While condition :
#code block
condition: A boolean expression that is checked before each iteration. If True, the
loop body is executed; if False, the loop terminates.
Code block: The indented statements that will be executed if the condition is True.
Example:
i=1
while i <= 5:
print(i)
i += 1
output
1
2
3
4
5
for Loop
The for loop is used to iterate over a sequence and execute the block of code for
each item in the sequence.
for variable in sequence:
# Code block to execute
• variable: A variable that takes the value of each item in the sequence during
each iteration.
• sequence: A collection or range of items (e.g., list, tuple, string, range) that
the loop will iterate over.
• Code block: The indented statements to execute during each iteration.
Example 1:
for letter in "Python":
print(letter)
output:
P
y
t
h
o
n
Example 2:
for i in range(1, 6):
print(i)
output
1
2
3
4
5
Example 3:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
output:
apple
banana
cherry
////////////////////////////////////////////////////////////////////////////////////////////////
Discuss in detail about conditional statement in python
Conditional statements allow a program to make decisions and execute certain blocks of code
based on specific conditions.
Conditional statement are
• If Statement
• If else Statement
• elif Statement
• Nested if Statements
if Statement
The if statement is used to test a condition. If the condition evaluates to True, the block of
code is executed. If the condition evaluates to False, the code is skipped.
Syntax
if condition:
# Code block to execute if the condition is true
Example
age = 18
if age >= 18:
print("You are eligible to vote.")
output
You are eligible to vote.
If else Statement
The else statement is used along with if. It provides an alternative block of code that will be
executed if the if condition is False.
Syntax
if condition:
# Code block to execute if the condition is true
else:
# Code block to execute if the condition is false
Example
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
output
You are not eligible to vote.
Elif Statement
It is used when you want to check multiple conditions one after the other. If the first if
condition is false, the elif statement is checked. If the elif condition is true, its block of code is
executed. If none of the conditions are true, an optional else statement can be used as a
fallback.
Syntax
if condition1:
# Code block if condition1 is true
elif condition2:
# Code block if condition2 is true
else:
# Code block if all conditions are false
Example
marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70 :
print("Grade: B")
elif marks >= 60 :
print("Grade: C")
else:
print("Grade: D")
Output:
Grade:A+
Nested if Statement
A nested if statement in Python is when you place one if statement inside another if
statement. This allows you to check multiple conditions in a more specific way, where one
condition depends on another.
Syntax
if condition1:
if condition2:
# Code block if both condition1 and condition2 are true
else:
# Code block if condition1 is true but condition2 is false
else:
# Code block if condition1 is false
Example
age = 20
citizen = True
if age >= 18:
if citizen:
print("You are eligible to vote.")
else:
print("You are not a citizen, so you cannot vote.")
else:
print("You are not old enough to vote.")
output
You are eligible to vote.
////////////////////////////////////////////////////////////////////////////////////////////////
Write a python program to find Result and Grade of a student.
S1=int(input(“Enter the mark in subject 1 : ”))
S2=int(input(“Enter the mark in subject 2 : ”))
S3=int(input(“Enter the mark in subject 3 : ”))
S4=int(input(“Enter the mark in subject 4 : ”))
S5=int(input(“Enter the mark in subject 5 : ”))
total=S1+S2+S3+S4+S5
p=(total/500)100
print("--- Student Result ---")
print("Percentage: ",p)
if p >= 90:
print("Grade: A+")
elif p >= 80:
print("Grade: A")
elif p >= 70:
print("Grade: B")
elif p >= 60:
print("Grade: C")
elif p >= 50:
print("Grade: D")
else:
print("Grade: F")
Output
Enter marks for subject 1: 85
Enter marks for subject 2: 78
Enter marks for subject 3: 92
Enter marks for subject 4: 88
Enter marks for subject 5: 76
--- Student Result ---
Percentage: 83.8%
Grade: A
//////////////////////////////////////////////////////////////////////////////////////////////////
Arithmetic
Logical
Logical AND and Returns True if both operands True and False returns False
are true.
Logical OR or Returns True if at least one of True or False returns True
the operands is true.
Logical NOT not Returns True if the operand is not True returns False
false.
Bitwise
Membership
the user is asked to input a number. If they enter something other than an integer the
ValueError exception is raised, and the message inside the except block is printed.
finally block
• The finally block always executes after try, except, and else blocks, regardless of whether
an exception was raised or not. It is typically used for cleanup tasks like closing files or
releasing resources.
Example
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}")
finally:
print("Execution complete.")
• If the user enters a negative number, the check_positive function raises a ValueError,
which is caught and printed by the except block.
///////////////////////////////////////////////////////////////////////////////////////////////
Program to check the given string palindrome or not
def is_palindrome(string):
return string == string[::-1]
print(factorial(5))
Output
120
///////////////////////////////////////////////////////////////////////////////////////////////////
explain in detail about list,string and dictionary
List in Python
• A list is a mutable, ordered collection of elements that can store different types of data.
Lists support indexing, allowing you to access elements by their position.
List Methods:
• append(item): Adds an item to the end of the list.
• insert(index, item): Inserts an item at a specified position.
• remove(item): Removes the first occurrence of the item.
• pop(index): Removes and returns an element by index. If no index is specified, it
removes the last element.
• sort(): Sorts the list in ascending order.
• reverse(): Reverses the order of the list.
Creating a list
fruits = ["apple", "banana", "cherry"]
Accessing elements
print(fruits[0])
Output:
apple
Modifying elements
fruits[1] = "blueberry"
print(fruits)
Output:
['apple', 'blueberry', 'cherry']
Adding elements
fruits.append("orange")
print(fruits)
Output:
['apple', 'blueberry', 'cherry', 'orange']
Removing elements
fruits.remove("blueberry")
print(fruits)
Output:
['apple', 'cherry', 'orange']
List slicing
print(fruits[1:3])
Output:
['cherry', 'orange']
List length
print(len(fruits))
Output:
3
2. String in Python
A string is an immutable sequence of characters. Strings are widely used to handle text-based
data in Python.
Key String Methods:
• replace(old, new): Replaces occurrences of a substring with another.
• split(delimiter): Splits the string into a list of substrings based on the delimiter.
• join(iterable): Joins elements of an iterable (e.g., list) into a string.
• find(substring): Returns the index of the first occurrence of the substring.
• upper(), lower(): Converts the string to uppercase or lowercase.
Example
Creating a string
message = "Hello, World!"
Accessing characters
print(message[0])
Output: H
String slicing
print(message[7:12])
Output: World
Concatenation
greeting = "Hello" + " " + "Python"
print(greeting)
Output: Hello Python
Length of string
print(len(message))
Output: 13
Replacing text
new_message = message.replace("World", "Python")
print(new_message)
Output: Hello, Python!
Splitting a string into a list
words = message.split(", ")
print(words)
Output:
['Hello', 'World!']
Upper and lower case
print(message.upper())
Output:
HELLO, WORLD!
print(message.lower())
Output:
hello, world!
Dictionary in Python
• A dictionary is a collection of key-value pairs. It is mutable, meaning you can change the
values after creating it, and it is unordered
Dictionary Methods:
• items(): Returns a view object of the dictionary’s key-value pairs.
• keys(): Returns a view object of the dictionary’s keys.
• values(): Returns a view object of the dictionary’s values.
• get(key): Returns the value for the given key, or None if the key does not exist.
• pop(key): Removes and returns the value for the given key.
Creating a dictionary
student = { "name": "John","age": 21,"major": "Computer Science"}
Accessing values by key
print(student["name"])
Output:
John
Modifying values
student["age"] = 22
print(student)
Output:
{'name': 'John', 'age': 22, 'major': 'Computer Science'}
Adding new key-value pair
student["GPA"] = 3.8
print(student)
Output:
{'name': 'John', 'age': 22, 'major': 'Computer Science', 'GPA': 3.8}
Removing a key-value pair
del student["major"]
print(student)
Output:
{'name': 'John', 'age': 22, 'GPA': 3.8}
Dictionary length
print(len(student))
Output:
3
///////////////////////////////////////////////////////////////////////////////////////////////////
explain in detail about polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows
objects of different classes to be treated as objects of a common superclass.
The term itself means "many shapes" and refers to the ability of different classes to be treated
as instances of the same class through a shared interface.
Types of Polymorphism
1. Compile-Time Polymorphism (Method Overloading)
2. Run-Time Polymorphism (Method Overriding)
math_ops = MathOperations()
print(“ Calling add with two parameters :”)
print(math_ops.add(5, 10))
print(“Calling add with three parameters”)
print(math_ops.add(5, 10, 15))
Output
Calling add with two parameters :
15
Calling add with three parameters :
30
Run-Time Polymorphism (Method Overriding)
Method Overriding occurs when a subclass provides a specific implementation of a method
that is already defined in its superclass. The method in the subclass has the same name, return
type, and parameters as the method in the superclass. This allows the subclass to customize or
extend the behavior of the base class method.
Example
class Animal:
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
def animal_sound(animal):
print(animal.speak())
dog = Dog()
cat = Cat()
animal_sound(dog)
animal_sound(cat)
Output:
Woof
Meow
2 MARK
DEFINE COMPUTATIONAL PROBLEM?
• A computational problem is a question or task that requires a well-defined
computational process to find a solution. It typically involves inputs, outputs, and a
method or algorithm to transform the inputs into the desired outputs
Define Function ?
• A function is a reusable block of code designed to perform a specific task or calculation.
It takes input values, known as parameters or arguments, processes them, and may
return an output value.
• Functions help to organize code, promote reusability, and improve readability by
allowing complex operations to be encapsulated within a single, callable unit.
define the use of infinite loops ?
Infinite loops are loops that run forever because they don't have a condition to stop. They are
useful for:
1. Continuous Processes: Keeping servers or apps running to handle requests.
2. User Interaction: Asking users for input until they choose to exit.
3. Real-Time Systems: Continuously monitoring sensors or conditions.
define boolean flag with example?
A boolean flag is a variable that can hold one of two values: true or false. It is commonly used
in programming to indicate the state or condition of a certain operation or process.
example
light_on = False
def toggle_light():
global light_on
light_on = not light_on
toggle_light()
if light_on:
print("The light is on.")
else:
print("The light is off.")
Define Identifier
In Python, an identifier is a name given to a variable, function, class, module, or other object.
Characteristics of Identifiers:
1. Unique: Each identifier must be distinct.
2. Case-sensitive: myVar and MyVar are different.
3. Alphanumeric: Contains letters (a-z, A-Z), digits (0-9), and underscores (_).
4. No special characters: Except underscore (_).
5. No keywords: Cannot be a reserved Python keyword.