Python Concepts with Examples
1. Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It supports
multiple programming paradigms, including procedural, object-oriented, and functional programming. Python
is widely used in various domains such as web development, data science, automation, AI, and machine
learning.
Example:
print("Hello, Python!")
2. Programming Fundamentals (Simple Definition)
Programming fundamentals are the core building blocks required to write any computer program. They
include understanding variables, data types, input/output operations, control structures like if-else, loops, and
functions.
Example: Using a for loop to print numbers from 1 to 5
for i in range(1, 6):
print(i)
3. OOP Concepts & File Handling
Object-Oriented Programming (OOP) organizes code using classes and objects. Key OOP concepts include:
- Class: Blueprint for objects
- Object: Instance of a class
- Inheritance: Reusing code from another class
- Encapsulation: Hiding internal details
- Polymorphism: One interface, many forms
Example:
class Animal:
Python Concepts with Examples
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
[Link]()
Reading/Writing Text Files:
- Reading:
with open('[Link]', 'r') as f:
print([Link]())
- Writing:
with open('[Link]', 'w') as f:
[Link]("Python is awesome!")
4. Python Data Structures
- List: Ordered, changeable.
Example: my_list = [1, 2, 3]
print(my_list[0])
- Tuple: Ordered, unchangeable.
Example: my_tuple = (1, 2, 3)
print(my_tuple[1])
- Set: Unordered, no duplicates.
Example: my_set = {1, 2, 2, 3}
print(my_set)
- Dictionary: Key-value pairs.
Example: my_dict = {"name": "Ali", "age": 20}
print(my_dict["name"])
Python Concepts with Examples
5. Definition of Functions
A function is a block of code that performs a specific task and runs only when it is called.
Example:
def greet():
print("Hello from a function")
greet()
6. Pre-defined vs User-defined Functions
- Pre-defined functions are built into Python (e.g., print(), len(), type()).
- User-defined functions are created by the programmer to perform specific tasks.
Example of user-defined:
def add(a, b):
return a + b
print(add(3, 4))
7. Benefits of Using Functions
- Code reuse: Write once, use many times
- Improves readability
- Simplifies debugging and testing
- Modular design
Example:
def square(x):
return x * x
print(square(5))
Python Concepts with Examples
8. Classification of Functions
- Built-in Functions: Provided by Python (e.g., sum(), max())
- User-defined Functions: Defined by the user
- Lambda Functions: Anonymous, single-expression functions
Example lambda:
square = lambda x: x * x
print(square(4))
9. Declaring, Defining, and Calling Functions
To create a function:
def function_name(parameters):
# block of code
To call a function:
function_name(arguments)
Example:
def greet(name):
print("Hello", name)
greet("Ayesha")