Python Notes With Code Examples and Flow Charts-By Madhusudhan Raju
Python Notes With Code Examples and Flow Charts-By Madhusudhan Raju
Contents
1. Introduction to Python .......................................................................................................................................................................... 4
What is Python? ........................................................................................................................................................................................... 4
Installing Python .......................................................................................................................................................................................... 4
Python Interpreter ....................................................................................................................................................................................... 4
Code Editors .................................................................................................................................................................................................. 5
Your First Python Program ........................................................................................................................................................................ 5
Python Extension ......................................................................................................................................................................................... 5
Linting Python Code ................................................................................................................................................................................... 5
Formatting Python Code ........................................................................................................................................................................... 6
Running Python Code ................................................................................................................................................................................ 6
Fig: Running Python Code ........................................................................................................................................................................ 6
Python Implementations ........................................................................................................................................................................... 7
How Python Code is Executed................................................................................................................................................................. 7
Fig: How Python Code is Executed .................................................................................................................................................... 7
2. Variables and Data Types ...................................................................................................................................................................... 7
Variables ......................................................................................................................................................................................................... 7
Variable Names............................................................................................................................................................................................. 7
Strings ............................................................................................................................................................................................................. 8
Escape Sequences ....................................................................................................................................................................................... 8
Formatted Strings ........................................................................................................................................................................................ 8
String Methods ............................................................................................................................................................................................. 9
Example of string methods:.................................................................................................................................................................. 9
3. Working with Numbers ......................................................................................................................................................................... 9
Numbers ......................................................................................................................................................................................................... 9
Working with Numbers ............................................................................................................................................................................10
Example of numeric operations: .......................................................................................................................................................10
Type Conversion.........................................................................................................................................................................................11
4. Operators and Conditionals...............................................................................................................................................................11
Comparison Operators ............................................................................................................................................................................11
Example of comparison operators: ..................................................................................................................................................11
Conditional Statements ...........................................................................................................................................................................12
Example of conditional statements:.................................................................................................................................................12
Ternary Operator........................................................................................................................................................................................13
Example of ternary operator:.............................................................................................................................................................13
Logical Operators ......................................................................................................................................................................................13
Example of logical operators:.............................................................................................................................................................13
Short-circuit Evaluations ..........................................................................................................................................................................13
Chaining Comparison Operators ..........................................................................................................................................................14
2
5. Loops ........................................................................................................................................................................................................14
For Loops......................................................................................................................................................................................................14
Output: .....................................................................................................................................................................................................14
For..Else .........................................................................................................................................................................................................14
Output: .....................................................................................................................................................................................................15
Nested Loops ..............................................................................................................................................................................................15
Iterables ........................................................................................................................................................................................................16
Example of iterating through different iterables: .........................................................................................................................16
While Loops .................................................................................................................................................................................................16
Output: .....................................................................................................................................................................................................16
Infinite Loops...............................................................................................................................................................................................17
Output: .....................................................................................................................................................................................................17
Exercise: Calculate Factorial.....................................................................................................................................................................17
Output: .....................................................................................................................................................................................................18
6. Functions .................................................................................................................................................................................................18
Defining Functions ....................................................................................................................................................................................18
Output: .....................................................................................................................................................................................................18
Arguments ...................................................................................................................................................................................................18
Example of different ways to pass arguments: .............................................................................................................................19
Types of Functions .....................................................................................................................................................................................19
Keyword Arguments .................................................................................................................................................................................19
Default Arguments ....................................................................................................................................................................................20
Variable-Length Arguments (*args) ......................................................................................................................................................20
Output: .....................................................................................................................................................................................................20
Variable-Length Keyword Arguments (**kwargs).............................................................................................................................20
Output: .....................................................................................................................................................................................................21
3
Comprehensive Python Notes with Code Examples and Flow
Charts
1. Introduction to Python
What is Python?
Python is a high-level, interpreted programming language designed with an emphasis on code
readability and simplicity. It was created by Guido van Rossum and first released in 1991. Python is widely
used for various applications such as web development, data analysis, artificial intelligence, scientific
computing, and automation.
Python supports multiple programming paradigms, including procedural, object-oriented, and functional
programming, making it versatile for different tasks. The language has a large community, extensive
libraries, and frameworks, which help developers quickly implement solutions.
Installing Python
To install Python on your system:
2. Download the appropriate installer for your operating system (Windows, macOS, or Linux).
4. After installation, you can verify that Python is installed correctly by opening the terminal/command
prompt and typing:
python
python --version
Python Interpreter
The Python interpreter is the program that reads and executes Python code. It converts Python code into
machine code, line by line, and executes it. There are two main ways to interact with the Python
4
interpreter:
Interactive Mode: Allows you to enter and execute Python commands one line at a time.
Script Mode: Allows you to write your Python code in a file with a .py extension and execute it all at
once.
Code Editors
Several code editors and Integrated Development Environments (IDEs) are available for Python
development:
IDLE: Python's default editor that comes with the installation. It is simple and easy to use for
beginners.
Visual Studio Code (VS Code): A powerful, lightweight code editor with support for Python through
extensions.
PyCharm: A comprehensive IDE specifically designed for Python development. It offers advanced
features like debugging, testing, and more.
Jupyter Notebook: Popular among data scientists and researchers, it allows interactive coding with
visual outputs and documentation.
python
print("Hello, World!")
3. Save the file with a .py extension and run it. You should see the output:
Hello, World!
Python Extension
Python files have the .py extension. This extension tells the operating system that the file contains Python
code and can be executed by the Python interpreter.
Flake8: Another linting tool that checks code for PEP 8 compliance and potential errors.
Pyflakes: A fast, lightweight linter that checks for errors in Python code.
Most IDEs have auto-formatting features, such as the black formatter, which automatically formats
Python code according to PEP 8 guidelines.
1. Interactive Mode: Open the terminal/command prompt and type python to enter the interactive
shell. Type Python code directly to see the output.
2. Script Mode: Save the code in a .py file and run it via the command:
6
Python Implementations
CPython: The default and most commonly used implementation of Python, written in C.
Jython: Python running on the Java Virtual Machine (JVM), which allows you to integrate Python with
Java applications.
IronPython: Python running on the .NET framework, enabling Python code to interact with .NET
libraries.
1. Compilation: Python source code is compiled into bytecode, which is a lower-level representation of
the code.
Variables
Variables in Python are used to store data. A variable is created when it is assigned a value:
python
age = 25
Python uses dynamic typing, meaning that you don't need to declare the type of the variable. The
interpreter determines the type based on the value assigned.
Variable Names
Variable names in Python follow these rules:
7
They cannot contain spaces or special characters like !, @, etc.
mermaid
flowchart TD
A[Variable Name Rules] --> B[Must start with letter or underscore]
A --> C[Can contain letters, numbers, underscores]
A --> D[Cannot contain spaces or special characters]
A --> E[Case-sensitive: 'age' ≠ 'Age']
Strings
Strings are sequences of characters enclosed in quotes. Python supports both single and double quotes:
python
string1 = "Hello"
string2 = 'World'
Strings in Python are immutable, meaning they cannot be changed once created.
Escape Sequences
Escape sequences allow special characters to be included in strings:
\n : Newline
\t : Tab
\\ : Backslash
Example:
python
message = "Hello\nWorld"
Formatted Strings
Formatted strings allow you to embed expressions or variables inside strings. This is done using f-strings
8
(introduced in Python 3.6):
python
name = "John"
message = f"Hello, {name}!"
String Methods
python
Numbers
Python supports integers, floating-point numbers, and complex numbers. Python automatically chooses
the correct type based on the value provided:
python
x = 10 # Integer
y = 3.14 # Float
z = 1 + 2j # Complex number
9
Working with Numbers
Python supports arithmetic operations such as:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%): Returns the remainder of division.
mermaid
flowchart TD
A[Numeric Operations] --> B[Addition: a + b]
A --> C[Subtraction: a - b]
A --> D[Multiplication: a * b]
A --> E[Division: a / b]
A --> F[Modulus: a % b]
A --> G[Exponentiation: a ** b]
A --> H[Floor Division: a // b]
python
a, b = 10, 3
# Basic operations
print(a + b) # 13 (Addition)
print(a - b) # 7 (Subtraction)
print(a * b) # 30 (Multiplication)
print(a / b) # 3.3333... (Division)
print(a % b) # 1 (Modulus - remainder of division)
print(a ** b) # 1000 (Exponentiation - 10 raised to power 3)
print(a // b) # 3 (Floor division - division rounded down)
10
Type Conversion
You can convert between different data types using built-in functions:
Example:
python
Comparison Operators
Comparison operators are used to compare values:
== : Equal to
!= : Not equal to
python
a, b = 10, 5
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= b) # True
11
print(a <= b) # False
Conditional Statements
Conditional statements allow you to execute code based on certain conditions:
python
if condition:
# Block of code
elif condition:
# Block of code
else:
# Block of code
python
age = 18
mermaid
flowchart TD
A[Start] --> B{Condition 1}
B -->|True| C[Execute Code Block 1]
B -->|False| D{Condition 2}
D -->|True| E[Execute Code Block 2]
D -->|False| F[Execute Else Block]
C --> G[Continue Program]
E --> G
F --> G
12
Ternary Operator
The ternary operator is a shorthand for if-else statements:
python
python
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # "Adult"
Logical Operators
and : Returns True if both conditions are true.
python
a, b = True, False
Short-circuit Evaluations
Logical operators in Python use short-circuit evaluation, meaning they stop evaluating as soon as the
result is determined. For example, with and, if the first condition is False, the second condition won't be
evaluated.
python
# Short-circuit example
def print_and_return_true():
print("This function was called")
13
return True
python
x = 5
# The following are equivalent
print(1 < x < 10) # True
print(1 < x and x < 10) # True
5. Loops
For Loops
A for loop is used to iterate over a sequence (like a list, string, or range). It allows you to execute a block
of code multiple times:
python
for i in range(5):
print(i)
Output:
0
1
2
3
4
For..Else
The else block can follow a for loop. It will execute if the loop completes without hitting a break
statement:
14
python
for i in range(3):
print(i)
else:
print("Loop completed")
Output:
0
1
2
Loop completed
mermaid
flowchart TD
A[Start] --> B[Initialize Loop]
B --> C{Is there a next item?}
C -->|Yes| D[Process item]
D --> E{Break statement?}
E -->|Yes| F[Exit Loop]
E -->|No| C
C -->|No| G[Execute else block]
G --> H[Continue Program]
F --> H
Nested Loops
A nested loop is a loop inside another loop. This is useful when dealing with multidimensional data
structures:
python
for i in range(3):
for j in range(2):
print(f"({i}, {j})")
Output:
(0, 0)
(0, 1)
15
(1, 0)
(1, 1)
(2, 0)
(2, 1)
Iterables
An iterable is any object that can be looped over, such as a list, tuple, string, or range.
python
While Loops
A while loop executes as long as a condition is True:
python
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
16
4
mermaid
flowchart TD
A[Start] --> B{Condition is True?}
B -->|Yes| C[Execute Code Block]
C --> D{Break statement?}
D -->|Yes| E[Exit Loop]
D -->|No| B
B -->|No| F[Continue Program]
E --> F
Infinite Loops
An infinite loop occurs if the condition in a while loop is always true. This can be stopped with a break
statement:
python
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
Output:
0
1
2
3
4
python
n = 5
factorial = 1
for i in range(1, n+1):
factorial *= i
17
print(f"The factorial of {n} is {factorial}")
Output:
6. Functions
Defining Functions
Functions are used to group code that performs a specific task. Functions are defined using the def
keyword:
python
def greet(name):
print(f"Hello, {name}!")
python
greet("Alice")
Output:
Hello, Alice!
mermaid
flowchart TD
A[Define Function] --> B[Function is called]
B --> C[Arguments passed to function]
C --> D[Execute function body]
D --> E{Return statement?}
E -->|Yes| F[Return value]
E -->|No| G[Return None]
F --> H[Continue Program]
G --> H
Arguments
Arguments are values passed to a function. They can be positional (passed in the order they appear) or
keyword-based (assigned by name).
18
Example of different ways to pass arguments:
python
Types of Functions
Void Functions: Functions that don't return any value.
Return Functions: Functions that return a value using the return statement:
python
# Return function
def add(x, y):
return x + y
Keyword Arguments
Keyword arguments allow you to specify the value of a function's parameter by name:
python
19
greet("Alice") # "Hello, Alice!"
greet("Bob", message="Hi") # "Hi, Bob!"
Default Arguments
Default arguments are used when a parameter isn't passed. They have a predefined value:
python
python
def print_args(*args):
for arg in args:
print(arg)
Output:
apple
banana
cherry
python
def print_kwargs(**kwargs):
20
for key, value in kwargs.items():
print(f"{key}: {value}")
Output:
name: Alice
age: 30
city: New York
mermaid
flowchart TD
A[Python Functions] --> B[Types of Functions]
B --> C[Void Functions: No return value]
B --> D[Return Functions: Return a value]
21