Ques bankPYsol Ut2
Ques bankPYsol Ut2
NO.
Package
the concepts of local variables and global variables refer to the scope of
variables in programming, which determines where and how these variables
can be accessed within the program. The scope essentially defines the region
of the code where a variable is accessible.
Local Variable:
x = 10 # x is a local variable
print(x)
example_function()
# print(x) # This would cause an error because x is local to
example_function
n this example:
Global Variable:
def example_function():
print(x) # Accessing the global variable inside a function
1. Mathematical Functions:
class Person:
def __init__(self, name, age):
self.name = name # Public attribute
self.__age = age # Private attribute (data hiding)
In Python, files can be opened, read, written to, and closed using built-in
functions. File operations are crucial for tasks that involve saving data or
interacting with external information.
1 Text Files
2 Binary Files:
● Description: Opens the file for reading. The file must exist,
otherwise, a FileNotFoundError is raised.
● Description: Opens the file for writing. If the file already exists, its
content is truncated (i.e., overwritten). If the file does not exist, a
new empty file is created.
● Description: Opens the file for appending. If the file does not exist,
it creates a new file. Data is added to the end of the file without
truncating the existing content.
● Description: Opens the file for reading in binary mode. The file is
opened in the same way as 'r', but it treats the file as binary rather
than text. It reads the file's raw bytes.
def reverse_number(num):
reversed_num = 0
return reversed_num
Concatenation (+ Operator)
The + operator is used to concatenate (join) two or more strings into a single
string.
. Repetition (* Operator)
The * operator is used to repeat a string multiple times. You specify the
number of times you want to repeat the string.
The in and not in operators are used to check whether a substring exists
within a string
.program:
str1 = "Hello"
str2 = "World"
repeat_result = str1 * 3
def speak(self):
print(f"{self.name} makes a sound")
# Method overriding
def speak(self):
print(f"{self.name} barks")
# Calling methods
dog.speak() # Output: Buddy barks
When a method in a child class has the same name, signature, and
parameters as a method in the parent class, it overrides the parent class
method. This is a key feature of polymorphism, where different classes can
have methods that behave differently, even if they have the same name.
# Parent Class
class Animal:
def sound(self):
print("Some generic animal sound")
# Child Class
class Dog(Animal):
def sound(self):
print("Woof! Woof!")
# Child Class
class Cat(Animal):
def sound(self):
print("Meow! Meow!")
● try block: The code that might raise an exception is placed inside
the try block.
● except block: If an exception occurs inside the try block, the code
inside the except block is executed. It handles the exception.
def check_positive_number(number):
try:
if number < 0:
raise ValueError("Number must be positive!")
print(f"Input number {number} is valid.")
except ValueError as e:
print(f"Error: {e}")
finally:
print("Completed number validation.\n")
def get_integer_input():
try:
user_input = int(input("Please enter a number: "))
check_positive_number(user_input)
return user_input
except ValueError as e:
print(f"Error: {e} - Invalid input, please enter an integer.")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("Input process is complete.\n")
In Python, a class is defined using the class keyword, followed by the name
of the class (usually in CamelCase), and a colon :. Inside the class, you
define methods and variables (also known as attributes) that belong to the
class.
class ClassName:
# Constructor to initialize object attributes (optional)
def __init__(self, param1, param2):
# Initialize the instance variables
self.param1 = param1
self.param2 = param2
# Method of the class
def some_method(self):
# Code for the method
pass
# Another method
def another_method(self, value):
# Code for another method
pass
1. class ClassName:
○ These are functions defined inside the class that describe the
behaviors of the class objects.
# Circumference = 2 * π * radius
circumference = 2 * math.pi * radius
9 Python program that will display calendar of month using calender module.
Ans:
import calendar
1. len()
The len() function is used to return the number of items in an object, such as
a list, string, tuple, dictionary, etc. It returns the length of the object.
Syntax:
len(object)
2. type()
The type() function is used to get the type (or class) of an object. It returns
the type of the object passed to it.
Syntax:
type(object)
3. max()
The max() function returns the largest item from an iterable (like a list, tuple,
etc.) or the largest of two or more arguments.
Syntax:
max(iterable, *args, key=None)
4. sum()
The sum() function returns the sum of all elements in an iterable (e.g., a list
or tuple). Optionally, you can also provide a starting value to add to the sum.
Syntax:
sum(iterable, start=0)
# Using len() to get the length of the string and the list
print("Length of the string:", len(string_example)) # Output: 13
print("Length of the list:", len(list_example)) # Output: 5
# Example 3: Using max() to get the maximum value from a list and multiple
arguments
numbers_list = [10, 20, 5, 30, 15]