0% found this document useful (0 votes)
7 views32 pages

Python Unit I Notes

The document discusses the significance of programming for engineers, highlighting its role in problem-solving, automation, data analysis, modeling, and optimization. It emphasizes the importance of Python as a versatile programming language with a rich history and extensive applications in engineering and science. Additionally, it provides guidance on setting up Python IDEs, understanding syntax and indentation rules, and best practices for coding.

Uploaded by

Vishnuvardan
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)
7 views32 pages

Python Unit I Notes

The document discusses the significance of programming for engineers, highlighting its role in problem-solving, automation, data analysis, modeling, and optimization. It emphasizes the importance of Python as a versatile programming language with a rich history and extensive applications in engineering and science. Additionally, it provides guidance on setting up Python IDEs, understanding syntax and indentation rules, and best practices for coding.

Uploaded by

Vishnuvardan
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

Lecture 1: Importance of Programming for Engineers

Programming has become a foundational competency for modern engineers across all
disciplines. It enhances analytical capability, improves productivity, and enables engineers to
design, simulate, optimize, and manage complex systems with precision.
1. Problem Solving and Logical Thinking
Programming trains engineers to decompose complex engineering problems into structured,
logical steps. This systematic approach directly aligns with engineering design methodology—
problem definition, constraint identification, solution formulation, and validation.
2. Automation and Efficiency
Repetitive engineering tasks such as calculations, report generation, data cleaning, and design
checks can be automated through programs. This reduces human error, saves time, and allows
engineers to focus on higher-level decision-making and innovation.
3. Data Analysis and Interpretation
Engineering decisions increasingly rely on large datasets (experimental data, sensor outputs,
monitoring records). Programming enables engineers to:
• Process and analyze large volumes of data
• Apply statistical and numerical methods
• Visualize trends, anomalies, and system behavior
This capability is essential in fields such as hydrology, structural monitoring,
manufacturing, and energy systems.
4. Modeling and Simulation
Programming supports the development and customization of mathematical and physical models.
Engineers can simulate real-world systems—such as fluid flow, structural response, thermal
behavior, or electrical networks—before physical implementation, reducing cost and risk.
5. Design Optimization
Through programming, engineers can implement optimization algorithms to identify best-
performing designs under multiple constraints (cost, safety, sustainability, efficiency). This is
particularly valuable in civil, mechanical, electrical, and environmental engineering applications.
6. Integration with Modern Engineering Tools
Most advanced engineering software and platforms (CAD, GIS, numerical solvers, machine
learning frameworks) provide scripting or programming interfaces. Engineers with programming
skills can:
• Customize workflows
• Extend software capabilities
• Integrate multiple tools into a unified system
7. Interdisciplinary Collaboration
Programming acts as a common language across engineering, science, and data disciplines. It
enables effective collaboration with data scientists, researchers, and software professionals,
which is critical for multidisciplinary projects and research.
8. Innovation and Emerging Technologies
Emerging domains—such as artificial intelligence, digital twins, Internet of Things (IoT), smart
infrastructure, and sustainable systems—are heavily programming-driven. Engineers who can
code are better positioned to innovate and adapt to future technological demands.
9. Career Competitiveness
Programming skills significantly enhance employability. Engineers with coding proficiency are
better suited for roles in:
• Research and development
• Design and analysis
• Automation and smart systems
• Consultancy and decision-support services
10. Lifelong Learning and Adaptability
Programming empowers engineers to independently learn new tools, methods, and technologies.
This adaptability is critical in a rapidly evolving engineering landscape.
Lecture 2: Introduction to Python: History & Popularity
1. Introduction to Python
Python is a high-level, interpreted, general-purpose programming language known for its
simplicity, readability, and versatility. It emphasizes clear syntax and logical structure, making it
highly suitable for beginners as well as professionals in engineering, science, and industry.
Python supports multiple programming paradigms, including:
• Procedural programming
• Object-Oriented programming
• Functional programming
Its design philosophy focuses on code readability and developer productivity.
2. History of Python
• Python was created by Guido van Rossum in the late 1980s.
• Development began at Centrum Wiskunde & Informatica (CWI), Netherlands, as a
successor to the ABC programming language.
• Python was officially released in 1991.
Key Historical Milestones
• 1991 – Python 0.9.0
Included core features such as classes, functions, exception handling, and core data types.
• 2000 – Python 2.0
Introduced list comprehensions and garbage collection.
• 2010 – Python 2.7
Final major release of Python 2 (support ended in 2020).
• 2008 – Python 3.0
Designed to remove inconsistencies and improve performance, Unicode support, and
security.
• Present
Python 3 continues to evolve with performance improvements and expanded libraries.
Important Note:
Python 3 is the standard and recommended version today. Python 2 is obsolete and no longer
supported.
3. Why the Name “Python”?
The name Python was inspired by the British comedy show “Monty Python’s Flying Circus”,
not by the snake. This influence is reflected in Python’s documentation and examples, which
often contain humorous references.
4. Popularity of Python
Python is consistently ranked among the top programming languages in the world.
Reasons for Python’s Popularity
a) Simple and Readable Syntax
• Uses English-like keywords
• Minimal syntax rules
• Reduced code length compared to C, C++, or Java
This makes Python easy to learn and maintain.
b) Open Source and Free
• Python is freely available
• Supported by a large global developer community
• Continuous improvement through community contributions
c) Extensive Standard Library
Python comes with a rich standard library for:
• File handling
• Mathematics and statistics
• Data processing
• Networking and system operations
d) Wide Range of Applications
Python is widely used in:
• Engineering analysis and simulation
• Data science and machine learning
• Web development
• Automation and scripting
• Scientific research
• Artificial intelligence and IoT
e) Strong Industry and Academic Adoption
Python is used by:
• Universities for teaching programming
• Research institutions for modeling and data analysis
• Industries for automation, analytics, and product development
5. Python in Engineering and Science
Python has become a preferred language for engineers due to:
• Availability of numerical and scientific libraries
• Ease of integration with simulation tools
• Capability to handle large datasets
• Support for visualization and reporting
It enables engineers to move from problem formulation → computation → visualization →
decision-making within a single environment.
6. Community and Ecosystem
Python has one of the largest programming communities worldwide.
• Regular global conferences (PyCon)
• Extensive online documentation and tutorials
• Thousands of third-party libraries and frameworks
This ecosystem ensures long-term stability and continuous growth.
Lecture 3: Setting up IDEs for Python: IDLE, VS Code, and Jupyter
This section gives you a practical, engineering-student-friendly setup workflow for three
common environments. Use IDLE for quick basics, VS Code for serious programming projects,
and Jupyter for data analysis, computations, and reports.
1) IDLE (Built-in Python IDE)
What it is
IDLE is the default IDE that typically comes with Python (especially on Windows). It is
lightweight and good for beginners to understand syntax, indentation, and basic execution.
Installation / Setup
If you installed Python from [Link]:
• IDLE is usually installed automatically.
Windows
1. Install Python (ensure “Add Python to PATH” is checked during installation).
2. Open Start Menu → IDLE (Python 3.x).
3. Verify:
o In the IDLE shell, type:
▪ print("Hello, Python")
o Press Enter.
macOS
• Python from [Link] includes IDLE, but macOS system Python can be confusing.
• Preferred: install Python 3 from [Link] and run IDLE from Applications or
Spotlight.
Linux (Ubuntu/Debian)
• Install:
o sudo apt install idle3
• Run:
o idle3
How to run a script in IDLE
1. File → New File
2. Write code
3. Save as [Link]
4. Run → Run Module (or press F5)
When IDLE is appropriate
• Learning basics (variables, if, loops, functions)
• Quick testing without project structure
• Low-resource systems
2) Visual Studio Code (VS Code)
What it is
VS Code is a modern editor with extensions that behaves like a powerful IDE. It is the best
general-purpose choice for engineering programming: clean project structure, debugging,
terminal, Git, and tool integration.
Step-by-step setup (recommended)
Step A — Install Python
• Install Python 3.x from [Link]
• During installation (Windows), check:
o Add Python to PATH
Verify in terminal:
• Windows (Command Prompt):
o python --version
• macOS/Linux:
o python3 --version
Step B — Install VS Code
• Install VS Code (official build)
Step C — Install the Python extension
1. Open VS Code
2. Go to Extensions (left sidebar)
3. Search “Python” (by Microsoft)
4. Install it
(Optional but strongly useful)
• Pylance (often installed automatically)
• Jupyter extension (for notebooks)
• Black Formatter (code formatting)
Step D — Select interpreter
1. Press Ctrl+Shift+P
2. Search: Python: Select Interpreter
3. Choose your installed Python 3.x
You must do this correctly; otherwise VS Code runs the wrong Python.
Step E — Create and run a program
1. Create a folder (example: python_basics)
2. Open folder in VS Code (File → Open Folder)
3. Create [Link]
4. Write:
o print("Hello from VS Code")
5. Run using either:
o Run ▶ button (top-right), or
o Terminal:
▪ python [Link] (Windows)
▪ python3 [Link] (macOS/Linux)
Recommended: Use a virtual environment (professional habit)
Inside your project folder terminal:
Windows
• python -m venv .venv
• .venv\Scripts\activate
macOS/Linux
• python3 -m venv .venv
• source .venv/bin/activate
Then install packages only inside the venv:
• pip install numpy pandas matplotlib
When VS Code is appropriate
• Semester-long coding work
• Projects with multiple files/modules
• Debugging and version control
• Professional engineering workflows
3) Jupyter Notebook / JupyterLab
What it is
Jupyter is an interactive notebook environment. It is ideal for:
• Data analysis
• Numerical modeling and plotting
• Step-by-step computation + explanation (lab records, reports)
You write code in “cells” and execute cell-by-cell.
Best installation routes
Option 1 (Simple): Install via pip
1. Open terminal (Command Prompt / PowerShell / Terminal)
2. Install:
o pip install notebook
o or better:
o pip install jupyterlab
Run:
• Classic Notebook:
o jupyter notebook
• JupyterLab:
o jupyter lab
A browser page will open.
Option 2 (Very common in academia): Anaconda
Anaconda bundles Python + Jupyter + scientific libraries.
• Good when you want fewer dependency problems.
After installation:
• Open Anaconda Navigator
• Launch JupyterLab or Notebook
Create and use notebooks
• New notebook → select Python 3 kernel
• Example:
o import numpy as np
o import [Link] as plt
Good practice: use the same venv kernel inside Jupyter
If you use .venv in VS Code projects, install an IPython kernel:
• Activate venv
• pip install ipykernel
• python -m ipykernel install --user --name=myprojectenv --display-name "Python
(myprojectenv)"
Then select that kernel in Jupyter/VS Code notebook.
When Jupyter is appropriate
• Labs, data exploration, graphs
• Hydrology/groundwater time series analysis
• Demonstrations and teaching (stepwise results)

