UNIT I-Pps-Rgc
UNIT I-Pps-Rgc
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.
1991: Python 1.0 released with features like exception handling and modules.
2008: Python 3.0 released, making major improvements but breaking backward compatibility.
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
1.3 Working with Python
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.
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 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.
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
2
Features of Python Interpreter
The Python Interpreter is the core component that executes Python code. Here are its key features:
1. Interpreted Execution
2. Interactive Mode
o Example:
o Example:
python my_script.py
4. Dynamic Typing
o Example:
x = 10 # x is an integer
5. Platform Independent
3
9. Bytecode Compilation
o Python internally converts code to bytecode (.pyc files) before execution for faster
performance.
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!
*************************************
4
How to Install Python on Windows 🐍
Step 1: Run the Python Installer
***************************
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
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.
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. 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))
Output
Hello, Python!
<class 'str'>
H
List (list)
Creating a List
You can create a list using square brackets [ ].
Program:
# Empty list
a=[]
9
b = ["Hello", "Python", 42, 3.14]
print(b)
Output:
[1, 2, 3]
['Hello', 'Python', 42, 3.14]
Program:
Output:
Apple
Cherry
Tuple
Program:
# Empty tuple
tup1 = ( )
print("Tuple:", tup2)
Output:
("Tuple:", tup2)
Accessing Tuple Items
Program:
10
tup1 = (1, 2, 3, 4, 5)
# Access elements
print(tup1[0]) # First item
Output:
1
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
Program:
a = 10
b=5
print(a > b)
print(a == b)
Output:
True
False
Creating a Set
You can create a set using curly braces { } or the set( ) function.
Program:
11
# Empty set
s1 = set()
Output:
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}
*******************
Python provides several ways to work with numbers, including basic arithmetic operations, built-in
functions, and math libraries.
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
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
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.
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"
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"))
Output:
0 (Position of first "Python")
15 (Position of last "Python")
2 (Occurrences of "Python")
"Java is fun. Java is easy."
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:
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"
Output:
********************************************
Python built-in functions are predefined functions that come with Python and can be used
directly without needing to import any module.
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!")
6. List & Tuple append() Adds item to a list lst = [1,2]; lst.append(3)
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))
******************************
18