TYBSC
Semester 6
Applied Component
Advanced Microprocessor, Microcontrollers & Python Programming
Introduction to Python
What is a Program?
A program is a set of instructions written by a programmer that tells a computer how to
perform a specific task. Programs are written in programming languages and executed by the
computer to solve problems, automate work, or perform calculations.
Example tasks:
Calculating student marks
Playing music
Sending emails
Operating ATM machines
The Python Programming Language
Python is a high-level, general-purpose, and easy-to-learn programming language.
It is widely used for:
Web development
Data science & Machine Learning
Automation & scripting
Game Development
Network and Cybersecurity
History of Python
Year Event
1989 Developed by Guido van Rossum in the Netherlands
1991 First public release
2000 Python 2.0 released
2008 Python 3.0 released
Today One of the most popular programming languages
Features of Python
Features of Python (Explained in Detail)
1. Simple and Easy to Learn
Python has a clear and readable syntax similar to English.
Programs require fewer lines of code compared to languages like C or Java.
No need for complex symbols like { } or ;.
This makes Python ideal for:
o Beginners
o Students
o Rapid learning and teaching
Example:
print("Hello World")
2. Free and Open Source
Python is free to download and use.
Its source code is open, meaning anyone can view, modify, and distribute it.
No license cost for:
o Individuals
o Educational institutions
o Companies
Encourages innovation and community contribution.
3. Cross-Platform (Portable)
Python programs can run on multiple operating systems without modification.
Supported platforms include:
o Windows
o macOS
o Linux
This is known as “Write Once, Run Anywhere”.
Benefit:
Same Python code works across different systems.
4. Large Standard Library
Python comes with a huge built-in library.
It provides ready-made modules for:
o File handling
o Mathematics
o Networking
o Date & time
o Operating system interaction
Reduces the need to write code from scratch.
Example modules:
math, os, sys, random, datetime
5. Supports Object-Oriented Programming (OOP)
Python supports OOP concepts such as:
o Classes
o Objects
o Inheritance
o Encapsulation
o Polymorphism
Helps in:
o Code reusability
o Better program structure
o Easier maintenance of large programs
Example:
class Student:
def __init__(self, name):
[Link] = name
6. Extensible and Embeddable
Extensible:
o Python can be extended using languages like C or C++ for performance-
critical tasks.
Embeddable:
o Python can be embedded into other applications as a scripting language.
Used in:
o Game engines
o Embedded systems
o Scientific software
7. Supports GUI Programming
Python can be used to create Graphical User Interface (GUI) applications.
Popular GUI libraries include:
o Tkinter
o PyQt
o wxPython
Used to develop:
o Desktop applications
o Interactive tools
Example:
Creating windows, buttons, menus, dialog boxes.
8. Excellent Community Support
Python has a very large global community.
Plenty of:
o Tutorials
o Documentation
o Discussion forums
o Online courses
Easy to find help for:
o Errors
o New libraries
o Project ideas
Continuous improvement due to community contributions.
Installing Python
Python can be install from the official website:
[Link]
Steps:
1. Download Python installer
2. Run installer → check “Add Python to PATH”
3. Follow installation wizard
4. Verify using terminal/cmd:
5. python --version
Running a Python Program
Python programs can be run in two ways:
1. Interactive Mode
Type commands directly in Python shell:
>>> print("Hello")
Hello
2. Script Mode
Write code in a file with .py extension and run it.
File: [Link]
print("Hello Python")
Run from terminal:
python [Link]
The First Python Program
print("Welcome to Python Programming")
Output:
Welcome to Python Programming
Arithmetic Operators in Python
Arithmetic operators are used to perform mathematical calculations on numeric values
such as integers and floating-point numbers.
1. Addition Operator (+)
Meaning
Adds two operands.
Can also be used to concatenate strings.
Example
5 + 3
Result
8
Explanation
Python adds the values 5 and 3.
Result is an integer because both operands are integers.
2. Subtraction Operator (-)
Meaning
Subtracts the right operand from the left operand.
Example
5 - 3
Result
2
Explanation
Python calculates the difference between 5 and 3.
Order of operands matters in subtraction.
3. Multiplication Operator (*)
Meaning
Multiplies two operands.
Can also be used to repeat strings.
Example
5 * 3
Result
15
Explanation
Python multiplies 5 by 3.
Useful in mathematical calculations and loops.
4. Division Operator (/)
Meaning
Divides the left operand by the right operand.
Always returns a floating-point result, even if division is exact.
Example
6 / 3
Result
2.0
Explanation
Although 6 ÷ 3 = 2, Python returns 2.0.
This ensures consistency in mathematical operations.
5. Floor Division Operator (//)
Meaning
Divides two numbers and returns the largest integer less than or equal to the result.
The decimal part is discarded (floored).
Example
7 // 2
Result
3
Explanation
Actual division: 7 ÷ 2 = 3.5
Floor division removes the decimal part → 3
Useful when working with indices or integer-based logic.
6. Modulus Operator (%)
Meaning
Returns the remainder of a division.
Example
7 % 2
Result
1
Explanation
7 ÷ 2 gives quotient 3 and remainder 1.
Commonly used to:
o Check even/odd numbers
o Cyclic operations
7. Exponentiation Operator (**)
Meaning
Raises the left operand to the power of the right operand.
Example
2 ** 3
Result
8
Explanation
2³ = 2 × 2 × 2 = 8
Used for power, squares, cubes, etc.
Summary Table (Quick Revision)
Operator Name Description Example Result
+ Addition Adds values 5 + 3 8
- Subtraction Subtracts values 5 - 3 2
* Multiplication Multiplies values 5 * 3 15
/ Division Returns float quotient 6 / 3 2.0
// Floor Division Integer quotient 7 // 2 3
% Modulus Remainder 7 % 2 1
** Exponent Power 2 ** 3 8
Key Points
/ always returns a float.
// removes the decimal part.
% gives the remainder.
** is used for powers.
Python handles integers and floats automatically.
Values and Types
Values are basic data items a program works with.
Every value has a type.
Value Type
10 int
12.45 float
"Hello" string
True / False boolean
Check type in Python:
print(type(10))
print(type("Hello"))
Variables, Expressions, and Statements in Python
1. Assignment Statements
An assignment statement assigns a value to a variable.
Syntax:
variable_name = value
Example:
x = 10
name = "Python"
Here, x holds integer value 10, and name holds string "Python".
2. Variable Names and Keywords
Variable Names
Rules for naming variables:
Must start with a letter or underscore
Cannot start with a number
Can contain letters, digits, and underscores
Case-sensitive (age and Age are different)
Valid: student_name, _count, marks1
Invalid: 1name, a-b, total%
Keywords
Keywords are reserved words in Python that cannot be used as variable names.
Examples: if, else, while, for, class, True, False, return, import
3. Expressions and Statements
Expression
A combination of variables, values, and operators that evaluates to a result.
Example:
5 + 3
x + y
Statement
An instruction executed by the interpreter.
Example statements:
x = 10 # assignment statement
print(x) # print statement
4. Script Mode
Python code written in a .py file and executed later is called script mode.
Steps:
1. Open editor (VS Code / IDLE / PyCharm)
2. Write program and save ([Link])
3. Run using:
python [Link]
5. Order of Operations (Operator Precedence)
Order Operation Symbol
1 Parentheses ()
2 Exponent **
3 Multiplication, Division, Modulus * / // %
4 Addition, Subtraction + -
Example:
result = 5 + 2 * 3
print(result) # Output: 11 (not 21)
7. Comments
Comments are notes in code ignored by Python. Used to explain code.
What are Comments?
Comments are explanatory notes written in a Python program.
They are meant for humans, not for the computer.
The Python interpreter ignores comments during execution.
Used to explain code, improve readability, and aid maintenance.
Why Comments are Important
Make programs easy to understand.
Help others (and your future self) read and modify code.
Useful for debugging and documentation.
Essential in large and complex programs.
Do not affect program output or speed.
Single-Line Comment
# This is a comment
Multi-Line Comment
'''
This is a multiline
comment
'''
8. Debugging
Debugging means finding and fixing errors in a program.
Types of Errors
Type Meaning Example
Syntax Error Violation of language print("Hello" (missing ))
rules
Runtime Occurs during 10 / 0 (Division by zero)
Error execution
Semantic Logic error, wrong average = total / 5 (when total should be
Error result divided by 4)
Example Program Covering Key Concepts
# program to demonstrate variables, expressions, comments
a = 10 # assignment
b = 20
# expression
sum = a + b
print("Sum =", sum) # statement
Output
Sum = 30
Functions in Python
A function is a reusable block of code that performs a specific task. Instead of writing the
same code repeatedly, we define a function once and call it whenever needed.
Importance of Functions in Python
What is a Function?
A function is a block of reusable code that performs a specific task.
It runs only when it is called.
Functions help in organizing programs into smaller parts.
Example:
def greet():
print("Hello, Python!")
Advantages:
1. Code Reusability
Functions allow the same code to be used multiple times.
Avoids rewriting the same logic again and again.
Saves time and effort.
2. Reduces Program Length
Repeated code is written once inside a function.
The program becomes shorter and cleaner.
Improves efficiency.
3. Improves Readability
Functions make programs easy to read and understand.
Each function name describes what the code does.
Large programs become well-structured.
4. Easier Debugging
Errors can be isolated to specific functions.
Makes testing and debugging simpler.
Fixing an error in one function fixes it everywhere it is used.
5. Better Program Organization (Modularity)
Programs are divided into small logical units (modules).
Each function handles one specific task.
Encourages top-down programming approach.
6. Improves Maintainability
Changes can be made in one place only.
Easy to modify or update programs.
Suitable for large and long-term projects.
7. Parameter Passing & Flexibility
Functions accept parameters to work with different data.
Makes functions flexible and dynamic.
8. Improves Code Efficiency
Reduces redundancy.
Makes programs faster to write and easier to optimize.
Encourages use of built-in and user-defined functions.
Summary
Importance Explanation
Reusability Write once, use many times
Readability Clear and understandable code
Modularity Breaks program into parts
Debugging Easy error detection
Maintenance Easy to update code
Teamwork Supports collaborative work
Key Points
Functions reduce repetition of code.
They improve clarity and structure.
Essential for large and complex programs.
Python supports built-in and user-defined functions.
1. Function Basics
Functions help break programs into smaller, manageable parts.
Improve code readability and reusability.
Example
def greet():
print("Hello, Python Learner!")
2. Function Calls
A function executes only when it is called.
def greet():
print("Hello!")
greet() # Function call
3. Math Functions
Python provides built-in mathematical functions via the math module.
import math
print([Link](25)) # 5.0
print([Link](2, 3)) # 8.0
Common math functions: sqrt(), pow(), sin(), cos(), ceil(), floor().
4. Composition
Using one function inside another is called composition.
import math
result = [Link](abs(-16))
print(result)
5. Adding New Functions
You can create your own functions using def.
def add(a, b):
return a + b
6. Definitions and Uses
Function Definition
def function_name(parameters):
statements
Function Use
Saves time
Easy debugging
Encourages modular programming
7. Flow of Execution
Program execution starts at the first line and moves down, but when a function is called,
control jumps to the function definition.
8. Parameters and Arguments
Parameters: Variables declared in function definition
Arguments: Values passed when calling the function
def multiply(x, y): # parameters
return x * y
multiply(4, 5) # arguments
9. Local Variables and Parameters
Variables created inside a function are local and accessible only within that function.
def test():
x = 10 # local variable
print(x)
test()
print(x) # Error: x not defined
Fruitful and Void Functions in Python
In Python, functions are broadly classified into two types based on whether they return a
value or not:
1. Fruitful Functions
2. Void Functions
1. Fruitful Functions
Definition
A fruitful function is a function that returns a value after performing a task.
The returned value can be:
o Number
o String
o Boolean
o List, tuple, etc.
The keyword return is used.
Characteristics of Fruitful Functions
Always use the return statement
Result can be:
o Stored in a variable
o Used in expressions
o Printed or further processed
More flexible and reusable
Syntax
def function_name(parameters):
statements
return value
Example (Physics Example: Force Calculation)
def calculate_force(mass, acceleration):
return mass * acceleration
Function Calling
F = calculate_force(10, 2)
print("Force =", F, "Newtons")
Output
Force = 20 Newtons
Where Fruitful Functions are Used
Mathematical calculations
Physics formulas
Data processing
Decision making
2. Void Functions
Definition
A void function is a function that does not return any value.
It performs a task but does not send a result back.
Uses print() instead of return.
Characteristics of Void Functions
No return statement (or return without value)
Output is displayed directly
Mainly used for:
o Displaying messages
o Printing results
o Performing actions
Syntax
def function_name(parameters):
statements
Example (Physics Example: Display Force)
def display_force(mass, acceleration):
force = mass * acceleration
print("Force =", force, "Newtons")
Function Calling
display_force(10, 2)
Output
Force = 20 Newtons
.
Difference Between Fruitful and Void Functions
Feature Fruitful Function Void Function
Return value Yes No
Uses return Yes No
Output storage Can be stored Cannot be stored
Flexibility High Low
Usage Calculations, logic Display, actions
Key Points
Fruitful functions return a value
Void functions do not return a value
return sends result back to caller
Void functions return None by default
Fruitful functions are more reusable
14. Boolean Functions
Functions that return True or False.
def is_even(n):
return n % 2 == 0
print(is_even(4)) # True
Example Program Covering Concepts
import math
# fruitfuil function
def area_circle(r):
return [Link] * r * r
# void function
def show_area(r):
area = area_circle(r)
print("Area =", area)
show_area(5)
Logical Operators
Types of Logical Operators in Python
Python provides three logical operators:
1. and
2. or
3. not
1. Logical AND (and)
Meaning
Returns True only if both conditions are True.
If any one condition is False, result is False.
Truth Table
Condition 1 Condition 2 Result
True True True
True False False
False True False
False False False
Example
x = 10
print(x > 5 and x < 20)
Output
True
Explanation
x > 5 → True
x < 20 → True
Both are True → Result is True
2. Logical OR (or)
Meaning
Returns True if at least one condition is True.
Returns False only if both conditions are False.
Truth Table
Condition 1 Condition 2 Result
True True True
True False True
False True True
False False False
Example
x = 3
print(x < 5 or x > 10)
Output
True
Explanation
x < 5 → True
Only one condition needs to be True
3. Logical NOT (not)
Meaning
Reverses the Boolean value.
True becomes False, False becomes True.
Truth Table
Condition Result
True False
False True
Example
x = 10
print(not(x > 5))
Output
False
Explanation
x > 5 → True
not True → False
if–else Statement in Python
What is if–else?
The if–else statement is used for decision making.
It allows a program to choose between two blocks of code based on a condition.
If the condition is True, the if block runs.
If the condition is False, the else block runs.
Syntax of if–else
if condition:
statements_if_true
else:
statements_if_false
How if–else Works (Step-by-Step)
1. Python checks the condition in the if statement.
2. If the condition is True:
o Statements inside the if block are executed.
o The else block is skipped.
3. If the condition is False:
o Statements inside the else block are executed.
o The if block is skipped.
Suitable Example 1: Check Whether a Number is Even or
Odd
num = 7
if num % 2 == 0:
print("Number is Even")
else:
print("Number is Odd")
Explanation
num % 2 == 0 checks whether the remainder is zero.
If True → number is Even
If False → number is Odd
Output
Number is Odd
Example 2 (Physics Example): Temperature Check
temperature = 35
if temperature < 40:
print("A little cold, isn't it?")
else:
print("Nice weather we're having.")
Explanation
Condition: temperature < 40
If True → first message is printed
If False → second message is printed
Output
A little cold, isn't it?
Key Points
if–else is used for two-way decision making.
Condition must return Boolean value.
Python uses indentation instead of braces {}.
Only one block (if or else) executes at a time.
Widely used in:
o Result processing
o Eligibility checks
o Comparisons
if–elif–else Statement in Python
What is if–elif–else?
The if–elif–else statement is used for multi-way decision making.
It allows a program to check multiple conditions one by one.
Only one block of code is executed—the one whose condition is True first.
If none of the conditions are True, the else block executes.
Syntax of if–elif–else
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements_else
Syntax Rules
elif means else if.
Conditions are checked from top to bottom.
Indentation is mandatory in Python.
Colon (:) must be used after if, elif, and else.
Working
1. Python checks the if condition.
2. If it is True, the corresponding block runs and the rest are skipped.
3. If it is False, Python checks the next elif condition.
4. This continues until a condition is True.
5. If no condition is True, the else block executes.
Example 1: Grade Calculation (Very Common Exam
Example)
marks = 78
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Explanation
marks >= 90 → False
marks >= 75 → True
So Grade B is printed.
Remaining conditions are skipped.
Output
Grade B
Example 2 (Physics Example): Temperature Classification
temperature = 45
if temperature < 0:
print("Freezing condition")
elif temperature < 30:
print("Normal temperature")
elif temperature < 40:
print("Warm condition")
else:
print("Very hot condition")
Explanation
temperature < 0 → False
temperature < 30 → False
temperature < 40 → False
else executes.
Output
Very hot condition
Keyboard Input
To take user input:
name = input("Enter your name: ")
print("Hello", name)
Convert input to number:
num = int(input("Enter a number: "))
while Loop in Python
What is a while Loop?
A while loop is used to repeat a block of code as long as a condition is True.
It is called an entry-controlled loop because the condition is checked before the loop
body executes.
Commonly used when the number of iterations is not known in advance.
Syntax of while Loop
while condition:
statements
Important Rules
The condition must evaluate to True or False.
The loop body must be indented.
The loop continues until the condition becomes False.
Working:
1. The condition is checked.
2. If the condition is True:
o The statements inside the loop are executed.
3. After execution, the condition is checked again.
4. Steps repeat until the condition becomes False.
5. When the condition is False, the loop terminates.
Suitable Example 1: Printing Numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i = i + 1
Explanation
i = 1 → initialization
Condition i <= 5 is checked
print(i) prints the value of i
i = i + 1 updates the loop variable
Loop stops when i becomes 6
Output
1
2
3
4
5
Example 2 (Physics Example): Distance Covered at
Constant Speed
Physics Formula:
Distance=Speed×Time\text{Distance} = \text{Speed} \times
\text{Time}Distance=Speed×Time
speed = 10 # m/s
time = 1
while time <= 5:
distance = speed * time
print("Time =", time, "s Distance =", distance, "m")
time += 1
Output
Time = 1 s Distance = 10 m
Time = 2 s Distance = 20 m
Time = 3 s Distance = 30 m
Time = 4 s Distance = 40 m
Time = 5 s Distance = 50 m
Key Points
while loop is an entry-controlled loop.
Condition is checked before each iteration.
Used when number of repetitions is unknown.
Loop variable must be updated to avoid infinite loop.
Indentation is mandatory in Python.
for Loop in Python
What is a for Loop?
A for loop is used to repeat a block of code for a fixed number of times.
It is mainly used to iterate over a sequence such as:
o List
o Tuple
o String
o Range of numbers
It is called an entry-controlled loop.
Syntax of for Loop
for variable in sequence:
statements
Important Points
The loop variable takes one value at a time from the sequence.
The loop continues until all values are exhausted.
Indentation is compulsory.
How the for Loop Works
1. Python picks the first value from the sequence.
2. Executes the loop body.
3. Picks the next value.
4. Repeats until the sequence ends.
5. Loop terminates automatically.
Suitable Example 1: Printing Numbers from 1 to 5
for i in range(1, 6):
print(i)
Explanation
range(1, 6) generates numbers from 1 to 5.
i takes each value one by one.
Loop prints numbers sequentially.
Output
1
2
3
4
5
range() Function in for Loop
Form Meaning
range(n) 0 to n-1
range(start, stop) start to stop-1
range(start, stop, step) with step size
Example:
for i in range(2, 11, 2):
print(i)
Key Points
for loop is used when number of iterations is known.
It automatically updates the loop variable.
No risk of infinite loop if used correctly.
Works with sequences and ranges.
Indentation is mandatory.