PYTHON NOTES (Diploma Mechanical Students)
Unit-1
Features of python
Python is a high-level, versa le programming language
known for its simplicity, readability, and wide range of
applica ons. It is widely used in web development, data
science, ar ficial intelligence and automa on. Python is
one of the most popular programming languages because
of its simplicity and powerful features.
1. Easy to Learn and Use
o Simple and readable syntax.
o Suitable for beginners.
2. Interpreted Language
o Code is executed line by line without compila on.
3. High-Level Language
o Hides complex details of the computer hardware.
4. Object-Oriented
o Supports classes, objects, inheritance,
polymorphism, etc.
5. Pla orm Independent
o Python programs can run on Windows, Linux, and
macOS with li le or no modifica on.
6. Open Source
o Free to download, use, and modify.
7. Dynamically Typed
o No need to declare variable data types explicitly.
8. Large Standard Library
o Provides built-in modules for file handling,
networking, databases, web development, and
more.
9. Extensible and Embeddable
o Can be integrated with languages like C and C++.
10. Supports Mul ple Programming Paradigms
o Object-Oriented Programming (OOP)
o Procedural Programming
o Func onal Programming
11. Automa c Memory Management
o Uses garbage collec on to manage memory
automa cally.
12. Wide Range of Applica ons
o Web development
o Data Science
o Ar ficial Intelligence & Machine Learning
o Automa on and Scrip ng
o Game Development
In short: Python is simple, versa le, portable, open-
source, and powerful, making it a preferred language for
beginners and professionals alike.
Applica ons of Python in Automa on and Engineering
In Automa on
1. Automa c file handling – Rename, move, copy, or
delete files automa cally.
2. Sending emails – Send emails and no fica ons without
doing it manually.
3. Web automa on – Fill online forms, download data, and
perform website tasks automa cally.
4. Report genera on – Create reports from data
automa cally.
5. So ware tes ng – Test applica ons automa cally to
save me.
In Engineering
1. Calcula ons – Solve mathema cal and engineering
problems quickly.
2. Data analysis – Analyze and organize engineering data.
3. Graphs and charts – Create visual representa ons of
data.
4. Robo cs – Control robots and automated machines.
5. IoT projects – Work with sensors and smart devices.
6. Simula ons – Test designs and systems on a computer
before building them.
7. Machine monitoring – Track machine performance and
detect problems.
Python Installa on and Development Environments
(IDE)
1. Python Installa on
Python is a high-level programming language used for
web development, data science, ar ficial intelligence,
IoT, and automa on. Before wri ng Python programs,
Python must be installed on the system.
Steps to Install Python
1. Visit the official Python website: Python Official Website
2. Download the latest version suitable for your opera ng
system (Windows, Linux, or macOS).
3. Run the installer and select "Add Python to PATH".
4. Click Install Now and complete the installa on.
5. Verify the installa on by opening Command Prompt and
typing:
python --version
or
python3 --version
If Python is installed successfully, the version number
will be displayed.
2. Development Environments (IDE)
An Integrated Development Environment (IDE) is
so ware that provides tools for wri ng, edi ng,
debugging, and execu ng Python programs.
Common Python IDEs
IDE Features
Default IDE with Python, simple
IDLE and lightweight.
Powerful IDE with debugging and
PyCharm code comple on features.
Lightweight editor with Python
Visual Studio extensions and debugging
Code (VS Code) support.
Interac ve environment mainly
Jupyter used for data science and
Notebook machine learning.
Scien fic Python IDE with built-in
Spyder tools for analysis and
visualiza on.
Beginner-friendly IDE with simple
Thonny interface.
Features of an IDE
Source code editor
Syntax highligh ng
Auto-comple on
Debugging tools
Error detec on
Code execu on and tes ng
Project management
Advantages of Using an IDE
Increases programming produc vity.
Helps detect errors quickly.
Simplifies debugging and tes ng.
Provides an organized environment for developing
applica ons.
Conclusion
Python can be installed easily from the official website,
and several IDEs such as IDLE, PyCharm, VS Code,
Jupyter Notebook, and Spyder provide efficient
environments for developing and debugging Python
applica ons.
Python Syntax and Keywords
1. Python Syntax
What is Python Syntax?
Python syntax is the set of rules that tells us how to
write Python programs correctly.
Simple Defini on:
Python syntax is the set of rules for wri ng Python
code.
If the syntax is correct, the program runs successfully. If
the syntax is wrong, Python gives an error.
Rules of Python Syntax
1. Use Proper Indenta on
Python uses indenta on (spaces) instead of curly
braces {} to define blocks of code.
Example:
if 10 > 5:
print("10 is greater than 5")
2. Statements End Without a Semicolon
Unlike some programming languages, Python does not
require a semicolon (;) at the end of each statement.
Example:
print("Hello")
print("Welcome")
3. Python is Case-Sensi ve
Python treats uppercase and lowercase le ers as
different.
Example:
name = "Ali"
Name = "Ahmed"
print(name)
print(Name)
Here, name and Name are two different variables.
4. Comments
Comments are used to explain the code. Python
ignores comments during execu on.
Example:
# This is a comment
print("Hello Students")
5. Proper Use of Quotes
Strings must be wri en inside single (' ') or double (" ")
quotes.
Example:
print("Python")
print('Programming')
2. Python Keywords
What are Keywords?
Keywords are reserved words in Python that have a
special meaning. They cannot be used as variable
names.
Simple Defini on:
Keywords are special words that have predefined
meanings in Python.
Common Python Keywords
Keyword Purpose
if Used for decision making
else Executes when the if condi on is false
elif Checks another condi on
Keyword Purpose
for Used for loops
while Repeats code while a condi on is true
break Exits a loop
con nue Skips the current itera on
def Defines a func on
return Returns a value from a func on
class Creates a class
import Imports a module
True Boolean true value
False Boolean false value
None Represents no value
and Logical AND operator
or Logical OR operator
not Logical NOT operator
try Starts excep on handling
except Handles errors
pass Does nothing (placeholder)
Examples of Keywords
1. if and else
age = 18
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible")
2. for
for i in range(5):
print(i)
3. while
count = 1
while count <= 3:
print(count)
count += 1
4. def
def greet():
print("Hello World")
greet()
Conclusion
Python syntax provides a simple and readable structure
for wri ng programs. Keywords are predefined reserved
words that perform specific func ons and cannot be
used as iden fiers. Understanding syntax and keywords
is essen al for wri ng correct Python programs.
Variables and Data Types in Python
Variables in Python
A variable is a named memory loca on used to store
data values. In Python, variables are created
automa cally when a value is assigned to them.
Syntax:
variable_name = value
Example:
name = "John"
age = 25
salary = 35000.50
print(name)
print(age)
print(salary)
Rules for Naming Variables:
Variable names can contain le ers, digits, and
underscores (_).
A variable name must start with a le er or an
underscore.
Variable names are case-sensi ve (Age and age are
different).
Keywords cannot be used as variable names.
Examples
student_name = "Ali" # Valid
_marks = 90 # Valid
2value = 100 # Invalid
Data Types in Python
A data type specifies the type of value stored in a
variable.
1. Numeric Data Types
Integer (int): Stores whole numbers.
x = 10
print(type(x))
Float (float): Stores decimal numbers.
y = 3.14
print(type(y))
Complex (complex): Stores complex numbers.
z = 2 + 3j
print(type(z))
2. String (str): Stores text enclosed within single or
double quotes.
name = "Python"
print(type(name))
3. Boolean (bool): Represents logical values True or
False.
is_ac ve = True
print(type(is_ac ve))
4. Sequence Data Types
List (list): An ordered and mutable collec on.
numbers = [10, 20, 30]
print(type(numbers))
Tuple (tuple): An ordered and immutable collec on.
colors = ("Red", "Green", "Blue")
print(type(colors))
Range (range): Represents a sequence of numbers.
r = range(5)
print(type(r))
5. Set Data Types
Set (set): An unordered collec on of unique elements.
items = {1, 2, 3}
print(type(items))
Frozen Set (frozenset): An immutable version of a set.
fset = frozenset([1, 2, 3])
print(type(fset))
6. Mapping Data Type
Dic onary (dict): Stores data in key-value pairs.
student = {
"name": "Ahmed",
"age": 21
}
print(type(student))
7. Binary Data Types
Bytes (bytes)
Syntax
b = b"Hello"
example program:
b = b"Hello"
print(b)
print(type(b))
Output
b'Hello'
<class 'bytes'>
Summary of Python Data Types
Category Data Types
Numeric int, float, complex
Text str
Boolean bool
Sequence list, tuple, range
Set set, frozenset
Mapping dict
Binary bytes, bytearray, memoryview
Conclusion
Variables are used to store data, and Python provides
several built-in data types such as int, float, string,
boolean, list, tuple, set, and dic onary to represent
different kinds of informa on. Understanding variables
and data types is fundamental to Python programming.
Input and Output Opera ons in Python
1. What is Input?
Input is the data entered by the user into a program.
Simple Defini on:
Input is the informa on given by the user to the
computer.
For example:
Enter your name
Enter your age
Enter two numbers
2. What is Output?
Output is the result displayed by the program a er
processing the input.
Simple Defini on:
Output is the informa on shown by the computer a er
execu ng a program.
For example:
Displaying a name
Showing the sum of two numbers
Prin ng a message
3. Input Func on in Python
Python uses the input() func on to take input from the
user.
Syntax
variable = input("Enter a value: ")
Example 1: Input a Name
name = input("Enter your name: ")
print("Welcome", name)
Output:
Enter your name: Ali
Welcome Ali
4. Output Func on in Python
Python uses the print() func on to display output.
Syntax
print(value)
Example 2: Print a Message
print("Hello Students")
print("Welcome to Python")
Output:
Hello Students
Welcome to Python
5. Input of Numbers
The input() func on always reads data as text (string).
To perform calcula ons, we must convert the input into
numbers using int() or float().
Example 3: Add Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum =", sum)
Output:
Enter first number: 10
Enter second number: 20
Sum = 30
6. Using float() for Decimal Numbers
height = float(input("Enter your height: "))
print("Height =", height)
Output:
Enter your height: 5.6
Height = 5.6
7. Prin ng Mul ple Values
We can display mul ple values in one print() statement.
Example
name = "Ayesha"
age = 19
print("Name:", name)
print("Age:", age)
Output:
Name: Ayesha
Age: 19
8. Input–Process–Output (IPO) Cycle
+-----------+ +------------+ +-----------+
| Input | ---> | Process | ---> | Output |
+-----------+ +------------+ +-----------+
Example:
Input: Enter two numbers.
Process: Add the numbers.
Output: Display the sum.
9. Advantages of Input and Output Func ons
Allow interac on between the user and the program.
Make programs dynamic (not fixed).
Easy to use and understand.
Help in solving real-life problems.
Summary Table
Func on Purpose Example
name =
Takes input from input("Enter
input()
the user name: ")
print() Displays output print("Hello")
Converts input to age = int(input())
int()
an integer
Converts input to height =
float() a decimal float(input())
number
Example:
name = input("Enter your name: ")
branch = input("Enter your branch: ")
roll = input("Enter your roll number: ")
print("\n--- Student Details ---")
print("Name :", name)
print("Branch :", branch)
print("Roll No:", roll)
This example is simple, prac cal, and helps students
understand both input and output clearly.
simple python programs for automa on
Simple Python Programs for Automa on
What is Automa on?
Automa on means using a computer program to
perform a task automa cally without doing it manually
every me.
Simple Defini on:
Automa on is the process of using a program to
complete repe ve tasks automa cally.
Examples of Automa on:
Calcula ng student marks
Renaming files
Sending emails automa cally
Crea ng reports
Taking a endance
Program 1: Display a Welcome Message
print("Welcome to Python Automa on")
Output:
Welcome to Python Automa on
Program 2: Add Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum =", sum)
Output (Example):
Enter first number: 15
Enter second number: 10
Sum = 25
Automa on Use: Automa cally calculates the sum.
Program 3: Calculate Area of a Rectangle
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print("Area =", area)
Output (Example):
Enter length: 5
Enter width: 4
Area = 20.0
Automa on Use: Quickly calculates the area.
Program 4: Calculate Student Percentage
m1 = int(input("Enter marks in Subject 1: "))
m2 = int(input("Enter marks in Subject 2: "))
m3 = int(input("Enter marks in Subject 3: "))
total = m1 + m2 + m3
percentage = total / 3
print("Total Marks =", total)
print("Percentage =", percentage)
Output (Example):
Enter marks in Subject 1: 80
Enter marks in Subject 2: 75
Enter marks in Subject 3: 90
Total Marks = 245
Percentage = 81.67
Automa on Use: Automa cally calculates total marks
and percentage.
Program 5: Check Even or Odd Number
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output (Example):
Enter a number: 12
Even Number
Automa on Use: Automa cally iden fies whether a
number is even or odd.
Program 6: Temperature Converter (Celsius to
Fahrenheit)
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit =", fahrenheit)
Output (Example):
Enter temperature in Celsius: 25
Temperature in Fahrenheit = 77.0
Automa on Use: Converts temperature automa cally.
Program 7: Simple Calculator
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Addi on =", a + b)
print("Subtrac on =", a - b)
print("Mul plica on =", a * b)
print("Division =", a / b)
Output (Example):
Enter first number: 20
Enter second number: 5
Addi on = 25
Subtrac on = 15
Mul plica on = 100
Division = 4.0
Program 8: Display Mul plica on Table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)
Output (Example):
Enter a number: 5
5x1=5
5 x 2 = 10
...
5 x 10 = 50
Automa on Use: Generates the mul plica on table
automa cally.
Real-Life Automa on Examples
Task Python Automa on
Student marks Calculate total and percentage
Salary Calculate employee salary
Shopping bill Calculate total amount
A endance Count present students
Unit conversion Convert Celsius to Fahrenheit