Web technology Python_49330896_2025_06_24_17_27
Web technology Python_49330896_2025_06_24_17_27
Python
1. History of Python
Python was created by Guido van Rossum in 1991. It is designed to be easy to read and write, with a focus on
reducing complexity.
Python 2 is released in 2000, introduced features like list comprehensions. It was officially discontinued in 2020.
Python 3 is released in 2008, brought major improvements but was not backward-compatible with Python 2.
2. Features of Python
1. Easy to Learn and Use: Python has a simple syntax that resembles English, making it beginner-friendly.
2. Interpreted Language: Python code is executed line by line, making debugging easier.
3. Dynamically Typed: No need to declare variable types explicitly.
4. Platform Independent: Python code runs on various operating systems like Windows, macOS, and Linux
without modification.
5. Extensive Libraries: Python has a rich standard library and third-party modules for various tasks.
6. Supports Multiple Paradigms: Procedural Programming, Object-Oriented Programming (OOP) and Functional
Programming
7. Open Source: Python is free to use and distribute, even for commercial purposes.
8. Automatic Memory Management: Python manages memory allocation and garbage collection automatically.
3. Applications of Python
1. Web Development: Frameworks like Django and Flask make it easy to build robust web applications.
2. Data Science and Machine Learning: Libraries like NumPy, Pandas, and Scikit-learn are widely used for data
analysis and modeling.
3. Automation and Scripting: Automates repetitive tasks using simple scripts.
4. Game Development: Libraries like Pygame help in creating games.
5. Scientific Computing: Used in research and simulations with libraries like SciPy and Matplotlib.
6. Artificial Intelligence: Frameworks like TensorFlow and PyTorch are popular for AI applications.
7. Embedded Systems: Python is used in IoT devices and microcontroller programming.
Python Syntax
Python's syntax is minimalistic and emphasizes readability. It is similar to writing in English, which makes it
accessible to beginners.
1. No Semicolons: Statements end without semicolons.
2. Case Sensitivity: Python is case-sensitive, Variables like name and Name are different.
3. Dynamic Typing: No need to declare variable types.
4. Line Continuation:
Implicit: Parentheses, brackets, or braces allow multi-line statements.
Explicit: Use a backslash (\) for multi-line statements.
Indentation in Python
Python uses indentation to define blocks of code, replacing the use of curly braces {} or begin-end keywords
seen in other languages.
Mandatory Indentation:
Use the same number of spaces or tabs for all statements in a block. Use 4 spaces for each level of
indentation.
Indentation is not optional in Python. Omitting or inconsistent indentation will result in a IndentationError.
Increase the indentation level for nested blocks.
Mixing tabs and spaces can cause errors. Use either spaces or tabs consistently.
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
Web Tech Python Infeepedia By: Infee Tripathi
Comments in Python
Comments are used to explain the code, making it easier to understand. They are ignored during execution.
Types of Comments:
1. Single-Line Comments: Begin with a # symbol.
Example: # This is a single-line comment
2. Multi-Line Comments: Python does not have a specific syntax for multi-line comments.
However, you can use triple quotes (''' or """) to create block comments.
Example:
"""
This is a multi-line comment.
It spans multiple lines.
"""
Python Variables and Constants
Variables in Python
Python variables has dynamic typing. Explicit type declaration does not require. The type is determined at
runtime.
Constants in Python
Python does not have a built-in constant declaration mechanism, but naming conventions (e.g., all
uppercase) are used to indicate constants.
Input Output
15 You are a minor.
18 You are just 18.
21 You are an adult.
Loops in Python
Loops are used to execute a block of code multiple times.
2. continue Example
for i in range(5):
if i == 2:
continue
print(i, end=" ")
# Output: 0 1 3 4
3. pass Example
for i in range(3):
pass # Placeholder for future code
print("Loop executed.")
# Output: Loop executed.
Functions in Python
Functions are reusable blocks of code that perform a specific task. They enhance modularity and reusability in
programming.
Example:
# Function definition
def greet(name):
return f"Hello, {name}!"
# Function call
message = greet("Alice")
print(message)
# Output: Hello, Alice!
Return Values
The return statement is used to send the result of a function back to the caller.
Aspect Explanation Example
Single Value Return Returns a single value to the caller. def square(x): return x ** 2
square(4) (Result: 16)
Multiple Values Returns multiple values as a tuple. def calc(a, b): return a + b, a * b
Return calc(2, 3) (Result: (5, 6))
No Return Value If return is omitted, the function returns def say_hello(): print("Hello")
None by default. say_hello() (Result: None)
Introduction to Modules
A module is a file containing Python code (functions, classes, or variables) that can be reused in other programs.
Built-in Modules
# Selective Import
from math import pi, pow
print(pi) # Output: 3.141592653589793
print(pow(2, 3)) # Output: 8.0
# Alias Import
import random as rnd
print(rnd.randint(1, 5)) # Output: Random integer between 1 and 5
2. Tuples: A tuple is an ordered, immutable collection of elements. It can also contain mixed data types and
allows duplicates.
Immutable: Elements cannot be modified after creation.
Lightweight: Tuples are faster than lists.
Suitable for fixed data that should not change.
4. Dictionaries: A dictionary is an unordered, mutable collection of key-value pairs. Keys must be unique and
immutable, while values can be mutable.
Fast lookups using keys.
Dynamic: Can grow or shrink dynamically.
Keys are unique; values can be duplicated.
Operation Description Example Code
Create Use curly braces {} or dict(). my_dict = {'a': 1, 'b': 2}
Access Use keys. print(my_dict['a']) # Output: 1
Add/Update Assign key-value pairs. my_dict['c'] = 3
Remove Use pop(), clear(). my_dict.pop('a')
Iterate Use for loop with keys(), values(), items(). for key, value in my_dict.items(): print(key, value)
5. Comprehensions:
Comprehensions are a concise way to create data structures.
Type Example Code Output
List Comprehension squares = [x**2 for x in range(5)] print(squares) [0, 1, 4, 9, 16]
Set Comprehension unique_squares = {x**2 for x in [1, 2, 2, 3]} {1, 4, 9}
print(unique_squares)
Dictionary square_dict = {x: x**2 for x in range(5)} {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Comprehension print(square_dict)
1. Class: A blueprint for creating objects. It defines the attributes and methods that the objects of the class will
have.
A class is a user-defined data type that serves as a blueprint for creating objects.
It is defined using the class keyword.
2. Object: An instance of a class. Objects are created using the class blueprint and can have their own data and
behavior.
3. Methods: Functions defined inside a class that operate on the attributes of the class.
Syntax
class ClassName:
def __init__(self, parameter1, parameter2):
self.attribute1 = parameter1
self.attribute2 = parameter2
Example: Constructor
class Person:
def __init__(self, name, age):
# Initializing attributes
self.name = name
self.age = age
def display_details(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# Accessing methods
person1.display_details() # Output: Name: Alice, Age: 25
person2.display_details() # Output: Name: Bob, Age: 30
Inheritance
Inheritance allows a class (called the child class) to inherit the attributes and methods of another class (called
the parent class).
It helps in reusing code and extending the functionality of existing classes.
Parent Class (Base Class): The class whose properties are inherited.
Child Class (Derived Class): The class that inherits the properties of the parent class.
A child class can add new attributes or methods and can override the methods of the parent class.
Syntax
class ParentClass:
# Parent class methods and attributes
pass
class ChildClass(ParentClass):
# Child class methods and attributes
pass
def display_species(self):
print(f"Species: {self.species}")
def display_details(self):
print(f"Species: {self.species}, Breed: {self.breed}")
Polymorphism
Polymorphism means "many forms." It allows the same method or operator to behave differently based on the
object or data type.
Types of Polymorphism
1. Method Overriding: A child class redefines a method of the parent class.
2. Method Overloading (Not natively supported in Python): Achieved by default parameters or handling multiple
argument types.
# Creating objects
vehicle = Vehicle()
car = Car()
# Calling methods
vehicle.start() # Output: Vehicle is starting...
car.start() # Output: Car is starting...
class Dog:
def sound(self):
print("Dogs bark.")
# Polymorphic behavior
def make_sound(animal):
animal.sound()
File Modes
Mode Description
'r' Opens a file for reading (default mode). The file must exist.
'w' Opens a file for writing. If the file exists, it is overwritten. If it doesn’t exist, a new file is created.
'a' Opens a file for appending. Data is added to the end of the file. If the file doesn’t exist, it creates a
new file.
'r+' Opens a file for both reading and writing. The file must exist.
'w+' Opens a file for both writing and reading. If the file exists, it is overwritten. If it doesn’t exist, a new
file is created.
'a+' Opens a file for both appending and reading. Data is added to the end of the file. If the file doesn’t
exist, a new file is created.
Example
file = open("example.txt", "w") # Open file in write mode
file.write("Hello, World!") # Write to the file
file.close() # Close the file
Writing to a File
Example
with open("example.txt", "r") as file:
content = file.read()
print(content)
# No need to call file.close() explicitly
Nested try-except Blocks: Sometimes, multiple operations on a file may require separate exception handling.