Python | PDF | Division (Mathematics) | Boolean Data Type
0% found this document useful (0 votes)
13 views27 pages

Python

python 5 mark

Uploaded by

altair071846
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views27 pages

Python

python 5 mark

Uploaded by

altair071846
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

5 Mark

Explain python data types.


1. Integer (int)
Represents whole numbers, both positive and negative, without any decimal point.
Example
num = 10

Floating Point (float)


Represents numbers with a decimal point. It is used for more precise values that require
fractional parts.
Example
pi = 3.14159
3. String (str)
Represents sequences of characters enclosed in single quotes (') or double quotes ("). Strings
are used for textual data.
Example
message = "Hello, World!"
4. Boolean (bool)
Represents one of two values: True or False. Boolean values are often used in conditional
statements.
Example
is_active = True
is_approved = False
5. List (list)
An ordered, mutable (changeable) collection of items. Lists can contain elements of different
types.
Example
numbers = [1, 2, 3, 4, 5]
6. Tuple (tuple)
An ordered, immutable (unchangeable) collection of items. Like lists, tuples can contain
elements of different types.
Example
person = ("Alice", 30, "Engineer")
7. Set (set)
An unordered collection of unique items. Sets are useful when you need to store multiple
items without duplicates.
Example
fruits = {"apple", "banana", "cherry"}
8. Dictionary (dict)
A collection of key-value pairs. Each key must be unique, and it maps to a corresponding value.
Dictionaries are mutable.
Example
student = {
"name": "John",
"age": 21,
"courses": ["Math", "Science"]
}
9. None (NoneType)
Represents the absence of a value or a null value. It is commonly used to signify that a variable
has no value assigned.
Example
result = None

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

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

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)

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


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

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

Operator Symbol Function Example


Addition + Adds two operands. 3 + 2 returns 5
Subtraction - Subtracts the second operand 3 - 2 returns 1
from the first.
Multiplication * Multiplies two operands. 3*2 returns 6
Division / Divides the first operand by 3/ 2 returns 1.5
the second (float division).
Floor Division // Divides and returns the largest 3 // 2 returns 1
integer less than or equal to
the quotient.
Modulus % Returns the remainder of the 3% 2 returns 1
division.
* Raises the first operand to the 32 returns 9
Exponentiation power of the second operand.

Comparison or relational operator

Operator Symbol Function Example

Equal == Checks if two operands are 3 == 3 returns True


equal.
Not Equal != Checks if two operands are 3 != 3 returns True
not equal.
Greater Than > Checks if the first operand is 3 > 2 returns True
greater than the second.
Less Than < Checks if the first operand is 3 < 2 returns False
less than the second.
Greater Than or >= Checks if the first operand is 3 >= 3 returns True
Equal greater than or equal to the
second.
Less Than or <= Checks if the first operand is 3 <= 2 returns False
Equal less than or equal to the
second.

Logical

Operator Symbol Function Example

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

Operator Symbol Function Example

Bitwise & Performs a bitwise AND operation. 3 & 2 returns 2


AND
Bitwise | Performs a bitwise OR operation. 5
OR
Bitwise ^ Performs a bitwise XOR operation. 3^ 2 returns 1
XOR
Bitwise ~ Inverts all the bits of the operand. ~3 returns -4
NOT
Left Shift << Shifts the bits of the first operand left by the 3 << 1 returns 6
number of positions specified by the second
operand.
Right >> Shifts the bits of the first operand right by 3>> 1 returns 1
Shift the number of positions specified by the
second operand.
Assignment

Operator Symbol Function Example

Assignment = Assigns the right x = 5 assigns 5 to x


operand's value to the left
operand.
Add and += Adds right operand to the x += 3 (if x=2, then x
Assign left operand and assigns becomes 5)
the result.
Subtract and -= Subtracts right operand x -= 3 (if x=5, then x becomes
Assign from the left operand and 2)
assigns the result.
Multiply and = Multiplies right operand x = 3 (if x=2, then x becomes
Assign with the left operand and 6)
assigns the result.
Divide and /= Divides the left operand x /= 2 (if x=6, then x
Assign by the right operand and becomes 3.0)
assigns the result.
Identity