4) Quick Comparison
Tool Best for Strengths Limitations
Poor for large projects, limited
IDLE Beginners Simple, comes with Python
tooling
VS Most engineering Debugging, project workflow,
Needs initial setup discipline
Code coding extensions
Data + computation Visualization + narrative + Not ideal for large software-
Jupyter
notebooks code style projects

5) Recommended workflow for Engineering Students


• Start with IDLE (first 1–2 weeks): syntax, indentation, basics.
• Shift to VS Code (main tool): all assignments, projects, clean folder structure.
• Use Jupyter for: plots, data analysis, modeling notebooks, report-like outputs.
6) Common setup issues (and fixes)
Issue A: “python is not recognized” (Windows)
• Python not added to PATH.
• Fix: reinstall Python and check Add Python to PATH, or add PATH manually.
Issue B: VS Code runs the wrong Python
• Fix: Python: Select Interpreter and choose correct version/venv.
Issue C: pip installs but imports fail
• You installed packages into one Python but running another.
• Fix: confirm interpreter and run:
o python -m pip install package_name
Issue D: Jupyter kernel mismatch
• Fix: install ipykernel in the same environment and select the right kernel.
Lecture 4: Python Syntax, Indentation Rules, and Statements
This topic is fundamental. If students misunderstand this, everything that follows (loops,
functions, classes) will collapse. Python is strict, explicit, and unforgiving about structure—by
design.
1. Python Syntax – Core Principles
What is Syntax?
Syntax is the set of rules that defines how a Python program must be written so that the
interpreter can understand and execute it.
In Python:
• Syntax is simple
• Syntax is readable
• Syntax is close to English
• Syntax is less cluttered (no braces {}, no semicolons ;)
Key Characteristics of Python Syntax
1. Case-sensitive language
o Value ≠ value
2. No semicolons required at line end
3. Statements are executed line by line
4. Blocks are defined by indentation, not braces
Example
x = 10
y = 20
print(x + y)
2. Python Indentation Rules (CRITICAL CONCEPT)
What is Indentation?
Indentation refers to the spaces at the beginning of a line that define a block of code.
In Python:
• Indentation is mandatory
• Indentation represents logical grouping
• Incorrect indentation causes Indentation Error
Standard Indentation Rule
• Use 4 spaces per indentation level (PEP 8 standard)
• Do not mix tabs and spaces
Why Python Uses Indentation
• Enforces clean, readable code
• Prevents ambiguous block definitions
• Forces logical clarity
Correct Indentation Example
if marks >= 50:
print("Pass")
print("Eligible for next level")
Incorrect Indentation Example
if marks >= 50:
print("Pass") # ERROR
Result:
IndentationError: expected an indented block
Indentation in Loops
for i in range(3):
print(i)
print("Loop running")
print("Loop ended")
Explanation:
• First two print statements → inside loop
• Last print → outside loop
3. Python Statements
What is a Statement?
A statement is an instruction that the Python interpreter can execute.
Every complete line of code is generally a statement.
Types of Python Statements
1. Simple Statements
Executed in a single line.
Examples:
x=5
name = "Python"
print(x)
Includes:
• Assignment statements
• Input/output statements
• Import statements
2. Compound Statements
Contain a header line and a block of code.
Structure:
keyword condition:
indented block
Examples:
• if
• for
• while
• def
• class
Example:
if temperature > 30:
print("Hot day")
4. Common Python Statements Explained
Assignment Statement
a = 10
b = 20
• Assigns value on right to variable on left
• Uses single equals =
Conditional Statement (if)
if age >= 18:
print("Eligible to vote")
• Colon : is mandatory
• Indentation defines condition scope
Loop Statement (for)
for i in range(5):
print(i)
• Executes block repeatedly
• Indentation defines loop body
Input Statement
x = input("Enter a number: ")
• Always returns string
• Type conversion required if numeric input is needed
Output Statement
print("Hello World")
5. Colon (:) Rule in Python
A colon must be used after:
• if
• for
• while
• def
• class
Example:
def add(a, b):
return a + b
Missing colon = SyntaxError
6. Statements vs Expressions (Exam-Favorite)
Expression
• Produces a value
5+3
a*b
Statement
• Performs an action
x=5
print(x)
7. Common Syntax and Indentation Errors
Error Cause
IndentationError Missing or incorrect indentation
SyntaxError Missing colon, incorrect structure
TabError Mixing tabs and spaces
Unexpected indent Extra spaces before a line
8. Best Practices (Must Teach Explicitly)
1. Always use 4 spaces for indentation
2. Never mix tabs and spaces
3. Use meaningful variable names
4. Keep one statement per line
5. Align indentation visually
9. Summary (Board-Worthy Points)
• Python syntax is simple and readable
• Python uses indentation instead of braces
• Indentation is mandatory and logical
• Statements can be simple or compound
• Colon (:) and indentation together define code blocks
• Improper syntax or indentation leads to runtime failure
Lecture 5: Comments and Documentation Strings (Docstrings) in Python
This topic is not cosmetic. Poor commenting and documentation reflect poor thinking and
make code unmaintainable. Python explicitly supports documentation as a first-class feature—
engineers are expected to use it correctly.
1. Comments in Python
What is a Comment?
A comment is a line of text in a program that is ignored by the Python interpreter. It is written
to explain the code for human readers.
Comments improve:
• Code readability
• Maintainability
• Collaboration
• Debugging and review
Types of Comments in Python
1. Single-line Comment
Written using the hash symbol #.
# This is a single-line comment
x = 10 # Assigning value to x
• Anything after # on that line is ignored
• Can be placed:
o On a separate line
o At the end of a statement
2. Multi-line Comments (Conventional)
Python does not have a true multi-line comment syntax.
Instead, multiple single-line comments are used.
# This program calculates
# the area of a circle
# using a fixed radius
This is the correct way to write multi-line comments.
When to Use Comments (Engineering Discipline)
Use comments to:
• Explain why something is done (not what is obvious)
• Clarify complex logic or assumptions
• State units, constraints, or limitations
• Mark TODOs or warnings
Do not use comments to:
• Explain trivial code
• Repeat the statement in English
• Hide bad or unclear code
Bad comment
x = x + 1 # increment x by 1
Good comment
x = x + 1 # Increment counter for convergence check
2. Documentation Strings (Docstrings)
What is a Docstring?
A docstring is a string literal used to document:
• Modules
• Functions
• Classes
• Methods
Docstrings are written using triple quotes:
• """ docstring """ (recommended)
• ''' docstring '''
Unlike comments, docstrings are stored in memory and can be accessed at runtime.
Why Docstrings Are Important
• Used by help() function
• Used by documentation tools
• Provide official program documentation
• Mandatory in professional and academic code
In short:
Comments are for developers.
Docstrings are for users and tools.
3. Types of Docstrings
1. Module Docstring
Placed at the top of a .py file.
"""
This module performs basic groundwater recharge calculations.
Author: Vishnuvardan
Date: 2026-01-02
"""
Purpose:
• Describes what the module does
• May include author, version, and usage notes
2. Function Docstring
Placed immediately after the function definition.
def area_of_circle(radius):
"""
Calculates the area of a circle.

Parameters:
radius (float): Radius of the circle in meters

Returns:
float: Area of the circle in square meters
"""
return 3.14159 * radius * radius
3. Class Docstring
Placed immediately after the class definition.
class Reservoir:
"""
Represents a surface water reservoir.

Attributes:
capacity (float): Storage capacity in cubic meters
"""
4. Accessing Docstrings
Using help()
help(area_of_circle)
Using __doc__
print(area_of_circle.__doc__)
This is why docstrings are powerful—they are part of the program, not ignored text.
5. Docstrings vs Comments (Exam-Favourite Table)
Aspect Comments Docstrings
Symbol # """ """
Interpreter ignores Yes No
Stored in memory No Yes
Used by help() No Yes
Purpose Explain code Document code
Scope Line-based Module / class / function
6. Formatting Standards (Professional Expectation)
A good docstring should answer:
1. What does this code do?
2. What are the inputs?
3. What are the outputs?
4. Are there assumptions or units?
Indentation and clarity matter.
7. Common Mistakes (You Must Explicitly Warn Students)
1. Using """ """ as comments randomly
2. Writing docstrings far from definitions
3. Mixing comments and docstrings incorrectly
4. Writing no documentation for functions
5. Over-commenting simple code
8. Best Practices (Non-Negotiable)
1. Use comments sparingly and purposefully
2. Always write docstrings for:
o Functions
o Classes
o Modules
3. Use triple double quotes """ """
4. Keep docstrings concise but complete
5. Treat documentation as part of the code, not optional text
9. Summary (Exam-Ready Points)
• Comments explain code and are ignored by Python
• Single-line comments use #
• Python has no true multi-line comments
• Docstrings use triple quotes
• Docstrings document modules, functions, and classes
• Docstrings are accessible using help() and __doc__
• Proper documentation is a professional engineering requirement
Lecture 6: Core Data Types in Python: Integers, Floats, and Booleans
Core data types form the numerical and logical foundation of Python programming. Every
engineering computation—whether structural analysis, hydrological modeling, or data
processing—ultimately relies on these three types. If these are weak, all higher concepts fail.
1. Integer Data Type (int)
Definition
An integer is a whole number without any decimal part. Integers can be:
• Positive
• Negative
• Zero
Python supports integers of unlimited size, constrained only by system memory.
Syntax and Examples
a = 10
b = -25
c=0
Check the type:
print(type(a))
Output:
<class 'int'>
Integer Operations
x = 15
y=4

