comp 12th
comp 12th
comp 12th
Conditional statements in Python allow you to control the flow of your program
based on conditions. The main types are:
1. if Statement
Executes a block of code if the condition is True.
x = 10
if x > 5:
print("x is greater than 5")
2. if-else Statement
Adds an alternative block of code if the condition is False.
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
3. if-elif-else Statement
Allows checking multiple conditions in sequence.
x = 10
if x < 5:
print("x is less than 5")
elif x == 10:
print("x is equal to 10")
else:
print("x is greater than 5 but not 10")
loops
1. While Loop
A while loop is a control flow statement in programming that repeatedly
executes a block of code as long as a specified condition evaluates to True. It is
used when the number of iterations is not predetermined but depends on a
conditions.
Example:
count = 0
while count < 5:
print(count)
count += 1
2. For Loop
A for loop is a control flow statement used in programming to repeatedly
execute a block of code for a specified number of iterations or over a collection
of items like lists, strings, or ranges.
Example:
for num in range(5):
print(num)
3. Finite and Infinite Loops
Finite Loop
A finite loop executes a specific number of times or iterates over a
predetermined set of items. It terminates when a condition is met or when all
items have been processed.
Example (Python)
# Finite loop iterating 5 times
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
The loop will stop after 5 iterations because the range is finite.
Infinite Loop
An infinite loop runs indefinitely because the termination condition is never
satisfied (or no condition is provided). Infinite loops are often used in programs
that wait for external events or user input, such as servers or GUIs.
Example (Python)
# Infinite loop
while True:
print("This is an infinite loop")
This loop will continue forever unless manually stopped (e.g., Ctrl+C in most
environments)
4. Nested Loop
A nested loop is a loop inside another loop. The inner loop runs completely each
time the outer loop runs once. Nested loops are commonly used for working
with multi-dimensional data or solving problems with multiple layers of
iteration.
Example:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
5. Break and Continue
In programming, break and continue are control flow statements used within
loops to manage the flow of execution:
break Statement
Purpose: Exits the loop immediately, regardless of its condition.
Use case: When a specific condition is met, and you no longer need to iterate.
Example:
for i in range(5):
if i == 3:
break
print(i)
# Output: 0 1 2
Explanation:
The loop runs until i == 3.
At i == 3, the break statement terminates the loop.
continue Statement
Purpose: Skips the rest of the code in the current iteration and jumps to the next
iteration of the loop.
Use case: When you want to bypass a specific iteration without breaking the
loop.
Example:
for i in range(5):
if i == 3:
continue
print(i)
# Output: 0 1 2 4
Explanation:
When i == 3, the continue statement skips the print(i) and moves to the next
iteration.
USER DEFINED FUNCTIONS IN PYTHON
CONCEPT OF A FUNCTION
➢ In Python, a function is a block of reusable code that performs a specific
task. Functions help in organizing and simplifying code, making it more
readable, maintainable, and modular. Python provides built-in functions
(like print(), len(), etc.) and allows you to create your own custom
functions.
➢ 1. Defining a Function
You define a function using the def keyword, followed by the function
name, parentheses (which can include parameters), and a colon. The
function's code block is indented.
def greet():
print("Hello, World!")
Functions are a core part of Python programming, providing structure and
reusability to your code. You can use them for computations, data
processing, or even breaking down a complex task into manageable parts.
➢ CALLING A FUNCTION
In Python, calling a function means executing the code within that
function. Here's the general syntax and an example:
General Syntax:
function_name(arguments)
Example 1: Calling a Function with No Arguments
def greet():
print("Hello, World!")
# Call the function
greet()
Output:
Hello, World!
Example 2: Calling a Function with Arguments
def greet(name):
print(f"Hello, {name}!")
# Call the function
greet("Alice")
Output:
Hello, Alice
Example 3: Calling a Function with Return Values
def add(a, b):
return a + b
# Call the function and store the result
result = add(5, 3)
print("The sum is:", result)
Output:
The sum is: 8
Make sure the function is defined before calling it in your code.
➢ ARGUMENTS AND ARBITRARY ARGUMENTS
In Python, arguments refer to the values passed to a function when calling
it. Functions can accept different types of arguments. Here's a breakdown
of the main types of arguments in Python:
1. Positional Arguments
These are the most common types of arguments. The values passed are
assigned to the function parameters in the same order in which they
appear.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("Alice", 30) # name="Alice", age=30
2. Keyword Arguments
In this case, you can specify the values for parameters by explicitly naming
them. The order doesn't matter, as long as each argument is assigned to a
parameter name.
def greet(name, age):
print(f"Hello, my name is {name} and I am {age} years old.")
greet(age=30, name="Alice") # name="Alice", age=30
3. Default Arguments
You can assign default values to function parameters. If an argument is not
passed for that parameter, the default value is used.
def greet(name, age=25):
print(f"Hello, my name is {name} and I am {age} years old.")
greet("Alice") # Uses default value for age (25)
greet("Bob", 30) # Uses provided value for age (30)
4. Variable-length Arguments (Arbitrary Arguments)
Sometimes, you don't know how many arguments will be passed to a
function. In such cases, you can use *args for a variable number of
positional arguments or **kwargs for a variable number of keyword
arguments.
*args: Collects additional positional arguments into a tuple.
def greet(*args):
for arg in args:
print(f"Hello, {arg}!")
greet("Alice", "Bob", "Charlie")
**kwargs: Collects additional keyword arguments into a dictionary
def greet(**kwargs):
for name, age in kwargs.items():
print(f"Hello, {name}, you are {age} years old.")
greet(Alice=30, Bob=25, Charlie=35)
5. Combination of Argument Types
You can combine different types of arguments in a single function, but the
order should be:
1. Positional arguments
2. *args
3. Default arguments
4. **kwargs
def greet(name, *args, age=30, **kwargs):
print(f"Hello, {name}.")
print(f"Additional information: {args}")
print(f"Age: {age}")
print(f"Other details: {kwargs}")
greet("Alice", "Engineer", "Loves coding", age=25, city="New York",
country="USA")
This would print:
Hello, Alice.
Additional information: ('Engineer', 'Loves coding')
Age: 25
Other details: {'city': 'New York', 'country': 'USA'}
➢ SCOPE OF VARIABLE (LOGICAL AND GLOBAL)
In Python, variables have two main types of scope: logical scope and global
scope. Here's how they differ:
1. Global Scope:
A global variable is defined outside any function or block of code and is
accessible from anywhere in the program.
Global variables are stored in the global namespace and can be accessed
by any function in the same module or script, unless shadowed by a local
variable with the same name.
If you want to modify a global variable inside a function, you need to
declare it as global within the function.
Example:
x = 10 # Global variable
def func():
global x
x = 20 # Modifying the global variable inside the function
func()
print(x) # Outputs: 20
Without the global keyword, attempting to modify x inside the function
would result in a local variable being created instead of modifying the
global one.
2. Logical Scope (also referred to as local scope):
A local variable is defined inside a function or block of code and is only
accessible within that function or block.
The logical scope refers to where the variable is logically available for use,
which can vary based on the flow of the program.
A local variable is typically created when the function is called and
destroyed when the function exits.
Local variables cannot be accessed outside their function, and they exist
only within that specific function or block.
Example:
def func():
x = 10 # Local variable
print(x)
func()
# print(x) # This will raise an error because x is local to func
Conclusion:
➢ Global variables can be accessed and modified anywhere in the code (as
long as you use the global keyword inside functions to modify them).
➢ Logical (local) variables are confined to the function or block they are
created in, and cannot be accessed outside of it.
➢ Python resolves variables based on the LEGB rule, giving priority from the
innermost scope (local) to the outermost scope (built-in).
FUNCTIONS RETURNING VALUES
In Python, functions can return values using the return
statement. This allows a function to output data back to the
caller. Here's a basic example:
Example of a function that returns a value:
def add(a, b):
result = a + b
return result
# Call the function and store the result
sum_result = add(5, 3)
print(sum_result) # Output: 8
Explanation:
The function add(a, b) takes two arguments (a and b),
calculates their sum, and returns the result using the return
keyword.
The sum_result stores the returned value, which is then
printed.
INTRODUCTION TO OBJECT ORIENTED
PROGRAMING IN PHY.
➢ CONCEPT OF OBJECT ORIENTED PROGRAMING:
Object-Oriented Programming (OOP) in Python is a programming paradigm
that organizes software design around data, or objects, rather than
functions and logic. Objects can contain both data in the form of fields
(often called attributes) and methods (functions that operate on the data).
OOP helps in organizing complex programs, making them easier to
manage, and promoting code reuse.
➢ BASIC ELEMENTS OF OOP:
1. Class: A blueprint for creating objects. It defines a set of attributes and
methods that the created objects will have.
2. Object: An instance of a class. It contains data and behavior defined by
the class.
3. Encapsulation: Hiding the internal state and requiring all interaction to
be done through methods. This ensures that the data is protected from
outside interference and misuse.
4. Inheritance: A mechanism by which one class can inherit the attributes
and methods of another class. This promotes code reuse and allows for
hierarchical relationships between classes.
5. Polymorphism: The ability of different objects to respond to the same
method in a way appropriate to their class, allowing for different behaviors
based on the object type.
6. Abstraction: Hiding the complexity of the system and exposing only the
essential features. It helps in simplifying complex systems by focusing on
high-level operations.
7.DATA Hiding;
In Object-Oriented Programming (OOP) in Python, data hiding refers to
the practice of restricting direct access to certain attributes or methods of
a class. This is done to ensure that an object's internal state is protected
from unintended interference or misuse. It allows the class to control how
its data is accessed or modified.
➢ Advantages of OOP:
1. Modularity: OOP allows for the division of complex programs into
smaller, manageable sections, making development and maintenance
easier.
2. Reusability: Through inheritance, objects and classes can be reused,
reducing redundancy in the code and saving time.
3. Maintainability: Changes made in the class or object structure will not
affect other parts of the system, improving the ease of making
modifications or fixing bugs.
4. Scalability: OOP's hierarchical structure enables easy extension of
programs as new features or requirements emerge.
5. Security: With encapsulation, the internal state of an object is
protected, and access to it is controlled via public methods, ensuring
greater data integrity.
6. Flexibility and Extensibility: Polymorphism allows objects of different
types to be treated as objects of a common superclass, making systems
more flexible and adaptable to change.
In Python, OOP is widely used due to its simple syntax and support for
defining classes and objects, making it an essential tool for developing
scalable and maintainable applications.
➢ Access specifiers;
In Object-Oriented Programming (OOP) in Python, access specifiers control
the visibility and accessibility of class attributes and methods. Python uses
a more flexible approach than some other languages like Java or C++, but it
still follows some conventions to define the access level of members
(attributes and methods).
Here’s a breakdown of the three main access levels in Python:
1. Public Access:
Public members are accessible from outside the class.
This is the default level of access for attributes and methods in Python.
There is no special syntax for defining public members; simply declare
them without any underscores.
2. Protected Access:
Protected members are meant to be used within the class and its
subclasses (child classes), but not directly from outside.
In Python, protected members are indicated by a single underscore (_)
before the attribute or method name.
This is just a convention and does not prevent access from outside the
class or subclass. It simply signals that these members are intended for
internal use.
3. Private Access:
Private members are intended to be used only within the class itself.
In Python, private members are indicated by a double underscore () before
the attribute or method name.
This triggers name mangling, which changes the name of the attribute in
the background, making it harder (but not impossible) to access from
outside the class.
Summary of Access Specifiers in Python:
Public: No leading underscore. Accessible from anywhere.
Protected: One leading underscore (_). Intended for internal use and
inheritance, but can be accessed from outside.
Private: Double leading underscore (). Name mangled to prevent direct
access, but still accessible using name mangling.
It's important to remember that Python does not enforce access
restrictions like some other languages. Instead, it relies on conventions and
the "we're all consenting adults" philosophy, meaning that it's up to the
developer to respect the intended access levels.
➢ Constructors;
In Python, constructors are special methods used to initialize objects of a
class. They are called automatically when an object of the class is created.
The constructor in Python is defined using the _init_ method.
Types of Constructors in Python
1. Default Constructor:
A default constructor is one that doesn't take any arguments except self.
It initializes the object with default values.
If no constructor is defined, Python provides a default constructor for the
class, which doesn't do any special initialization.
2. Parameterized Constructor:
A parameterized constructor takes one or more arguments along with self.
It allows us to initialize objects with different values when they are
created.
Summary:
Default Constructor: Does not accept any arguments except self. Used for
initializing object with default values.
Parameterized Constructor: Accepts parameters, allowing objects to be
initialized with custom values when they are created.
➢ Concept of destructor:
In Python, a destructor is a special method used to define how an object
should be cleaned up or destroyed when it is no longer in use. It is defined
using the _del_() method, which is automatically called when an object is
about to be destroyed, i.e., when it is garbage collected.
DATABASE AND SOL
➢ DATABASE AND ITS ADVANTAGES;
In Python, a database is typically used to store, manage, and retrieve data
efficiently. Python provides libraries like SQLite, MySQL, PostgreSQL, and
others to interact with databases. Databases can either be relational (SQL-
based) or non-relational (NoSQL-based), with SQL databases like SQLite,
MySQL, and PostgreSQL being the most commonly used in Python
projects.
Don'ts:
Don’t click on links in unsolicited emails or messages.
Don’t share sensitive personal information over unsecured websites.
Don’t download software or files from untrusted sources.
Don’t ignore software updates, as they often include security patches.