UNIT I
INTRODUCTION: History - Features - Working with Python - Installing Python - basic syntax -
Data types - variables - Manipulating Numbers - Text Manipulations - Python Build in Functions.
1.1 History
Python was created by Guido van Rossum in the late 1980s and officially released in 1991. It was
designed as a successor to the ABC language, with a focus on code readability and simplicity.
Key Milestones in Python's History:
1991: Python 1.0 released with features like exception handling and modules.
2000: Python 2.0 introduced list comprehensions and garbage collection.
2008: Python 3.0 released, making major improvements but breaking backward compatibility.
2018: Python 2.x officially deprecated, urging users to migrate to Python 3.
Present: Python is one of the most popular programming languages, widely used in AI, web
development, data science, and automation.
Python’s simplicity and versatility have made it a favorite among developers worldwide
**************************************
1.2 Features of Python
1. Easy to Learn & Use
Python has a simple and readable syntax, like writing in English.
2. Interpreted Language
No need to compile; Python runs line by line, making debugging easier.
3. Platform Independent
Works on Windows, Mac, and Linux without modification.
4. Open-Source
Free to use and modify, with a large community for support.
5. Object-Oriented & Functional
Supports both OOP (like Java, C++) and functional programming styles.
6. Huge Libraries & Frameworks
Pre-built modules for AI, web development, and more (NumPy, Pandas, Django, etc.).
7. Dynamically Typed
No need to declare variable types (e.g., x = 10 works automatically).
8. Extensible & Embeddable
Can use C, C++, or Java code inside Python programs.
9. Automation & Scripting
Great for writing scripts to automate tasks.
10. Strong Community Support
Millions of developers contribute, making Python continuously improve.
*****************************************
1
1.3 Working with Python
Python is a computer programming language like Java.
It is called an interpreted language because it runs code line by line instead of compiling it all at once.
Python uses small code modules instead of writing everything in one long list.
The most common version of Python is CPython.
How Does Python Work?
Python code goes through several steps before running on a computer:
Write Code – You type your Python program in a text editor and save it as a .py file.
Compilation – Python checks for mistakes and converts the code into bytecode (.pyc).
Python Virtual Machine (PVM) – This reads the bytecode and turns it into machine language (0s and
1s).
Execution – The computer’s CPU runs the machine language and gives the output.
Python Libraries & Modules
Python has built-in tools (called modules) that help you do tasks quickly.
When you use import, Python checks if the module is already available and runs it.
If the module is not built-in, Python looks for it in specific folders and loads it.
Compiler vs. Interpreter
Feature Compiler (Like Java) Interpreter (Like Python)
Speed Faster (converts everything first) Slower (runs line by line)
Errors Shows all mistakes before running Stops when a mistake is found
Portability Must be changed for different computers Works on any system with Python
Memory Usage Uses more memory Uses less memory
Debugging Harder to fix errors Easier to fix errors
2
Features of Python Interpreter
The Python Interpreter is the core component that executes Python code. Here are its key features:
1. Interpreted Execution
o Executes code line by line, making debugging easier.
o No need for compilation like in C or Java.
2. Interactive Mode
o Allows running Python commands directly in the terminal.
o Supports quick testing and debugging.
o Example:
>>> print("Hello, World!")
3. Script Mode Execution
o Runs Python files (.py) stored on disk.
o Example:
python my_script.py
4. Dynamic Typing
o No need to declare variable types; Python decides at runtime.
o Example:
x = 10 # x is an integer
x = "Python" # x is now a string
5. Platform Independent
o Works on Windows, Mac, Linux, and Raspberry Pi without modification.
6. Automatic Memory Management
o Uses garbage collection to manage memory efficiently.
7. Supports Multiple Paradigms
o Works with procedural, object-oriented, and functional programming styles.
8. Extensible and Embeddable
o Can integrate with C, C++, and Java for performance optimization.
o Can be embedded in other applications.
3
9. Bytecode Compilation
o Python internally converts code to bytecode (.pyc files) before execution for faster
performance.
10. Standard Libraries and Modules
Comes with built-in libraries for math, file handling, networking, and web development.
These features make the Python interpreter powerful, flexible, and easy to use!
*************************************
1.4 INSTALLING PYTHON
Step 1: Download Python for Windows
Visit the Python Website and Navigate to the Downloads Section
First and foremost step is to open a browser and type Python Download or paste link
(https://www.python.org/downloads/ )
Step 2: Choose the Python Version
Once you landed on the download page choose the Python Version
Click on the version you want to download. – Python 3.13.2 (the latest stable release as of now is
Python 3.13.21
Step 3: Download the Python Installer
Once the download is complete, run the installer program. On Windows , it will typically be a .exe
file , on macOS , it will be a .pkg file , and on Linux , it will be a .tar.gz file .
4
How to Install Python on Windows 🐍
Step 1: Run the Python Installer
1. Download Python Installer from the official website.
2. Open the downloaded .exe file to start the installation.
3. Check the box "Add Python to PATH" (Important!).
4. Click Install and wait for it to complete.
5. Click Close when done. 🎉 Python is now installed!
Step 2: Open Python (IDLE)
1. Go to Windows Start Menu and type IDLE.
2. Open Python IDLE (Shell).
3. You will see >>> – this is the Python command prompt.
4. Type:
print("Hello, Python!")
5. Press Enter, and Python will display
Hello, Python!
***************************
1.5 Basic syntax
Python syntax is the set of rules that define how Python programs are written and interpreted.
It acts like grammar for the Python programming language, ensuring that the code is structured correctly
so that the computer can understand and execute it.
Python syntax can be executed by writing directly in the Command Line
>>> print("Hello, World!")
Hello, World
Or by creating a python file on the server, using the .py file extension, and running it in the Command
Line:
5
C:\Users\Your Name>python myfile.py
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.
Python will give you an error if you skip the indentation:
Program:
if 5 > 2:
print("Five is greater than two!")
Output:
Five is greater than two!
Python Variables
A variable in Python is like a name that points to a value stored in memory.
Unlike other programming languages, you don’t need to specify the type of a variable .Python
figures it out automatically.
Program:
a = 10
b = "Hello"
print(type(a))
print(type(b))
Output:
<class 'int'>
<class 'str'>
Python Keywords
Keywords are special words in Python that have specific meanings.
You cannot use them as names for variables, functions, or classes.
Here is a list of Python keywords:
6
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Program:
#This is a comment.
print("Hello, World!")
Output:
Hello, World!
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Program:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Output:
Hello, World!
*******************************************
1.6 Python Data Types
7
A data type in Python tells what kind of value a variable can hold.
Python automatically decides the data type when you assign a value to a variable. You don’t need
to mention it separately.
The following are the standard or built-in data types in Python:
Numeric – int, float, complex
Sequence Type – string, list, tuple
Mapping Type – dict
Boolean – bool
Set Type – set, frozenset
Binary Types – bytes, bytearray, memoryview
1.6.1 Numeric Data Types in Python
In Python, numbers can be of three types:
1. Integers (int) – Whole numbers (positive or negative) without decimals.
Example: 10, -5, 1000
2. Floats (float) – Numbers with decimals.
Example: 3.14, -0.5, 2.0
3. Complex Numbers (complex) – Numbers with a real and imaginary part.
Example: 2 + 3j, -1 + 4j
Python automatically recognizes these types when you assign a value.
Program:
x = 10
y = 3.14
z = 2 + 3j
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'int'>
8
<class 'float'>
<class 'complex'>
1.6.2 Sequence Data Types in Python
Sequence data types store multiple values in an ordered way.
Python has three main sequence types:
1. String (str)
2. List (list)
3. Tuple (tuple)
String (str)
A string is a collection of characters inside single ('), double ("), or triple (''') quotes.
Program
s = "Hello, Python!"
print(s)
print(type(s))
# Access characters using an index
print(s[0])
Output
Hello, Python!
<class 'str'>
H
List (list)
A list in Python is like a container that holds multiple items.
It is ordered, and you can store different types of data in it.
Creating a List
You can create a list using square brackets [ ].
Program:
# Empty list
a=[]
# List with numbers
a = [1, 2, 3]
print(a)
# List with mixed data types
9
b = ["Hello", "Python", 42, 3.14]
print(b)
Output:
[1, 2, 3]
['Hello', 'Python', 42, 3.14]
Accessing List Items
You can access list items using index numbers.
Program:
a = ["Apple", "Banana", "Cherry"]
# Access using positive index (starts from 0)
print(a[0]) # Output:
print(a[2]) # Output:
Output:
Apple
Cherry
Tuple
A tuple is like a list, but it cannot be changed after it is created (immutable).
Tuples store multiple values in an ordered way.
Creating a Tuple in Python
Tuples can have numbers, strings, or even lists.
They are created using parentheses ( ) or just commas.
Program:
# Empty tuple
tup1 = ( )
# Tuple with strings
tup2 = ('Hello', 'Python')
print("Tuple:", tup2)
Output:
("Tuple:", tup2)
Accessing Tuple Items
Use index numbers to get items, just like in a list.
Program:
10
tup1 = (1, 2, 3, 4, 5)
# Access elements
print(tup1[0]) # First item
Output:
1
1.6.3 Boolean Data Type
A Boolean data type in Python has only two values:
True (Yes)
False (No)
It is used to check conditions and make decisions. Boolean values belong to the bool class.
Program
print(type(True))
print(type(False))
Output:
<class 'bool'>
<class 'bool'>
Boolean in Conditions
Booleans are useful in decision-making.
Program:
a = 10
b=5
print(a > b)
print(a == b)
Output:
True
False
1.6.4 Set Data Type
A Set in Python is a collection of unique items.
Set items are unordered, unchangeable, and do not allow duplicate values.
Creating a Set
You can create a set using curly braces { } or the set( ) function.
Program:
11
# Empty set
s1 = set()
# Set from a string (duplicates removed)
s2 = set("Hello")
print(s2)
# Set from a list
s3 = set(["Apple", "Banana", "Apple"])
print(s3)
Output:
{'H', 'e', 'l', 'o'}
{'Apple', 'Banana'} (No duplicates)
1.6.5 Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered, changeable and do not allow duplicates.
Program:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
*******************
1.7 Manipulating Numbers in Python
Python provides several ways to work with numbers, including basic arithmetic operations, built-in
functions, and math libraries.
1. Basic Arithmetic Operations
Python supports standard arithmetic operations
Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
12
** Exponentiation
// Floor division
Program
a = 10
b=3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Output
13
7
30
3.3333
3
1
1000
2. Built-in Number Functions
Python has functions to manipulate numbers easily:
Function Description
abs() Returns the absolute value of a number
round() Rounds a numbers
pow() Returns the value of x to the power of y
Program:
x = -10
y = 2.7
print(abs(x))
print(round(y))
print(pow(2, 3))
Output:
10
3
8
3. Using the math Module
Python has a built-in module that you can use for mathematical tasks.
The math module has a set of methods and constants
13
Function Description
math.sqrt() Returns the square root of a number
math.factorial() Returns the factorial of a number
math.ceil() Rounds a number up to the nearest integer
math.floor() Rounds a number down to the nearest integer
math.pi() The math. pi constant returns the value of PI:
Program:
import math
print(math.sqrt(16))
print(math.factorial(5))
print(math.ceil(2.3))
print(math.floor(2.9))
print(math.pi)
Output:
4.0
120
3
2
3.141592653589793
4. Random Numbers (random Module)
Generate random numbers using the random module
Function Description
randint() Returns a random number between the given range
choice() Returns a random element from the given sequence
rand() Returns a random floating-point number between 0.0 and 1.0
Program:
import random
print(random.randint(1, 10))
print(random.random( ))
print(random.choice([10, 20, 30]))
Output:
7 # Random integer between 1 and 10
0.5382 # Random float between 0 and 1
14
20 # Random choice from [10, 20, 30]
********************************************************
1.7 Text Manipulation in Python
Text manipulation means changing or working with text (strings) using different methods in
Python.
It can be categorized into
1. Change letter case.
2. Find and replace words.
3. Check text type.
4. Splitting and Joining Text
5. Trimming and Aligning Text.
1. Change letter case
These functions help modify letter cases.
Function Description
upper() Converts a string into upper case
lower() Converts a string into lower case
title() Converts the first character of each word to upper case
swapcase() Swaps cases, lower case becomes upper case and vice versa
Program
text = "Hello World"
print(text.upper())
print(text.lower())
print(text.title())
print(text.swapcase())
Output
# "HELLO WORLD"
# "hello world"
# "Hello World"
# "hELLO wORLD"
2. Find and replace words
These functions help search, count, and replace words.
15
Function Description
find() Finds the position of a value in a string.
rfind() Finds the last place where a value appears in a string.
count() Counts how many times a value appears in a string
replace() Replaces a value in a string with another value.
Program:
text = "Python is fun. Python is easy."
print(text.find("Python"))
print(text.rfind("Python"))
print(text.count("Python"))
new_text = text.replace("Python", "Java")
print(new_text)
Output:
0 (Position of first "Python")
15 (Position of last "Python")
2 (Occurrences of "Python")
"Java is fun. Java is easy."
3. Check text type.
These functions check the type of characters in a string.
Function Description
isdigit() Returns True if all characters in the string are digits
isalpha() Returns True if all characters in the string are in the alphabet
isalnum() Returns True if all characters in the string are alphanumeric
isspace( ) Returns True if all characters in the string are whitespaces
Program:
print("123".isdigit( ))
print("Hello".isalpha( ))
print("Hello123".isalnum( ))
print(" ".isspace( ))
Output:
True (Only digits)
True (Only letters)
True (Letters + numbers)
True (Only spaces)
16
4. Splitting and Joining Text
Splitting means breaking text into parts. Joining means combining them.
Function Description
split() Splits the string at the specified separator, and returns a list
join( ) Turns multiple elements into a single string
Program:
text = "apple,banana,orange"
# Splitting into a list
words = text.split(",")
print(words)
# Joining into a string
new_text = " | ".join(words)
print(new_text)
Output:
['apple', 'banana', 'orange']
"apple | banana | orange"
********************************************
1.8 Python Build in Functions
Python built-in functions are predefined functions that come with Python and can be used
directly without needing to import any module.
Python built-in functions can be categorized based on their purpose:
1. Input/Output Functions
2. Type Conversion Functions
3. String Functions
4. Mathematical Functions
5. Sequence and Collection Functions
6. List, Tuple, and Set Functions
7. Dictionary Functions
8. File Handling Functions
9. Functional Programming Functions
10. Object and Class Functions
11. Exception Handling Functions
12. System-Related Functions
Category Function Description Example Program
17
1. Input/Output print() Displays output print("Hello, World!")
input() Takes user input name = input("Enter name: ")
2. Type Conversion int() Converts to an integer num = int("10")
str() Converts to a string text = str(123)
3. String Functions len() Finds length of a string print(len("hello"))
str.upper() Converts to uppercase print("hello".upper())
4. Mathematical abs() Returns absolute value print(abs(-5))
max() Finds the largest number print(max(3, 8, 2))
5. Sequence & sorted() Sorts elements in order print(sorted([3, 1, 2]))
Collection
sum() Adds elements in a list print(sum([1, 2, 3]))
6. List & Tuple append() Adds item to a list lst = [1,2]; lst.append(3)
Removes last item from
pop() lst.pop()
list
7. Dictionary keys() Returns all keys print({"a":1}.keys())
get() Retrieves value by key print({"a":1}.get("a"))
8. File Handling open() Opens a file f = open("file.txt")
read() Reads file content print(f.read())
9. Functional Applies function to
map() print(list(map(str, [1,2])))
Programming elements
Filters elements by
filter() print(list(filter(lambda x: x>2, [1,2,3])))
condition
10. Object & Class type() Gets data type print(type(5))
isinstance() Checks if object is a type print(isinstance(5, int))
11. Exception try Handles errors try: print(1/0) except: print("Error")
Handling
raise Raises an exception raise ValueError("Error")
******************************
18