91

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

[9:31 AM, 6/15/2024] +91 70788 28486: a) What is exception and how we can

handle an exception?
b) Write type of exception generated in python program with reason.
c) How we open the file in python?
d) What is exception handling? Explain with an example.
e) What is the purpose of flush () method? Explain with suitable examples.
f) Write a program to print Fibonacci series.
g) Write a program to find factorial of a given number.
h) Write a program to convert Celsius to Fahrenheit.
i) Write a program to find whether a given number is Armstrong number or
not f.
j) Write a program to Circulate the value of n variables.
[9:31 AM, 6/15/2024] +91 70788 28486: Sure, here are the answers:

a) An exception is an event that occurs during the execution of a program that


disrupts the normal flow of instructions. In Python, exceptions can be handled
using try-except blocks. By using try-except blocks, you can catch and handle
exceptions gracefully, preventing the program from crashing.

b) Types of exceptions generated in a Python program:


- SyntaxError: Occurs when there is a syntax error in the code.
- TypeError: Occurs when an operation is performed on an object of
inappropriate type.
- NameError: Occurs when a name is not found in the local or global scope.
- ValueError: Occurs when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
- ZeroDivisionError: Occurs when the second operand of a division or modulo
operation is zero.

c) To open a file in Python, you can use the open() function. It takes the filename
as the first argument and the mode as the second argument. Modes include read
('r'), write ('w'), append ('a'), etc.

d) Exception handling is the process of handling exceptions that occur during the
execution of a program. It involves using try-except blocks to catch and handle
exceptions gracefully. Here's an example:
python
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number!")

In this example, if the user enters 0 as input, it will raise a ZeroDivisionError, and if
the user enters a non-integer value, it will raise a ValueError. The try-except
blocks catch these exceptions and handle them appropriately.

e) The flush() method in Python is used to flush the internal buffer of a file. It
ensures that all the buffered data is written to the file. This can be useful when
you want to ensure that data is written to the file immediately. Here's an
example:

python
with open("file.txt", "w") as file:
file.write("Hello")
file.flush() # Flush the buffer to ensure "Hello" is written to the file immediately

f) Program to print Fibonacci series:

python
def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series

n = 10
print("Fibonacci series:")
print(fibonacci(n))

g) Program to find factorial of a given number:

python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

num = 5
print("Factorial of", num, "is:", factorial(num))

h) Program to convert Celsius to Fahrenheit:

python
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32

celsius = 30
print(celsius, "degrees Celsius is equal to", celsius_to_fahrenheit(celsius),
"degrees Fahrenheit")

i) Program to find whether a given number is Armstrong number or not:

python
def is_armstrong(num):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
return num == sum

number = 153
if is_armstrong(number):
print(number, "is an Armstrong number")
else:
print(number, "is not an Armstrong number")

j) Program to circulate the value of n variables:

python
def circulate_values(*args):
return args[-1], *args[:-1]

a, b, c = 1, 2, 3
a, b, c = circulate_values(a, b, c)
print("After circulating values:", a, b, c) # Output: 3 1 2

[9:31 AM, 6/15/2024] +91 70788 28486: a) Write a Python Program to check
whether a number is even or odd.
b) Write a Python Program to find the sum of digits in a number.
c) Define Function in Python with suitable example.
d) Write a Python Program to check whether a number is positive or negative.
e) What do you mean by loop?
f) Discuss different types of loops in python.
g) Explain List.
h) Difference between identifiers &keywords with help of examples.
i) Differentiate between “9 & 3" and "9 and 3" with output.
j) Explain briefly constant, variables, expression, keywords and statements
available in python.
[9:31 AM, 6/15/2024] +91 70788 28486: Sure, here are the answers to your
questions:

a) Python Program to check whether a number is even or odd:

python
def check_even_odd(num):
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")

num = 7
check_even_odd(num)

b) Python Program to find the sum of digits in a number:

python
def sum_of_digits(num):
total = 0
while num > 0:
total += num % 10
num //= 10
return total

number = 12345
print("Sum of digits in", number, "is:", sum_of_digits(number))

c) Function in Python with suitable example:

python
def greet(name):
print("Hello,", name)

greet("Alice")

In this example, greet is a function that takes one argument name and prints a
greeting message.