print(x + y) # Addition → 19
print(x - y) # Subtraction → 11
print(x * y) # Multiplication → 60
print(x // y) # Floor division → 3
print(x % y) # Modulus → 3
Engineering Relevance
• Counting iterations and loops
• Indexing arrays and datasets
• Discrete quantities (number of samples, nodes, steps)
2. Floating-Point Data Type (float)
Definition
A float represents a real number with a decimal point. It is used when precision beyond whole
numbers is required.
Syntax and Examples
x = 3.14
y = -0.005
z = 10.0
Type check:
print(type(x))
Output:
<class 'float'>
Scientific Notation
Python supports exponential notation:
a = 3.5e3 # 3500.0
b = 2e-4 # 0.0002
Float Operations
a = 7.5
b = 2.0

print(a / b) # 3.75
print(a * b) # 15.0
Precision Warning (Must Be Taught)
print(0.1 + 0.2)
Output:
0.30000000000000004
Reason:
• Floats are stored in binary approximation
• This is normal behavior, not an error
Engineering Relevance
• Measurements (length, discharge, rainfall, velocity)
• Model parameters and coefficients
• Scientific calculations and simulations
3. Boolean Data Type (bool)
Definition
A Boolean represents one of two values:
• True
• False
Booleans are fundamental to decision-making and control flow.
Syntax and Examples
is_valid = True
is_complete = False
Type check:
print(type(is_valid))
Output:
<class 'bool'>
Boolean from Comparisons
x = 10
y = 20

print(x > y) # False


print(x == y) # False
print(x < y) # True
Logical Operators
a = True
b = False

print(a and b) # False


print(a or b) # True
print(not a) # False
Boolean from Numeric Values
bool(0) # False
bool(1) # True
bool(-5) # True
Rule:
• 0 → False
• Any non-zero number → True
4. Type Conversion (Very Important)
Explicit Type Conversion
x = int(3.7) # 3
y = float(5) # 5.0
z = bool(0) # False
Input Always Returns String
value = input("Enter a number: ")
print(type(value)) # <class 'str'>
Correct usage:
value = int(input("Enter a number: "))
Failure to convert types is a common exam and lab mistake.
5. Comparison Summary Table
Data Type Keyword Example Purpose
Integer int 10, -3 Counting, indexing
Float float 3.14, 2.0 Measurements, precision
Boolean bool True, False Decision-making
6. Common Errors (Explicitly Warn Students)
1. Assuming 5 / 2 gives integer → It gives float (2.5)
2. Forgetting to convert input() to int/float
3. Comparing floats using == without tolerance
4. Treating True and False as strings ("True" is not boolean)
7. Best Practices (Engineering Discipline)
1. Use int for counts, indices, loops
2. Use float for physical quantities
3. Use bool only for logical conditions
4. Always verify data types using type()
5. Convert inputs explicitly—never assume
8. Summary (Exam-Ready Points)
• int stores whole numbers
• float stores decimal and real numbers
• bool stores True or False
• Python supports automatic and explicit type conversion
• input() always returns a string
• Core data types are the backbone of all computations
Lecture 7: Type Conversion in Python: Explicit and Implicit
Type conversion is a core operational concept in Python. Engineers routinely combine integers,
floating-point values, and user inputs; if type conversion is misunderstood, programs will either
fail or—worse—produce incorrect results silently.
1. What is Type Conversion?
Type conversion is the process of converting a value from one data type to another.
Python supports two forms:
1. Implicit Type Conversion (Automatic)
2. Explicit Type Conversion (Type Casting)
2. Implicit Type Conversion (Automatic)
Definition
Implicit conversion is performed automatically by Python when it converts a smaller or
compatible data type into a larger or more general type without data loss.
Python does this to maintain precision.
Example 1: Integer to Float
a = 10 # int
b = 2.5 # float

c=a+b
print(c)
print(type(c))
Output:
12.5
<class 'float'>
Explanation:
• int → automatically converted to float
• Result is float
Example 2: Boolean in Arithmetic
x = True
y = False

print(x + 5) # 6
print(y + 5) # 5
Reason:
• True → 1
• False → 0
Rules of Implicit Conversion
• bool → int → float
• Python never implicitly converts string to number
• Conversion happens only when it is safe and logical
3. Explicit Type Conversion (Type Casting)
Definition
Explicit conversion is manually performed by the programmer using built-in functions.
Common casting functions:
• int()
• float()
• bool()
• str()
Example 1: Float to Integer
x = 7.8
y = int(x)

print(y) #7
print(type(y)) # <class 'int'>
Important:
• int() truncates, it does not round
Example 2: Integer to Float
a=5
b = float(a)

print(b) # 5.0
Example 3: String to Number (CRITICAL)
value = input("Enter a number: ")
result = value + 10
Error:
TypeError: can only concatenate str (not "int") to str
✔ Correct:
value = int(input("Enter a number: "))
result = value + 10
Example 4: Boolean Conversion
print(bool(0)) # False
print(bool(10)) # True
print(bool("")) # False
print(bool("Hi")) # True
Rules:
• 0, 0.0, "" → False
• Everything else → True
4. Conversion Table (Exam-Focused)
From To Method Result
int float float(5) 5.0
float int int(5.9) 5
str int int("10") 10
str float float("3.14") 3.14
int bool bool(0) False
bool int int(True) 1
5. Invalid Conversions (Must Be Stated)
int("abc") # ValueError
float("10a") # ValueError
int("3.5") # ValueError
Reason:
• String must represent a valid numeric literal
6. Explicit vs Implicit Conversion (Comparison)
Aspect Implicit Explicit
Done by Python Programmer
Control No Full
Data loss No Possible
Example 5 + 2.5 int(3.7)
Risk Low High if careless
7. Best Practices (Engineering Discipline)
1. Never rely on implicit conversion for input data
2. Always convert input() explicitly
3. Avoid implicit logic in critical calculations
4. Check data types using type()
5. Document conversions clearly in scientific code
8. Common Student Mistakes
1. Forgetting int() or float() on input
2. Expecting int() to round values
3. Comparing strings with numbers
4. Assuming Python converts "10" to 10 automatically
9. Summary (Exam-Ready Points)
• Type conversion changes one data type into another
• Python supports implicit and explicit conversion
• Implicit conversion is automatic and safe
• Explicit conversion is manual and controlled
• input() always returns a string
• Improper type conversion causes runtime error
Lecture 8: Variables and Assignment Statements in Python
Variables and assignment statements are the basic building blocks of any Python program.
Every computation, model, or algorithm begins with assigning values to variables. Weak
understanding here guarantees errors later.
1. What is a Variable?
A variable is a named reference to a value stored in memory.
In Python, variables are created automatically at the time of assignment.
Key Characteristics
• No need to declare data type explicitly
• Type is determined at runtime
• Variable name acts as a label for stored data
Example
x = 10
name = "Python"
pi = 3.14
Here:
• x → integer
• name → string
• pi → float
2. Assignment Statement
Definition
An assignment statement assigns a value (right-hand side) to a variable (left-hand side) using
the assignment operator =.
General Syntax
variable_name = value
Example
radius = 5
area = 3.14159 * radius * radius
Important rule:
Right-hand side is evaluated first, then assigned to the left-hand side.
3. Assignment Operator (=) vs Equality Operator (==)
This confusion is extremely common and must be corrected early.
x=5 # Assignment
x == 5 # Comparison
Operator Purpose Meaning
= Assignment Stores value
== Equality test Compares values
Using = in conditions causes syntax errors.
4. Variable Naming Rules (EXAM CRITICAL)
Python enforces strict rules for variable names.
Valid Rules
1. Must start with a letter (a–z, A–Z) or underscore _
2. Cannot start with a number
3. Can contain letters, digits, and underscores
4. No spaces allowed
5. Cannot use Python keywords
Valid Examples
total
_total
marks1
avg_score
Invalid Examples
1value # starts with number
total marks # space not allowed
class # keyword
5. Keywords Cannot Be Variables
Python keywords have predefined meanings.
Example:
if = 10 # ERROR
Use:
if_value = 10
6. Dynamic Typing in Python
Python uses dynamic typing, meaning:
• Variable type can change during execution
Example
x = 10
print(type(x))

x = 3.5
print(type(x))
Output:
<class 'int'>
<class 'float'>
This flexibility is powerful—but dangerous if misused.
7. Multiple Assignment
Python allows assigning values to multiple variables in a single line.
Example
a, b, c = 10, 20, 30
Swapping Variables (No Temporary Variable)
x=5
y = 10

x, y = y, x
Efficient and clean—no other language does this so simply.
8. Same Value to Multiple Variables
x = y = z = 100
All three variables point to the same value.
9. Assignment with Expressions
Assignment can include expressions.
length = 10
width = 5
area = length * width
Python evaluates the expression first, then assigns the result.
10. Augmented Assignment Operators
These combine operation + assignment.
Operator Meaning Example
+= Add and assign x += 1
-= Subtract and assign x -= 1
*= Multiply and assign x *= 2
/= Divide and assign x /= 2
Example:
count = 10
count += 1
Equivalent to:
count = count + 1
11. Common Errors (Explicitly Warn Students)
1. Using == instead of = for assignment
2. Starting variable names with numbers
3. Using keywords as variable names
4. Assuming variable type never changes
5. Forgetting reassignment overwrites old value
12. Best Practices (Engineering Discipline)
1. Use meaningful variable names
2. Follow snake_case naming style
o total_flow_rate
3. Avoid single-letter names except for loops
4. Keep variable scope minimal
5. Do not reuse variables with different meanings
13. Summary (Exam-Ready Points)
• Variables store values in memory
• Assignment uses the = operator
• Python is dynamically typed
• Variable names must follow strict rules
• = is assignment, == is comparison
• Python supports multiple and augmented assignments
Lecture 9: Arithmetic Operators and Expressions in Python
Arithmetic operators are the computational backbone of Python. Every numerical task—
engineering calculations, scientific models, simulations, and data processing—reduces to
operators acting on expressions. Weak fundamentals here guarantee incorrect results later.
1. What is an Arithmetic Operator?
An arithmetic operator performs a mathematical operation on one or more operands (values or
variables).
Operands
• Values or variables on which the operation is performed
Example
result = 10 + 5
• + → operator
• 10, 5 → operands
2. Arithmetic Operators in Python
Operator Name Description Example
+ Addition Adds two values 10 + 5 → 15
- Subtraction Subtracts RHS from LHS 10 - 5 → 5
* Multiplication Multiplies values 10 * 5 → 50
/ Division Always returns float 10 / 4 → 2.5
// Floor Division Quotient without decimal 10 // 4 → 2
% Modulus Remainder 10 % 4 → 2
** Exponentiation Power 2 ** 3 → 8
3. Arithmetic Expressions
Definition
An expression is a combination of:
• Operands (constants, variables)
• Operators
that evaluates to a single value.
Examples
a = 10
b=3

expr1 = a + b
expr2 = a * b - 5
expr3 = (a + b) * 2
4. Division in Python (CRITICAL DIFFERENCE)
True Division /
10 / 4 # 2.5
• Always returns float
• Even when operands are integers
Floor Division //
10 // 4 # 2
• Removes decimal part
• Result type depends on operands
7 // 2 # 3
7.0 // 2 # 3.0
5. Modulus Operator %
Purpose
Returns the remainder after division.
10 % 3 # 1
Common Uses
• Checking even/odd numbers
• Cyclic conditions
• Time-step calculations
Example:
if number % 2 == 0:
print("Even number")
6. Exponentiation Operator **
2 ** 3 # 8
5 ** 2 # 25
Also supports floats:
9 ** 0.5 # 3.0
7. Operator Precedence (Exam-Favourite)
Python follows BODMAS-like precedence.
Precedence Order (High → Low)
1. **
2. *, /, //, %
3. +, -
Example
result = 10 + 2 * 3
Evaluation:
• 2*3=6
• 10 + 6 = 16
To change order:
result = (10 + 2) * 3 # 36
8. Associativity Rule
• ** → Right to Left
• Others → Left to Right
Example:
2 ** 3 ** 2
Evaluation:
2 ** (3 ** 2) = 2 ** 9 = 512
9. Using Variables in Expressions
length = 10
width = 5
area = length * width
Expressions can include:
• Variables
• Constants
• Multiple operators
10. Arithmetic with Mixed Data Types
a=5 # int
b = 2.0 # float

print(a + b) # 7.0
Rule:
• Result becomes float if any operand is float
11. Augmented Arithmetic Expressions
Shortcut operators:
x = 10
x += 5 # 15
x *= 2 # 30
x -= 4 # 26
Equivalent to:
x=x+5
12. Common Student Mistakes (Explicit Warning)
1. Expecting / to give integer result
2. Confusing // and /
3. Forgetting operator precedence
4. Using % incorrectly
5. Writing long expressions without parentheses
13. Best Practices (Engineering Discipline)
1. Use parentheses for clarity
2. Break complex expressions into steps
3. Avoid magic numbers—use variables
4. Check intermediate results
5. Maintain unit consistency in expressions
14. Summary (Exam-Ready Points)
• Arithmetic operators perform mathematical operations
• Python supports + - * / // % **
• / always returns float
• // performs floor division
• % returns remainder
• Expressions evaluate based on precedence and associativity
• Parentheses override precedence
Lecture 10: The Dynamic Typing Model and Reference Counting in Python (CBS)
This topic explains how Python actually works internally. If students think Python variables
behave like C or Java variables, they are already wrong. Python follows a dynamic typing +
object reference model, backed by reference counting–based memory management.
1. Python’s Dynamic Typing Model
What is Dynamic Typing?
In Python, data types are associated with objects, not with variables.
A variable:
• Does not have a fixed type
• Is simply a reference (name) pointing to an object in memory
Key Principle
Variables are labels, not containers.
Example
x = 10
print(type(x)) # int

x = 3.5
print(type(x)) # float
What happened?
• The object 10 (int) was created
• x pointed to it
• Later, x was redirected to a new object 3.5 (float)
The original integer object is unaffected.
2. Variable Assignment = Reference Binding
Assignment does NOT copy values
It binds a name to an object.
a = 10
b=a
Memory logic:
• Object 10 exists once
• Both a and b refer to the same object
Verify Using id()
a = 10
b=a

print(id(a))
print(id(b))
Both IDs will be the same → same object.
Reassignment Changes Reference
b = 20
Now:
• a → 10
• b → 20
The reference is changed, not the original object.
3. Why This Matters (Engineering Reality)
Because of dynamic typing:
• Python is flexible and fast to write
• But careless reassignment can cause logic errors
• Understanding references prevents bugs in:
o Numerical modeling
o Data pipelines
o Scientific simulations
4. Mutability and References (Critical Extension)
Some objects are mutable, some are immutable.
Immutable Objects
• int
• float
• bool
• str
• tuple
These cannot be changed, only replaced.
x = 10
x = x + 1 # creates a new object (11)
Mutable Objects (Preview)
• list
• dict
• set
These can be modified in-place.
This is where reference behavior becomes dangerous if misunderstood.
a = [1, 2]
b=a
[Link](3)

print(a) # [1, 2, 3]
Same object, two references.
5. Reference Counting: Python’s Memory Management Core
What is Reference Counting?
Python tracks:
How many references (names) point to each object
This count is called the reference count.
Basic Rule
• When reference count → 0
• Object becomes eligible for garbage collection
Example
x = 100
y=x
Reference count of object 100 = 2
del x
Reference count = 1
del y
Reference count = 0 → object can be destroyed
6. Visual Mental Model (Must Teach)
x ─┐
├──► [ 10 ] (object in memory)
y ─┘
After del x:
y ───► [ 10 ]
After del y:
(no references) → object removed
7. del Keyword and References
The del statement:
• Deletes the reference
• Not necessarily the object
a=5
del a
If no other references exist:
• Object is removed
If other references exist:
• Object stays alive
8. Why Reference Counting Is Important
Advantages
• Immediate cleanup of unused objects
• Predictable memory behavior
• Efficient for most workloads
Limitation (Advanced Note)
• Reference cycles (objects referring to each other)
• Python uses an additional cyclic garbage collector to handle this
(Do not go deep at UG level—mention only.)
9. Dynamic Typing vs Static Typing (Exam Table)
Aspect Python (Dynamic) C / Java (Static)
Variable type Changes at runtime Fixed at declaration
Type checking Runtime Compile time
Flexibility High Low
Risk of runtime errors Higher Lower
Development speed Faster Slower
10. Common Student Misconceptions (Correct Aggressively)
1. “Variable stores the value”
✔ Variable references the value
2. “Assignment copies data”
✔ Assignment binds a reference
3. “Deleting variable deletes data always”
✔ Object exists until references = 0
4. “Type belongs to variable”
✔ Type belongs to object
11. Best Practices (Engineering Discipline)
1. Be explicit when reassigning variables
2. Avoid reusing variable names with different meanings
3. Understand reference behavior before using mutable objects
4. Use id() for debugging reference-related bugs
5. Write clean, predictable code—do not rely on side effects
12. Summary (Exam-Ready Points)
• Python uses dynamic typing
• Variables are references to objects
• Assignment binds a name to an object
• Objects track how many references point to them
• Reference count reaching zero allows memory cleanup
• del removes references, not objects directly
• Understanding this prevents serious logical errors

You might also like