0% found this document useful (0 votes)
2 views21 pages

Python Notes With Code Examples and Flow Charts-By Madhusudhan Raju

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Python Notes With Code Examples and Flow Charts-By Madhusudhan Raju

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

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

"Python is not just a language; it’s a powerful


tool that bridges the gap between creativity and
logic, enabling developers to bring their ideas to
life with simplicity and elegance."

---- Madhu Raj

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:

1. Visit the official Python website: python.org.

2. Download the appropriate installer for your operating system (Windows, macOS, or Linux).

3. Run the installer and follow the installation instructions.


Make sure to check the option Add Python to PATH during installation.

4. After installation, you can verify that Python is installed correctly by opening the terminal/command
prompt and typing:

python

python --version

Check 'Add Verify with


Visit Download Complete Ready to
Run installer Python to 'python --
python.org installer installation use Python
PATH' version'

Fig: This should display the installed version of Python.

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.

Your First Python Program


Here's how you can write and execute your first Python program:

1. Open your editor (e.g., IDLE or VS Code).

2. Type the following code:

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.

Linting Python Code


Linting is the process of analyzing code to detect potential errors, stylistic issues, or areas that could be
optimized. Linting tools for Python include:
5
Pylint: A popular Python linting tool that checks for errors and enforces coding standards.

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.

Formatting Python Code


Formatting is essential for maintaining clean, readable code. Python follows PEP 8, a style guide that
dictates:

Use 4 spaces per indentation level (no tabs).

Limit lines to 79 characters.

Use blank lines to separate functions and classes.

Use descriptive variable and function names.

Most IDEs have auto-formatting features, such as the black formatter, which automatically formats
Python code according to PEP 8 guidelines.

Running Python Code


There are multiple ways to run Python code:

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:

Fig: Running Python Code

6
Python Implementations
CPython: The default and most commonly used implementation of Python, written in C.

PyPy: A faster Python interpreter that uses Just-In-Time (JIT) compilation.

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.

How Python Code is Executed


Python code is executed in two steps:

1. Compilation: Python source code is compiled into bytecode, which is a lower-level representation of
the code.

2. Interpretation: The bytecode is executed by the Python interpreter.

Python Bytecode Python Execution


Source Code Compilation Interpreter Output

Fig: How Python Code is Executed

2. Variables and Data Types

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:

They must start with a letter (a-z, A-Z) or an underscore (_).

They can contain letters, numbers, and underscores.

7
They cannot contain spaces or special characters like !, @, etc.

Python is case-sensitive, so age and Age are treated as different variables.

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

\' : Single quote

\" : Double quote

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 provides many built-in string methods:

.lower() : Converts string to lowercase.

.upper() : Converts string to uppercase.

.replace(old, new) : Replaces occurrences of old with new.

.strip() : Removes whitespace from both ends of the string.

.split() : Splits the string into a list of substrings.

Example of string methods:

python

text = " Hello, World! "


print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.strip()) # "Hello, World!"
print(text.replace("World", "Python")) # " Hello, Python! "
print("apple,banana,orange".split(",")) # ['apple', 'banana', 'orange']

3. Working with Numbers

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.

Exponentiation (**): Raises a number to the power of another.


Floor division (//): Divides and rounds down to the nearest integer.

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]

Example of numeric operations:

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:

int() : Converts a value to an integer.

float() : Converts a value to a float.

str() : Converts a value to a string.

Example:

python

x = int(3.5) # Converts 3.5 to 3


y = float(5) # Converts 5 to 5.0
z = str(10) # Converts 10 to "10"
print(x, y, z) # 3 5.0 10

4. Operators and Conditionals

Comparison Operators
Comparison operators are used to compare values:

== : Equal to

!= : Not equal to

> : Greater than

< : Less than

>= : Greater than or equal to

<= : Less than or equal to

Example of comparison operators:

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

Example of conditional statements:

python

age = 18

if age < 13:


print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")

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

result = "Yes" if condition else "No"

Example of ternary operator:

python

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status) # "Adult"

Logical Operators
and : Returns True if both conditions are true.

or : Returns True if at least one condition is true.

not : Negates a condition.

Example of logical operators:

python

a, b = True, False

print(a and b) # False


print(a or b) # True
print(not a) # 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

# The second condition isn't evaluated because the first is False


result = False and print_and_return_true()
print(result) # False, and the function wasn't called

Chaining Comparison Operators


You can chain comparison operators in a single expression:

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.

Example of iterating through different iterables:

python

# Iterating through a list


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# Iterating through a string


for char in "Python":
print(char)

# Iterating through a tuple


coordinates = (1, 2, 3)
for coord in coordinates:
print(coord)

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

Exercise: Calculate Factorial


Write a program to calculate the factorial of a number using loops:

python

n = 5
factorial = 1
for i in range(1, n+1):
factorial *= i

17
print(f"The factorial of {n} is {factorial}")

Output:

The factorial of 5 is 120

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}!")

To call the function:

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

def describe_person(name, age, city):


print(f"{name} is {age} years old and lives in {city}.")

# Positional arguments (order matters)


describe_person("John", 30, "New York")

# Keyword arguments (order doesn't matter)


describe_person(age=25, city="Paris", name="Alice")

# Mix of positional and keyword arguments


# (positional must come before keyword)
describe_person("Bob", city="London", age=35)

Types of Functions
Void Functions: Functions that don't return any value.

Return Functions: Functions that return a value using the return statement:

python

# Void function (no return value)


def greet(name):
print(f"Hello, {name}!")

# Return function
def add(x, y):
return x + y

# Using the return value


result = add(5, 3)
print(result) # 8

Keyword Arguments
Keyword arguments allow you to specify the value of a function's parameter by name:

python

def greet(name, message="Hello"):


print(f"{message}, {name}!")

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

def power(base, exponent=2):


return base ** exponent

print(power(5)) # 25 (5^2, using default exponent)


print(power(5, 3)) # 125 (5^3, overriding default)

Variable-Length Arguments (*args)


*args allows you to pass a variable number of arguments to a function. These arguments are stored in a
tuple:

python

def print_args(*args):
for arg in args:
print(arg)

print_args("apple", "banana", "cherry")

Output:

apple
banana
cherry

Variable-Length Keyword Arguments (**kwargs)


**kwargs allows you to pass a variable number of keyword arguments to a function. These arguments are
stored in a dictionary:

python

def print_kwargs(**kwargs):
20
for key, value in kwargs.items():
print(f"{key}: {value}")

print_kwargs(name="Alice", age=30, city="New York")

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]

A --> E[Types of Arguments]


E --> F[Positional Arguments: Passed by position]
E --> G[Keyword Arguments: Passed by name]
E --> H[Default Arguments: Have predefined values]
E --> I[Variable Arguments: *args, **kwargs]

21

You might also like