d) Python Program to check whether a number is positive or negative:


python
def check_positive_negative(num):
if num > 0:
print(num, "is positive")
elif num < 0:
print(num, "is negative")
else:
print(num, "is zero")

num = -5
check_positive_negative(num)

e) Loop in programming is a control flow statement that executes a block of code


repeatedly until a certain condition is met. It allows you to execute a piece of
code multiple times without having to write the same code multiple times.

f) Different types of loops in Python:


- for loop
- while loop

g) List in Python is a collection of items that are ordered and mutable. It can
contain elements of different data types and allows duplicate elements. Lists are
defined by enclosing comma-separated values within square brackets [].

h) Difference between identifiers & keywords:


- Identifiers: These are user-defined names used to identify variables, functions,
classes, modules, etc. They should follow certain rules such as starting with a
letter or underscore and not being a keyword.
- Keywords: These are reserved words in Python that have predefined meanings
and cannot be used as identifiers. Examples include if, else, while, for, def, class,
etc.

Example:
python
# Valid identifier
my_variable = 5

# Invalid identifier (using a keyword as an identifier)


if = 10 # Error: 'if' is a keyword

i) Difference between "9 & 3" and "9 and 3":


- "9 & 3" is a string containing the characters "9" and "&".
- "9 and 3" is a logical expression evaluating to False because it checks if both
"9" and "3" are true, which they are not.

j) Brief explanation of constant, variables, expression, keywords, and statements


in Python:
- Constant: A value that does not change during the execution of a program,
such as numbers or strings.
- Variable: A name that is used to refer to a value stored in memory. It can
change during the execution of a program.
- Expression: A combination of variables, operators, and/or function calls that
evaluates to a value.
- Keywords: Reserved words in Python that have predefined meanings and
cannot be used as identifiers.
- Statements: Instructions that perform actions in Python, such as assignments,
function calls, loops, etc.
[9:31 AM, 6/15/2024] +91 70788 28486: f) What is meant by module in python?
g) Explain function and module with suitable example.
h) Write short notes on types of operators in python with appropriate
example.
i) Write a program to Exchange the value of two variables.
j) Write a program to find the sum of n natural numbers.
[9:31 AM, 6/15/2024] +91 70788 28486: Sure, here are the answers to your
questions:

f) Module in Python:
A module in Python is a file containing Python code. It can define functions,
classes, and variables that can be reused in other Python files by importing them.
Modules allow you to organize code into separate files for better maintainability
and reusability.
g) Explanation of function and module with suitable examples:
- Function: A function in Python is a block of reusable code that performs a
specific task. It takes inputs, processes them, and returns an output. Functions
help in code reusability and modularity. Example:

python
def greet(name):
print("Hello,", name)

greet("Alice")

- Module: A module is a Python file that contains reusable code, including


functions, classes, and variables. It allows you to organize related code into
separate files. Example:

*my_module.py:*
python
def greet(name):
print("Hello,", name)

def add(a, b):


return a + b

*main_program.py:*
python
import my_module

my_module.greet("Bob")
result = my_module.add(3, 5)
print("Result:", result)

h) Types of operators in Python:


1. Arithmetic operators: Used to perform mathematical operations such as
addition, subtraction, multiplication, division, etc. Example:

python
a = 10
b=5
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)

2. Comparison operators: Used to compare two values and return a Boolean


result (True or False). Example:

python
a = 10
b=5
print("Is a greater than b?", a > b)
print("Is a equal to b?", a == b)
print("Is a not equal to b?", a != b)

3. Logical operators: Used to combine conditional statements. Example:

python
x = True
y = False
print("x and y:", x and y)
print("x or y:", x or y)
print("not x:", not x)

4. Assignment operators: Used to assign values to variables. Example:

python
x = 10
y=5
x += y # equivalent to x = x + y
print("x after addition:", x)

i) Program to Exchange the value of two variables:

python
a=5
b = 10

a, b = b, a

print("a after swapping:", a)


print("b after swapping:", b)

j) Program to find the sum of n natural numbers:

python
def sum_of_natural_numbers(n):
return (n * (n + 1)) // 2

n = 10
print("Sum of first", n, "natural numbers:", sum_of_natural_numbers(n))

You might also like