Overview of Python
Python is a high-level, interpreted, general-purpose programming language known for its simplicity, readability, and versatility. Since its inception, Python has become one of the most widely used languages in the world, powering everything from web development and automation scripts to data analysis, artificial intelligence, and scientific computing.
This overview provides a foundational understanding of Python, what makes it unique, and why it continues to be a preferred language among developers, educators, and researchers.
What is Python?
Python is an open-source programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability and reduces the cost of program maintenance by allowing developers to express concepts in fewer lines of code compared to languages like C++ or Java.
Python supports multiple programming paradigms, including:
- Procedural programming
- Object-oriented programming (OOP)
- Functional programming
Its dynamic typing, automatic memory management, and extensive standard library make it suitable for both beginners and professionals.
Key Features of Python
-
Readable and Clean Syntax Python’s syntax closely resembles plain English, making it ideal for beginners. The use of indentation rather than curly braces improves readability and enforces good coding practices.
-
Interpreted Language Python code is executed line by line, which simplifies debugging and testing. It doesn’t require compilation, so you can quickly write and test code snippets.
-
Dynamically Typed You don’t need to declare the data type of a variable. Python determines it during runtime, making it flexible and concise.
-
Extensive Standard Library Python includes a large standard library offering modules and packages for a variety of tasks such as file I/O, regular expressions, threading, HTTP handling, and more.
-
Cross-Platform Python is platform-independent. Code written on Windows will typically run on Linux or macOS with little or no modification.
-
Large Community and Ecosystem Python has a vast and active community. Thousands of open-source libraries and frameworks (like Django, Flask, NumPy, Pandas, TensorFlow) support Python’s application across industries.
Common Use Cases
Python is a general-purpose language used across a wide range of domains:
- Web Development: Using frameworks like Django and Flask.
- Data Science and Machine Learning: With libraries such as NumPy, Pandas, Scikit-learn, TensorFlow, and PyTorch.
- Scripting and Automation: Writing small scripts to automate tasks such as file handling, data scraping, and system monitoring.
- Game Development: Using libraries like Pygame.
- Desktop GUI Applications: Built with Tkinter or PyQt.
- Cybersecurity and Penetration Testing: Many tools and scripts in security are Python-based.
- Education: Python is widely taught in schools and universities due to its simplicity.
Advantages of Learning Python
- Beginner-Friendly: Designed with simplicity in mind, making it a popular choice for first-time programmers.
- Versatile: One language, many applications.
- High Demand in Industry: Python skills are highly sought after in job markets around the globe.
- Strong Community Support: A large ecosystem means solutions and help are easily accessible.
Limitations of Python
While Python offers many advantages, it’s important to be aware of its limitations:
- Slower Execution: Compared to compiled languages like C or Java, Python may be slower due to its interpreted nature.
- Memory Consumption: Python’s dynamic typing and flexibility come at the cost of higher memory usage.
- Mobile Development: Not commonly used for mobile app development, though some tools like Kivy exist.
Who Should Learn Python?
- Students and Beginners who want to learn programming fundamentals.
- Web Developers who want to build scalable web applications.
- Data Scientists and Analysts interested in working with data.
- Engineers and Automation Experts looking to write scripts to automate workflows.
- Anyone looking for a career in software, AI, or scientific computing.
Conclusion
Python is a modern, high-level language that combines power with simplicity. Whether you’re just beginning your programming journey or you’re an experienced developer exploring new domains, Python is a valuable tool that opens up numerous opportunities. As we progress through this documentation, you’ll learn everything from installation and basic syntax to advanced concepts and project development.
Why Python?
Choosing the right programming language is crucial for the success of a project, especially in the early stages of learning or development. Python stands out among modern languages due to its ease of use, readability, and a rich ecosystem of tools and libraries. This section explores the key reasons why Python is one of the most popular and versatile programming languages in the world.
1. Beginner-Friendly
Python’s clean and human-readable syntax lowers the entry barrier for beginners. The code closely resembles English, which allows new programmers to focus on learning programming concepts rather than worrying about complex syntax rules.
# Python code to print a greeting
name = “Alice”
print(“Hello,”, name)
Compared to other languages, Python avoids boilerplate code and makes the learning curve less steep.
2. Versatile and General-Purpose
Python is not limited to one type of task or domain. It is a general-purpose language, which means it can be used for:
- Web development
- Data analysis
- Machine learning
- Automation and scripting
- Game development
- Cybersecurity
- Desktop applications
- Internet of Things (IoT)
- Scientific computing
This versatility allows developers to apply their Python knowledge across multiple industries.
3. Strong Community Support
Python has one of the largest and most active developer communities. This means:
- Abundant free learning resources (tutorials, forums, documentation)
- Quick support for debugging and resolving issues
- Thousands of third-party libraries and frameworks maintained by the community
For learners and professionals alike, this support system reduces friction and speeds up the development process.
4. Rich Ecosystem of Libraries and Frameworks
Python offers powerful libraries and frameworks that drastically simplify complex tasks:
| Domain | Popular Libraries/Frameworks |
|---|---|
| Web Development | Django, Flask, FastAPI |
| Data Science | Pandas, NumPy, Matplotlib |
| Machine Learning | Scikit-learn, TensorFlow, PyTorch |
| Automation | Selenium, PyAutoGUI, schedule |
| Testing | unittest, pytest |
| Game Development | Pygame |
These tools help developers build applications faster and more efficiently, often with just a few lines of code.
5. Excellent for Rapid Development
ython’s simplicity and the availability of high-level libraries enable rapid prototyping. This is especially useful in startups, research, and education, where time-to-market or proof-of-concept is crucial.
Developers can go from idea to working prototype in a matter of hours or days.
6. Cross-Platform Compatibility
Python is available on all major operating systems — Windows, macOS, and Linux. You can write a Python script once and run it on multiple platforms with minimal or no changes.
This portability makes Python ideal for collaborative and cross-environment projects.
7. In-Demand Skill in the Industry
Python is consistently ranked among the top programming languages in developer surveys (e.g., Stack Overflow, TIOBE Index). It is heavily used by:
- Tech companies (Google, Facebook, Netflix)
- Data science and AI startups
- Government and research institutions
- Fintech and enterprise software providers
Learning Python opens up numerous career opportunities across domains.
History of Python
Python has a rich and thoughtful history that reflects its core philosophy: simplicity and readability. Unlike many programming languages that emerged from academic or corporate research labs, Python was born out of a personal project — one that grew into one of the most influential programming languages of the modern era.
This section walks through the key milestones in the development of Python, helping you understand not only how Python came to be, but also why it was created the way it was.
Origin and Motivation
Python was created by Guido van Rossum, a Dutch programmer, during the late 1980s. At the time, van Rossum was working at the Centrum Wiskunde & Informatica (CWI) in the Netherlands and was involved in a project called ABC, a simple teaching language.
While ABC had several good ideas, it also had limitations. Guido wanted to build a language that retained the best parts of ABC while improving its flexibility and extensibility. Over the Christmas holidays in 1989, he began developing the new language — eventually naming it “Python.”
Why the name “Python”? Guido van Rossum was a fan of the British comedy group Monty Python’s Flying Circus. He wanted a name that was short, unique, and slightly mysterious — hence, Python.
Key Milestones
1991: Python 0.9.0
The first public release of Python, version 0.9.0, was released on February 20, 1991. It already included many features that would become hallmarks of the language:
- Functions
- Exception handling
- Core data types:
str,list,dict,tuple - Modules
# Simple Python example from early versions
def greet(name):
print(“Hello,”, name)greet(“World”)
1994: Python 1.0
Python 1.0 was officially released in January 1994. This version introduced:
- Lambda functions
-
map(),filter(), andreduce()functions - The formal inclusion of modules
2000: Python 2.0
Python 2.0 was released on October 16, 2000, marking a major update:
- List comprehensions
- Garbage collection based on reference counting and cyclic detection
- Unicode support
Python 2 became the dominant version for many years, but over time, inconsistencies and legacy issues accumulated.
2008: Python 3.0 (“Python 3000”)
Python 3.0 was released on December 3, 2008, as a backward-incompatible version intended to clean up the language and remove legacy designs. Key changes included:
- Print statement became a function:
print() - Better Unicode handling
-
range()replacedxrange() - Dictionary methods like
.keys()returned views instead of lists
Despite its improvements, the transition from Python 2 to 3 was slow because many libraries were not initially compatible.
Modern Evolution
2020: Python 2 End-of-Life
After years of parallel support, Python 2 reached end-of-life on January 1, 2020, officially pushing the community to adopt Python 3 fully.
2023 and Beyond
Python continues to evolve with a focus on:
- Performance improvements (e.g., Python 3.11 introduced the “Faster CPython” project)
- Better typing support with
typingandmypy - Pattern matching (introduced in Python 3.10)
- Community-driven governance (via the Python Software Foundation and PEPs — Python Enhancement Proposals)
Release Timeline Summary
| Version | Year | Key Features |
|---|---|---|
| 0.9.0 | 1991 | First public release, core features |
| 1.0 | 1994 | Lambda,
map()
,
filter()
,
reduce()
|
| 2.0 | 2000 | List comprehensions, garbage collection |
| 3.0 | 2008 | Unicode, new
print()
, cleaner syntax |
| 3.10+ | 2021– | Pattern matching, improved performance |
Guido van Rossum: The Benevolent Dictator for Life
For much of Python’s life, Guido van Rossum acted as the BDFL (Benevolent Dictator for Life), guiding its development with vision and consistency. In 2018, he stepped down from this role, leaving governance to the Python Steering Council — a group of core developers elected by the community.
Conclusion
Python’s history is a story of thoughtful evolution, driven by a commitment to simplicity, readability, and community collaboration. From its humble beginnings as a hobby project to its current role as a foundational technology in science, education, and industry, Python’s journey reflects the power of open-source innovation and practical design.
In the next section, we’ll cover how to install Python and get your development environment ready.
Syntax and Indentation in Python
Unlike many programming languages that use braces
{}
or keywords to define code blocks, Python uses indentation as a core part of its syntax. This unique feature makes Python code more readable and consistent, but it also means that proper indentation is not optional — it is mandatory.
In this section, we’ll explore Python’s syntax rules and how indentation defines the structure and flow of a Python program.
1. Python’s Clean Syntax
Python’s syntax is designed to be clear and human-readable. Statements end with newlines rather than semicolons (though semicolons are allowed, they are not recommended). Curly braces
{}
are not used for grouping code blocks. Instead, Python relies on indentation levels to determine block structure.
greeting.pyname = "Alice"print("Hello,", name)
There’s no need to declare variable types (
name
is automatically recognized as a string), and there are no trailing semicolons.
2. The Role of Indentation
Indentation is not just for readability — it defines the code structure. All statements within the same block of code must be indented the same amount.
A block typically follows structures like
if
,
for
,
while
,
def
,
class
, etc.
age = 18 if age >= 18: print(“You are eligible to vote.”) print(“Remember to carry your ID.”)
If the indentation is inconsistent or missing, Python will raise an
IndentationError
.
3. Consistent Use of Spaces or Tabs
You must choose either spaces or tabs for indentation — do not mix them. PEP 8 (Python’s style guide) recommends:
- Using 4 spaces per indentation level
- Avoiding tabs
Most modern IDEs and code editors are configured to use 4 spaces by default when writing Python code.
4. Nested Indentation
You can nest blocks inside other blocks, just like other languages. Each new block increases the indentation level.
score = 85 if score >= 50: print(“Pass”) if score >= 80: print(“Distinction”)
In this example, the inner
if
block is indented further than the outer block, and Python uses this indentation to determine the scope of each condition.
5. Indentation Errors
Python is strict about indentation. A mismatch in indentation will immediately raise an error.
Example of Incorrect Indentation:
def greet():print(“Hello”) # This will raise an IndentationError
Comments in Python
Comments are an essential part of writing clean, maintainable, and professional code. While your code tells the computer what to do, comments explain your intentions to other developers — including your future self.
In Python, comments are easy to write and highly encouraged. They are ignored by the Python interpreter and serve purely as human-readable documentation.
This section explores the different types of comments in Python, when and how to use them, and what makes a comment truly useful.
1. What is a Comment?
A comment is a line or part of a line in a program that is not executed. It helps:
- Explain the logic or intent behind code
- Clarify complex operations
- Provide metadata (e.g., author, date, purpose)
- Temporarily disable code during debugging
2. Single-Line Comments
In Python, single-line comments begin with a hash symbol (
#
). Everything after the
#
on that line is treated as a comment.
Bad comment:
i = i + 1 # Increment i by 1
Better comment:
i = i + 1 # Move to the next item in the list
3. Multi-Line Comments
Python does not have a distinct multi-line comment syntax like
/* */
in some other languages. Instead, you use
#
at the beginning of each line:
# This function calculates the area of a circle.# It takes the radius as input and returns the result.# The formula used is: area = π * r^2def area(radius): return 3.14 * radius * radius
For longer explanations or module-level comments, it’s better to use docstrings (discussed below).
5. Where to Use Comments
| Use Case | Example |
|---|---|
| Explaining logic | Why you chose a particular algorithm or technique |
| Marking TODOs |
# TODO: Optimize this loop later
|
| Clarifying workarounds | When a bug or platform limitation requires an unusual solution |
| Separating sections |
# ----- Input Handling -----
|
Numeric Types in Python
Numeric types are among the most fundamental data types in Python. They allow developers to represent and perform operations on numeric values such as integers, decimal numbers, and even complex numbers. Python provides three distinct numeric types:
-
int– Integer values -
float– Floating-point decimal values -
complex– Complex numbers with real and imaginary parts
This article explores each of these types in detail, including syntax, behavior, and practical examples.
1. int – Integer Type
The
int
type represents whole numbers (both positive and negative) without any decimal part. Python integers are of arbitrary precision, meaning they can be very large, limited only by memory.
Characteristics:
- No fractional part
- Supports binary, octal, and hexadecimal literals
- Commonly used in counting, indexing, and integer arithmetic
Example 1: Basic Integer Assignment and Arithmetic
a = 10b = 4print(a + b) # Output: 14
This demonstrates basic addition using integer values.
Example 2: Integer Division and Floor Division
a = 10print(a / 3) # Output: 3.333...print(a // 3) # Output: 3 (floor division)
Note that
/
returns a
float
, while
//
returns an
int
by removing the fractional part.
Example 3: Working with Binary, Octal, and Hexadecimal
bin_num = 0b1010 # binary (10)oct_num = 0o12 # octal (10)hex_num = 0xA # hexadecimal (10) print(bin_num + oct_num + hex_num) # Output: 30
Python allows integer literals in various bases using prefixes like
0b
,
0o
, and
0x
.
2. float – Floating-Point Numbers
The
float
type is used to represent decimal or real numbers with a fractional component. Python floats are based on the IEEE 754 double-precision format.
Characteristics:
- Represent numbers with decimals (e.g., 3.14, -0.5)
- Subject to rounding errors due to binary representation
- Useful in scientific, financial, and statistical computations
Example 1: Basic Float Assignment and Operations
pi = 3.14159radius = 5area = pi * radius ** 2print("Area:", area)
Calculates the area of a circle using floating-point arithmetic.
Example 2: Rounding and Formatting
value = 10 / 3print(round(value, 2)) # Output: 3.33print(f"{value:.4f}") # Output: 3.3333
Shows how to round and format float values for presentation.
Example 3: Scientific Notation
mass = 5.97e24 # Earth's mass in kilogramsspeed = 3.0e8 # Speed of light in m/senergy = mass * speed ** 2print("E =", energy)
Demonstrates how to use exponential notation for large or small values.
Strings in Python
In Python, strings are one of the most commonly used data types. They are used to store and manipulate textual data, such as names, messages, or any sequence of characters. Python strings are powerful, immutable, and come with a rich set of built-in methods.
What is a String
A string in Python is a sequence of Unicode characters enclosed in single quotes (
'...'
), double quotes (
"..."
), or triple quotes (
'''...'''
or
"""..."""
).
Syntax:
single = 'Hello'double = "World"multiline = """This isa multi-line string."""
String Characteristics
- Immutable: Once created, strings cannot be modified.
- Indexed: Each character has a position (starting from 0).
- Iterable: Strings can be looped over.
- Supports Slicing: You can extract substrings.
Example 1: Basic String Operations
greeting = "Hello"name = "Alice"message = greeting + ", " + name + "!"print(message)
This demonstrates concatenation of multiple strings to form a complete message. The
+
operator joins strings.
Example 2: Indexing and Slicing
word = "Python"print(word[0]) # First characterprint(word[-1]) # Last characterprint(word[1:4]) # Characters from index 1 to 3
-
word[0]accesses the first character. -
word[-1]accesses the last character using negative indexing. -
word[1:4]slices from index 1 up to (but not including) index 4.
Example 3: String Methods
text = " Learn Python Programming "print(text.strip()) # Removes leading/trailing whitespaceprint(text.lower()) # Converts to lowercaseprint(text.upper()) # Converts to uppercaseprint(text.replace("Python", "Java")) # Replaces substring
Python provides many string methods for transforming and cleaning text.
Example 4: Multiline Strings and Escaping
message = """Hello,This is a multilinestring with line breaks."""print(message) escaped = "He said, \"Python is awesome!\""print(escaped)
- Triple quotes allow multiline string literals.
- Backslashes (
\) are used to escape special characters like\",\n,\t.
Example 5: String Formatting
Python supports multiple string formatting methods:
Using
f-strings
(Recommended in Python 3.6+)
name = "Alice"print(f"Welcome, {name}!")
Using
.format()
method
print("Welcome, {}!".format("Alice"))
Using
%
formatting (older style)
print("Welcome, %s!" % "Alice")
Example 6: Iterating Over a String
language = "Python"for char in language: print(char)
Each character in a string can be accessed using a
for
loop because strings are iterable.
Commonly Used String Methods
| Method | Description |
|---|---|
str.lower()
| Converts string to lowercase |
str.upper()
| Converts string to uppercase |
str.strip()
| Removes whitespace from both ends |
str.replace()
| Replaces a substring with another |
str.split()
| Splits string into a list by separator |
str.join()
| Joins elements of an iterable with string |
str.startswith()
| Checks if string starts with a prefix |
str.endswith()
| Checks if string ends with a suffix |
String Immutability
Strings are immutable, meaning operations return new strings and do not alter the original.
name = "Alice"new_name = name.replace("A", "E")print(name) # Aliceprint(new_name) # Elice
name
remains unchanged. A new string is returned.
Summary
- Strings in Python are immutable sequences of characters.
- They support indexing, slicing, iteration, and a rich set of methods.
- Triple quotes allow for multiline strings.
- Formatting can be done using
f-strings,.format(), or%.
In the next article, we’ll explore Lists in Python — dynamic arrays that support mutable operations and heterogeneous data.
What is a String?
A string in Python is a sequence of Unicode characters enclosed in single quotes (
'...'
), double quotes (
"..."
), or triple quotes (
'''...'''
or
"""..."""
).
Syntax:
single = 'Hello'double = "World"multiline = """This isa multi-line string."""
Arithmetic Operators in Python
Arithmetic operators in Python are used to perform mathematical operations between numerical values. These operators work with both integers and floating-point numbers.
List of Arithmetic Operators
| Operator | Symbol | Description |
|---|---|---|
| Addition |
+
| Adds two operands |
| Subtraction |
-
| Subtracts the right operand from the left |
| Multiplication |
*
| Multiplies two operands |
| Division |
/
| Divides left operand by right (float result) |
| Floor Division |
//
| Divides and returns the integer quotient |
| Modulus |
%
| Returns remainder after division |
| Exponentiation |
**
| Raises the first operand to the power of the second |
1. Addition (+)
Adds two numbers.
a = 10b = 5print("Sum:", a + b)
Sum: 15
Example 2: Adding Floats
x = 3.5y = 4.5print("Result:", x + y)
Result: 8.0
Example 3: Adding Mixed Types
num = 7decimal = 2.3print("Total:", num + decimal)
Total: 9.3
2. Subtraction (-)
Subtracts the right operand from the left.
a = 15b = 8print("Difference:", a - b)
Difference: 7
3. Multiplication (*)
Multiplies two operands.
a = 6b = 4print("Product:", a * b)
Product: 24
4. Division (/)
Divides left operand by right. Result is always a float.
a = 20b = 4print("Quotient:", a / b)
Quotient: 5.0
Example 2: Dividing Floats
x = 7.5y = 2.5print("Result:", x / y)
Result: 3.0
Example 3: Division with Result < 1
num = 3den = 10print("Result:", num / den)
Result: 0.3
5. Floor Division (//)
Divides and returns the integer part (quotient).
a = 15b = 4print("Floor Division:", a // b)
Floor Division: 3
Example 2: With Negative Numbers
x = -10y = 3print("Result:", x // y)
Result: -4
Example 3: With Floats
num = 7.5den = 2print("Result:", num // den)
Result: 3.0
6. Modulus (%)
Returns remainder after division.
a = 17b = 5print("Remainder:", a % b)
Remainder: 2
Example 2: Even or Odd Check
num = 8print("Is Even?", num % 2 == 0)
Is Even? True
Example 3: Negative Modulus
x = -13y = 4print("Result:", x % y)
Result: 3
7. Exponentiation (**)
Raises first operand to the power of the second.
a = 2b = 3print("Power:", a ** b)
Power: 8
Example 2: Square Root
num = 16print("Square Root:", num ** 0.5)
Square Root: 4.0
Example 3: Negative Exponents
base = 2exp = -2print("Result:", base ** exp)
Result: 0.25
Comparison Operators
Comparison operators (also called relational operators) are used to compare two values. The result is always a boolean value:
True
or
False
.
These operators are essential for decision-making, such as in
if
statements and loops.
List of Comparison Operators
| Operator | Symbol | Description |
|---|---|---|
| Equal |
==
| Returns True if both operands are equal |
| Not Equal |
!=
| Returns True if operands are not equal |
| Greater Than |
>
| Returns True if left operand is greater |
| Less Than |
<
| Returns True if left operand is lesser |
| Greater Than or Equal |
>=
| True if left operand is greater or equal |
| Less Than or Equal |
<=
| True if left operand is less or equal |
1. Equal To (==)
Checks if two values are equal.
a = 10b = 10print(a == b)
True
Example 2: Comparing Strings
name1 = "Alice"name2 = "alice"print(name1 == name2)
False
Example 3: Comparing Different Types
num = 10text = "10"print(num == text)
False
2. Not Equal (!=)
Checks if two values are not equal.
x = 7y = 5print(x != y)
True
Example 2: Strings Comparison
first = "Python"second = "Java"print(first != second)
True
Example 3: Comparing Different Types
a = 5b = "5"print(a != b)
3. Greater Than (>)
Checks if the left operand is greater than the right.
a = 15b = 10print(a > b)
True
Example 2: Floats Comparison
x = 7.8y = 9.2print(x > y)
False
Example 3: Negative Numbers
a = -2b = -5print(a > b)
True
4. Less Than (<)
Checks if the left operand is less than the right.
x = 8y = 12print(x < y)
True
Example 2: Floats Comparison
x = 2.5y = 1.5print(x < y)
False
Example 3: Negative Numbers
a = -10b = -1print(a < b)
True
5. Greater Than or Equal (>=)
Checks if the left operand is greater than or equal to the right.
a = 10b = 10print(a >= b)
True
Example 2: Floats
x = 5.0y = 4.9print(x >= y)
True
Example 3: Negative Comparison
a = -2b = -3print(a >= b)
True
Logical Operators in Python
Logical operators are used to combine multiple conditions (expressions) and produce a boolean result:
True
or
False
.
Logical operators play a key role in decision-making and are commonly used in
if
statements and loops.
List of Logical Operators
| Operator | Keyword | Description |
|---|---|---|
| and |
and
| True if both conditions are True |
| or |
or
| True if at least one condition is True |
| not |
not
| Reverses the result: True becomes False, False becomes True |
1. and Operator
eturns
True
only if both conditions are
True
.
a = 5b = 10print(a < 10 and b > 5)
True
Example 2: One Condition False
x = 3y = 7print(x > 5 and y < 10)
False
Example 3: Combining String and Number
name = "Alice"age = 20print(name == "Alice" and age >= 18)
True
Explanation:
- If either side of the
andoperator isFalse, the whole expression evaluates toFalse.
2. or Operator
Returns
True
if at least one condition is
True
.
a = 5b = 10print(a > 10 or b > 5)
True
Example 2: Both Conditions False
x = 1y = 2print(x > 5 or y > 10)
False
Example 3: Multiple Conditions
status = "inactive"score = 80print(status == "active" or score >= 75)
True
Explanation:
- If any one condition is
True, the entire expression evaluates toTrue.
3. not Operator
Reverses the boolean result:
True
becomes
False
, and vice versa.
is_logged_in = Trueprint(not is_logged_in)
False
Example 2: Used with
and
x = 10y = 5print(not (x < 20 and y > 2))
False
Example 3: Used with
or
is_admin = Falseis_user = Trueprint(not (is_admin or is_user))
False
Explanation:
- The
notoperator inverts the result of an expression. - Very useful for conditions where you want to check for the opposite.
Combining Logical Operators
You can combine
and
,
or
, and
not
in a single expression:
age = 25is_student = Falseprint((age >= 18 and age <= 30) or is_student)
True
Assignment Operators
Assignment operators are used to assign values to variables. In addition to simple assignment (
=
), Python provides compound assignment operators that combine arithmetic or bitwise operations with assignment — helping to write more concise and readable code.
List of Assignment Operators
| Operator | Symbol | Description |
|---|---|---|
| Simple Assignment |
=
| Assigns the right-hand value to the left-hand variable |
| Add and Assign |
+=
| Adds right operand to left operand and assigns the result |
| Subtract and Assign |
-=
| Subtracts right operand from left operand and assigns the result |
| Multiply and Assign |
*=
| Multiplies left operand by right operand and assigns the result |
| Divide and Assign |
/=
| Divides left operand by right operand and assigns the result |
| Modulus and Assign |
%=
| Performs modulus operation and assigns the result |
| Floor Divide and Assign |
//=
| Floor division and assign |
| Exponent and Assign |
**=
| Raises left operand to power of right operand and assigns result |
1. Simple Assignment (=)
Assigns the value of the right-hand side to the left-hand variable.
x = 10y = 5print("x =", x)print("y =", y)
x = 10y = 5
Explanation:
- The
=operator assigns the value on the right to the variable on the left. - It does not compare; it stores the value.
2. Add and Assign (+=)
Adds a value to the variable and updates the variable.
count = 5count += 3print("count =", count)
count = 8
Example 2: String Concatenation with
+=
greeting = "Hello"greeting += " World"print(greeting)
Hello World
Example 3: Using in Loops
total = 0for i in range(1, 6): total += iprint(total)
15
Conditional Statements
In any programming language, decision-making is key. Python provides conditional statements to let you run code based on conditions.
These are essential when you want your program to respond differently depending on user input, state, or data.
Types of Conditional Statements in Python
-
ifstatement -
if-elsestatement -
if-elif-elseladder - Nested
ifstatements
Basic Syntax of if Statement
if condition: # block of code
Explanation:
- The
conditionis an expression that evaluates to True or False. - If True, the indented block of code runs.
- If False, Python skips the block.
Example 1: Simple if Statement
age = 18if age >= 18: print("You are eligible to vote.")
You are eligible to vote.
Example 2: if-else Statement
age = 16if age >= 18: print("You are eligible to vote.")else: print("You are not eligible to vote.")
You are not eligible to vote.
Explanation:
- The
elseblock runs if theifcondition is False. - This provides a clear alternative action.
Example 3: if-elif-else Ladder
marks = 85 if marks >= 90: print("Grade: A")elif marks >= 80: print("Grade: B")elif marks >= 70: print("Grade: C")else: print("Grade: F")
Grade: B
Explanation:
- The
elif(short for else if) allows multiple conditions to be checked. - The first True condition will run.
- If no condition is True,
elseblock executes.
Loops in Python – for Loop
The
for
loop in Python is used to iterate over a sequence of elements such as lists, strings, tuples, ranges, dictionaries, and sets.
It is ideal when you know how many elements you want to process — and it’s one of the most commonly used loop structures in Python.
Basic Syntax of for Loop
for item in sequence: # block of code
Explanation:
- The loop extracts one item at a time from the sequence.
- The item is assigned to the variable
item. - The loop runs until all elements have been processed.
Example 1: Iterating Over a List
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit)
I like appleI like bananaI like cherry
Explanation:
- The loop automatically picks one element from the list on each iteration.
- Very readable and simple to use with sequences like lists.
Example 2: Iterating Over a String
word = "Python" for char in word: print(char)
Python
Explanation:
- Strings are sequences of characters — the
forloop processes them one character at a time.
Example 3: Using range() for Numeric Sequences
for i in range(1, 6): print("Number:", i)
Number: 1Number: 2Number: 3Number: 4Number: 5
Explanation:
-
range(start, stop)generates a sequence of numbers fromstarttostop - 1. - Perfect for loops that count or repeat a set number of times.
Loops in Python – while Loop
A loop allows you to execute a block of code repeatedly as long as a certain condition is met.
The
while
loop in Python is used when you want to repeat an action an unknown number of times — until a condition becomes false.
Basic Syntax of while Loop
while condition: # block of code
Explanation:
- The
conditionis checked before each iteration. - If True, the block is executed.
- If False, the loop ends.
Example 1: Simple Counter
count = 1 while count <= 5: print("Count:", count) count += 1
Count: 1Count: 2Count: 3Count: 4Count: 5
Explanation:
- The loop runs until
countexceeds 5. -
count += 1increments the counter each time.
Defining Functions in Python
A function is a reusable block of code that performs a specific task. Functions help you:
- Organize code
- Avoid repetition
- Improve readability and maintainability
In Python, you define a function using the
def
keyword.
Basic Syntax of a Function
def function_name(): # block of code
Explanation:
-
def– keyword used to define a function. -
function_name– name of your function. - Parentheses
()may include parameters. - The indented block is the function body — it contains the code to execute.
Example 1: Defining and Calling a Function
def greet(): print("Hello, welcome to Python!") greet()
Hello, welcome to Python!
Explanation:
- The function
greet()is defined first. - Calling
greet()executes the function.
Example 2: Function With One Parameter
def greet(name): print("Hello,", name) greet("Alice")
Hello, Alice
Explanation:
- The function accepts a parameter called
name. - When called, the argument
"Alice"is passed in.
Example 3: Function With Multiple Parameters
def add(a, b): print("Sum is:", a + b) add(5, 7)
Sum is: 12
Explanation:
- Functions can take multiple parameters.
- You can pass any number of arguments (that match the parameter list).
Example 4: Function With Default Parameter
def greet(name="Guest"): print("Hello,", name) greet()greet("Bob")
Hello, GuestHello, Bob
Explanation:
- Default parameters provide a default value if no argument is passed.
- Useful for optional arguments.
Example 5: Function Returning a Value
def square(n): return n * n result = square(4)print("Square is:", result)
Square is: 16
Explanation:
- The
returnstatement sends a value back to the caller. - You can assign the returned value to a variable.
Example 6: Function Documentation (Docstring)
def greet(): """This function prints a greeting message.""" print("Hello!") print(greet.__doc__)greet()
This function prints a greeting message.Hello!
Explanation:
- The first string inside a function is a docstring.
- It documents what the function does.
- You can access it with
function_name.__doc__.
Why Use Functions?
| Benefit | Description |
|---|---|
| Code Reuse | Write once, use many times |
| Modularity | Break complex problems into simpler parts |
| Clarity | Improve code readability |
| Maintainability | Easier to update, test, and debug |
| Avoid Repetition | No need to duplicate code |
Summary
- Functions in Python are defined with
def. - Functions may have parameters and may return values.
- They improve code structure and reusability.
- Use docstrings to document what your function does.
Arguments and Parameters in Python
Functions often need input values to perform a task. These inputs are called:
- Parameters → the names listed in the function definition.
- Arguments → the actual values passed when calling the function.
Understanding how arguments work is key to writing flexible and reusable functions.
Defining Parameters
def greet(name): print("Hello,", name) greet("Alice") # Argument "Alice" passed
Hello, Alice
Explanation:
-
name→ parameter. -
"Alice"→ argument. - When called, the argument is passed to the parameter.
Multiple Parameters
def add(a, b): print("Sum:", a + b) add(3, 5)
Sum: 8
Explanation:
- You can define any number of parameters.
- Arguments must match the parameter order.
Parameters of Different Data Types
def display(name, age, is_member): print("Name:", name) print("Age:", age) print("Member:", is_member) display("John", 30, True)
Name: JohnAge: 30Member: True
Explanation:
- Parameters can be of any type: string, integer, boolean, float, list, etc.
List as Argument
def show_items(items): for item in items: print("Item:", item) show_items(["apple", "banana", "cherry"])
Item: appleItem: bananaItem: cherry
Explanation:
- You can pass lists and other collections as arguments.
Tuple as Argument
def print_coords(coords): x, y = coords print("X:", x) print("Y:", y) print_coords((10, 20))
X: 10Y: 20
Explanation:
- Tuples can be passed to functions and unpacked.
Dictionary as Argument
def print_user(info): for key, value in info.items(): print(f"{key}: {value}") print_user({"name": "Emma", "age": 25, "city": "Paris"})
name: Emmaage: 25city: Paris
Explanation:
- Dictionaries allow passing structured data to functions.
Summary
- Functions can accept different kinds of arguments: positional, keyword, default,
*args, and**kwargs. - You can pass any type of data: string, int, float, list, tuple, dictionary, etc.
- These techniques give you flexibility and power when designing functions.
Return Values in Python Functions
In Python, a function can send back a value to the part of the program that called it. This is done using the
return
statement.
Functions that return values are more flexible because the caller can use the result in further calculations or logic.
Basic Syntax of
return
def function_name(): return value
-
returnends the function and sends a value back to the caller. - If no
returnis used, the function returnsNoneby default.
Example 1: Returning a Single Value
def add(a, b): return a + b result = add(3, 5)print("Sum is:", result)
Sum is: 8
Explanation:
- The function returns the result of
a + b. - The caller stores this value in
result.
Example 2: Returning a String
def greet(name): return f"Hello, {name}" message = greet("Alice")print(message)
Hello, Alice
Explanation:
- The function builds a string and returns it.
- The caller receives and prints the string.
Example 3: Returning Multiple Values (Tuple)
def get_stats(numbers): return min(numbers), max(numbers), sum(numbers) low, high, total = get_stats([4, 7, 1, 9])print("Min:", low)print("Max:", high)print("Sum:", total)
Min: 1Max: 9Sum: 21
Explanation:
- A function can return multiple values as a tuple.
- The caller can unpack the values.
Example 4: Returning a List
def squares(n): return [i * i for i in range(1, n + 1)] print("Squares:", squares(5))
Squares: [1, 4, 9, 16, 25]
Explanation:
- The function returns a list of computed values.
Example 5: Returning a Dictionary
def person_info(name, age): return {"name": name, "age": age} info = person_info("John", 30)print(info)
{'name': 'John', 'age': 30}
Explanation:
- The function returns a dictionary of key-value pairs.
Example 6: Returning None
def log_message(message): print("LOG:", message) result = log_message("Processing started")print(result)
LOG: Processing startedNone
Explanation:
- If a function does not return anything, Python returns
None. - Useful for side-effect functions (logging, writing to file, etc.).
Why Use Return Values?
| Reason | Benefit |
|---|---|
| Reuse results | Value can be passed around your program |
| Flexible function behavior | Different callers can use the result differently |
| Separate calculation from display | Functions focus on computing, not printing |
| Compose multiple functions | Functions can call each other and build pipelines |
Summary
- The
returnstatement sends back values from a function. - You can return any type: string, int, float, list, tuple, dict, None.
- Functions can return multiple values.
- Returning values allows your code to be modular, flexible, and reusable.
Variable Scope in Python
Scope refers to the region of a program where a variable is visible and accessible.
In Python, variable scope is critical to writing clear, bug-free, and maintainable code. You need to understand where your variables exist — and when they are created or destroyed.
Types of Variable Scope
| Scope Type | Where Defined | Lifetime |
|---|---|---|
| Local | Inside a function | Exists only during function execution |
| Global | Outside any function | Exists as long as program runs |
| Enclosing | Inside enclosing function (for nested functions) | As long as enclosing function exists |
| Built-in | Defined by Python | Always available (e.g.,
len
,
range
) |
Local Scope Example
def my_func(): x = 10 # Local variable print("Inside function, x =", x) my_func()# print(x) # This would cause an error
Inside function, x = 10
Explanation:
-
xis local tomy_func. - It cannot be accessed outside the function.
Global Scope Example
x = 50 # Global variable def my_func(): print("Inside function, x =", x) my_func()print("Outside function, x =", x)
Inside function, x = 50Outside function, x = 50
Explanation:
-
xis declared outside the function — so it is global. - It is accessible inside and outside the function.
Modifying Global Variable Inside a Function
x = 5 def change_global(): global x x = 100 change_global()print("x =", x)
x = 100
Explanation:
-
globalkeyword tells Python thatxinside the function refers to the global variable.
Enclosing Scope (Nested Functions)
def outer(): x = "outer value" def inner(): print("Inner:", x) inner() outer()
Inner: outer value
Explanation:
- Inner function
inner()can access variables from its enclosing functionouter().
Best Practices for Scope
| Guideline | Why |
|---|---|
| Use local variables when possible | Avoid unintended side effects |
| Limit use of global variables | Keeps functions self-contained |
| Use clear variable names per scope | Improves readability |
| Understand LEGB rule | Prevents scope-related bugs |
Summary
- Scope defines where a variable exists in your program.
- Use
localscope inside functions; limit global variables. - Python resolves names using the LEGB rule.
- Nested functions can access enclosing variables.
- Built-in functions are always accessible.
Lambda Functions
In Python, a lambda function is a small, anonymous function defined using the
lambda
keyword. Unlike regular functions created with
def
, lambda functions are typically used for simple, one-line operations.
Lambda functions are useful when you need a quick function — especially when passing functions as arguments.
Syntax of Lambda Function
lambda arguments: expression
-
lambda— keyword to define the anonymous function. -
arguments— one or more parameters. -
expression— a single expression whose result is returned.
Lambda functions do not contain multiple statements or complex logic — they must be written in one line.
Example 1: Basic Lambda Function
square = lambda x: x * xprint(square(5))
25
Explanation:
-
lambda x: x * xdefines an anonymous function that returns the square ofx. - The function is assigned to
squareand called like a normal function.
Example 2: Lambda with Two Parameters
add = lambda a, b: a + bprint(add(3, 7))
10
Explanation:
- Lambda function with two arguments:
aandb. - Returns their sum.
Example 3: Using Lambda with map()
nums = [1, 2, 3, 4]squares = list(map(lambda x: x * x, nums))print(squares)
[1, 4, 9, 16]
Explanation:
-
map()applies the lambda function to every element in the list. - The result is a list of squared numbers.
Example 4: Using Lambda with filter()
nums = [1, 2, 3, 4, 5, 6]even = list(filter(lambda x: x % 2 == 0, nums))print(even)
[2, 4, 6]
Explanation:
-
filter()applies the lambda function to each element. - It returns only those elements that satisfy the condition.
Example 5: Lambda Inside Sorted
names = ["Alice", "Bob", "Charlie", "David"]sorted_names = sorted(names, key=lambda name: len(name))print(sorted_names)
['Bob', 'Alice', 'David', 'Charlie']
Explanation:
- Lambda function used as
keyinsorted(). - Sorts names based on their length.
Example 6: Lambda with Default Parameter
greet = lambda name="Guest": f"Hello, {name}"print(greet())print(greet("Alice"))
Hello, GuestHello, Alice
Explanation:
- You can use default parameters in a lambda function.
When to Use Lambda Functions
| Use Case | Example |
|---|---|
| Simple, one-line transformations |
map()
,
filter()
,
sorted()
|
| Passing function as argument | Higher-order functions |
| Quick, throwaway functions | Short anonymous operations |
| Avoiding full function definition | Save lines of code when logic is simple |
Limitations of Lambda Functions
- Can only contain one expression (no statements, no multiple lines).
- Cannot include assignments or complex logic.
- Readability may suffer if overused for complex operations.
Summary
- Lambda functions are anonymous, one-line functions created with
lambda. - They are ideal for short, simple tasks.
- Commonly used with
map(),filter(), andsorted(). - For complex logic, prefer regular functions using
def.
Recursion in Python
Recursion is a programming technique where a function calls itself to solve a problem.
A recursive function breaks down a large problem into smaller sub-problems — often resulting in simple and elegant solutions.
However, recursion must be designed carefully to avoid infinite loops and excessive memory usage.
Key Concepts
- Base Case — The simplest scenario that ends the recursion.
- Recursive Case — The part where the function calls itself with modified input.
Syntax of a Recursive Function
def recursive_function(parameters): if base_case_condition: return result else: return recursive_function(modified_parameters)
Example 1: Factorial (n!)
Factorial of
n
→
n! = n * (n - 1) * (n - 2) * ... * 1
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) print(factorial(5))
120
Explanation:
- Base case:
factorial(1) = 1 - Recursive case:
n * factorial(n-1)
Example 2: Fibonacci Sequence
Fibonacci:
0, 1, 1, 2, 3, 5, 8, ...
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(6))
8
Explanation:
- Base cases:
fibonacci(0) = 0,fibonacci(1) = 1 - Recursive case:
fibonacci(n-1) + fibonacci(n-2)
Example 4: Reverse a String
def reverse_string(s): if len(s) == 0: return "" else: return s[-1] + reverse_string(s[:-1]) print(reverse_string("python"))
nohtyp
Explanation:
- Base case: Empty string returns
"". - Recursive case: Last character + reverse of remaining string.
How Recursion Works Internally
Every recursive call creates a new frame in the call stack.
Steps:
- Function calls itself → Stack grows.
- Reaches base case → Stops recursion.
- Stack unwinds → Each frame returns its value.
Summary
- Recursion is a function calling itself to solve smaller sub-problems.
- Requires a base case and a recursive case.
- Suitable for problems with a naturally recursive structure.
- Must be used carefully to avoid excessive stack usage.
Importing Modules in Python
A module is a file containing Python definitions and code — typically
.py
files. Modules allow you to:
Organize your code Reuse code across projects Access Python’s built-in modules Use external libraries
To access a module, you use the
import
statement.
Syntax of Import
import module_name
Or:
import module_name as alias
Or:
from module_name import specific_function_or_class