Operator Symbol Function Example

Is is Checks if two operands x is y returns True


refer to the same if x and y are the same
object. object.
Is Not is not Checks if two operands x is not y returns True
do not refer to the if x and y are different
same object. objects.

Membership

Operator Symbol Function Example

In in Checks if a value exists in a 3 in [1, 2, 3] returns


sequence (like a list or tuple). True
Not In not in Checks if a value does not 4 not in [1, 2, 3]
exist in a sequence. returns True
Implementation of Exception Handling
Exception handling in Python is a way to manage runtime errors in a program. It helps ensure
that the program continues to run or fails gracefully when encountering errors.
Key components of exception handling:
try block:
• Contains code that might raise an exception.
• If an exception occurs, the control is passed to the corresponding except block.
Example
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid integer.")

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.

2. Catching multiple exceptions


• You can catch multiple types of exceptions in different except blocks. Each block handles a
specific error type.
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!")
3.else block
• The else block runs if no exceptions are raised in the try block. It’s used to run code that
should execute only when the try block is successful.
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 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.")

5. Raising an exception manually with raise


• You can manually raise an exception using the raise keyword if you want to trigger an
error under specific conditions.
Example
try:
num = int(input("Enter a positive number: "))
if num < 0:
raise ValueError("Negative numbers are not allowed!")
print(num)
except ValueError as e:
print(e)

• 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]

input_string = input("Enter a string: ")


if is_palindrome(input_string):
print("Palindrome")
else:
print("Not a palindrome")
Output
Enter a String: Malayalam
Palindrome
/////////////////////////////////////////////////////////////////////////////////////////////////
Recursion Function
Recursion in Python is a programming technique where a function calls itself to solve a
problem. Recursion is especially useful for problems that can be broken down into smaller,
similar subproblems.
Structure of a Recursive Function:
A typical recursive function has:
• A base case that stops the recursion.
• A recursive case that breaks the problem down and calls the function itself.
characteristics of recursive functions:
1. Stack Memory:
o Each time a recursive function calls itself, Python keeps track of it in memory.
o Once the base case is reached, the saved states are removed, and results are
returned.
2. Depth of Recursion:
o There is a limit to how many times a function can call itself.
o If the function calls itself too many times, Python will stop and give an error.
3. Time Complexity:
o Recursive functions can be slow because they sometimes repeat the same work
many times, making them inefficient for large problems.
Example 1:
def factorial(n):
if n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case

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)

1. Compile-Time Polymorphism (Method Overloading)


Method Overloading allows a class to have multiple methods with the same name but
different parameter lists (different types or numbers of parameters). Python does not support
method overloading in the traditional sense, but you can achieve similar functionality using
default arguments or variable-length arguments.
Example
class MathOperations:
def add(self, a, b, c=0):
return a + b + c

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 COMPUTER HARDWARE ?


• Computer hardware refers to the physical components of a computer system that are
tangible and can be touched.
It include
• central processing unit (CPU),
• memory (RAM),
• storage devices (hard drives and SSDs),
• motherboards,
• power supplies,
• peripheral devices like keyboards, mice, and monitors.

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.

limits of computational problems


The limits of computational problems refer to what can and cannot be efficiently solved by
computers. Key points include:
1. Complexity: Some problems take too long to solve and are very difficult (like NP-hard
problems).
2. Decidability: Some problems can't be solved by any algorithm, meaning there's no way
to determine a solution for all cases (e.g., the Halting Problem).
3. Resources: Limits on memory and processing power can make it hard to solve complex
problems.
4. Approximation: For many tough problems, finding an exact solution isn't practical, so we
use approximation algorithms to get close enough solutions quickly.

You might also like