PYTHON
PYTHON
1) Define Function
In Python, a function is a block of reusable code that performs a specific task. You define a
function using the def keyword, followed by the function name and parentheses () that may
include parameters.
• def function_name(parameters):
• # Code block (indented)
• return result # optional
• class MyClass:
• def __init__(self, name):
• self.name = name
• def greet(self):
• print("Hello,", self.name)
Data Hiding is an object-oriented programming concept where internal object details (like
variables) are hidden from outside access to protect the integrity of the data.
In Python, data hiding is done using name mangling by prefixing variables or methods
with double underscores (__).
class Student:
7)Define and explain local variable and global variable with suitable Example
A local variable is declared inside a function and can be used only within that function
• def my_func():
• x = 10 # local variable
• print("Local x:", x)
• my_func()
A global variable is declared outside all functions and can be accessed inside any function
• x = 20 # global variable
• def my_func():
• print("Global x inside function:", x)
• my_func()
Example:
• f = open("data.txt", "r")
• print(f.read())
• f.close()
Example:
• f = open("data.txt", "w")
• f.write("Hello World!")
• f.close()
Example:
• f = open("data.txt", "a")
• f.write("\nNew Line")
• f.close()
Example:
• f = open("data.txt", "r+")
• print(f.read())
• f.write("\nAdded text")
• f.close()
5
The input() function is used to take input from the user via the keyboard.
print("Hello,", name)
A list is a built-in ordered, mutable collection used to store multiple items in a single
variable.
# Creating a list
# Accessing a list
print(fruits[0]) # apple
print(fruits[-1]) # mango
for f in fruits:
print("I like", f)