Unit 1 Python
Unit 1 Python
History of Python
✓ Guido Van Rossum, a computer programmer in the Netherlands, created
Python.
✓ During his research at the National Research Institute for Mathematics and
Computer Science in the Netherlands, he created Python.
✓ The name for the language was inspired by the BBC TV show Monty Python’s
Flying Circus because Guido Van Rossum was a big fan of the show.
✓ He published the first version of the Python code (version 0.9.0) in 1991. It
already included good features such as some data types and functions for error
handling.
✓ Python 1.0 was released in 1994 with new functions to easily process a list of
data, such as map, filter, and reduce.
✓ Python 1.5 released in 1997
✓ Python 2.0 was released on October 16, 2000, with new useful features for
programmers, such as support for Unicode characters and a shorter way to loop
through a list.
✓ On December 3, 2008, Python 3.0 was released. It included features such as the
print function and more support for number division and error handling.
✓ The latest version of Python, Python 3.11 was released in 2022.
✓ In recent years, Python has gained a lot of popularity and is a highly
demanding programming language. It has spread its demand in various fields
which includes machine learning, artificial intelligence, data analysis, web
development.
Features of Python
1. Free and Open Source
Python language is freely available at the official website.
Since it is open-source, this means that source code is also available to the public.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc It is also a
developer-friendly language.
3. Easy to Read
Python’s syntax is really very easy. The code block is defined by the indentations
rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports
object-oriented language and concepts of classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need
to remember the system architecture.
7. Easy to Debug
Python coding is very easy to debug
8. Python is a Portable language:
Python language is also a portable language. For example, if we have Python code
for Windows and if we want to run this code on other platforms such as Linux, Unix,
and Mac then we do not need to change it, we can run this code on any platform.
9. Python is an integrated language:
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.
10. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a
time.
11. Large Standard Library:
Python has a large standard library that provides a rich set of modules and functions.
12. Dynamically Typed Language:
Python is a dynamically typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of this
feature we don’t need to specify the type of variable.
13. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value.
Uses of Python
Variables in Python
Variables are containers for storing data values. We do not need to declare variables
before using them or declare their type.
A variable is created the moment we first assign a value to it. A Python variable is a
name given to a memory location.
Ex:
x = “Welcome”
y=5
z = 34.89
print(x)
print(y)
print(z)
Rules for Python variables
• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
• Variable in Python names is case-sensitive.
• The reserved words(keywords) in Python cannot be used to name the variable
in Python.
Python Assign Values to Multiple Variables:
We can assign single value to multiple variables.
Ex:
x = y = z = 8;
We can also assign multiple values to several variables simultaneously.
Ex:
a , b, c = 35, “Hello” , 89.12
Python Variable Types
There are two types of variables in Python - Local variable and Global variable.
Local Variable:
The variables that are declared within the function and have scope within the function
are known as local variables.
Ex:
# Declaring a function
def add():
# Defining local variables. They have scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
Global Variables
Global variables in Python are the ones that are defined and declared outside a
function, and we need to use them inside a function.
Ex:
def f():
print(s)
# Global scope
s = "Global Variables"
f()
output:
Global Variables
Get the Type:
You can get the data type of a variable with the type() function.
Ex:
x=5
y = "John"
print(type(x))
print(type(y))
Output:
<class 'int'>
<class 'str'>
Datatypes in Python
Built-in data types in Python are:
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Numbers:
Python supports three kinds of numerical data.
o Int: It contains positive or negative whole numbers (without fractions or
decimals). In Python, there is no limit to how long an integer value can be.
o Float: It is a real number with a floating-point representation. It is specified by
a decimal point.It can be accurate to within 15 decimal places.
o Complex: A complex number is specified as (real part) + (imaginary part)j . For
example – 2+3j
Ex:
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Sequence Type:
There are several sequence data types of Python
• Python String
• Python List
• Python Tuple
String Data Type
A string is a collection of one or more characters put in a single quote, double-quote,
or triple-quote.
Ex:
a = "string in a double quote"
b= 'string in a single quote'
print(a)
print(b)
Output:
string in a double quote
string in a single quote
List Data Type:
Lists in Python can be created by just placing the sequence inside the square
brackets[].
Ex:
# Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
# list with mixed int and string
b = ["Welcome", "To",”Python” , 4, 5]
print(b)
Output:
[1, 2, 3]
["Welcome", "To",”Python” , 4, 5]
Tuple Data Type:
The tuple is another data type which is a sequence of data like list. But it is
immutable. That means data in a tuple is write-protected. Data in a tuple is written
using parenthesis and commas.
Ex:
tuple having only integer type of data.
a=(1,2,3,4)
print(a) #prints the whole tuple
tuple having multiple type of data.
b=("hello", 1,2,3,"go")
print(b) #prints the whole tuple
Output:
(1,2,3,4)
("hello", 1,2,3,"go")
Dictionary:
A dictionary is a key-value pair set arranged in any order. It stores a specific value for
each key. Dictionaries are written within curly braces in the form key:value.
Ex:
a = {1:"first name",2:"last name", "age":33}
#print value having key=1
print(a[1])
#print value having key=2
print(a[2])
#print value having key="age"
print(a["age"])
Output:
first name
last name
33
Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False.
Ex:
print(type(True))
print(type(False))
Output:
<class 'bool'>
<class 'bool'>
Set Data Type:
Set is an unordered collection of data types that is iterable, mutable, and has no
duplicate elements.
Sets can be created by using the built-in set() function with sequence of objects.
Elements are placed inside curly braces, separated by a ‘comma’.
Ex:
set2 = {'abcd', 2, 3,'Python'}
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
Output:
{'abcd', 2, 3,'Python'}
{'abcd', 2, 3,'Python', 10}
Python Interpreter
Python is an interpreted language developed by Guido van Rossum in the year of
1991.
It is an interpreted language because it executes line-by-line instructions.
The Python interpreter is called “CPython” and it's written in the C programming
language.
Steps used:
• Lexing
• Parsing
• Creation of byte code
• Conversion to machine-executable code
• Returning output
Step 1: Lexing
In Lexing, single line of code executed by the interpreter is converted into smaller
parts. Each of these parts is called a token, and these tokens are generated by the lexer,
which is a part of the Python interpreter.
Step 2: Parsing
In this step, Parser performs the process of Parsing. Parsing is a process in which the
tokens generated in the Lexing stage is converted into a structure called Abstract
Syntax Tree.
Python interpreter checks for syntax errors, and if an error is found, the interpreter
stops translating code and shows an error message.
Step 3: Creation of Byte Code
In this step, compiler converts the Abstract Syntax Tree into an intermediate language
code, called bytecode. This is a compiled version of the original code, which is a low-
level, platform independent representation.
This byte code is stored in a file with the same name as the original source file, but
with a ‘.pyc’ extension instead of ‘.py’.
Step 4: Conversion to Machine-executable Code
Python Virtual Machine, or PVM is the actual runtime engine of Python.
It iterates through the byte code instructions stored in the file with .pyc extension. It
converts the statements into machine code, that is binary (0s and 1s).
It loads the inputs and libraries involved in the program, so that the required
instructions can be carried out successfully.
Step 5: Returning Output
After the code is converted to binary, it is executed by the interpreter. If there is an
error, it displays the message. Such an error is called a runtime error. If there is no
runtime error during program execution, then the interpreter prints the output and exits
successfully.
Keywords in Python
Python Keywords are some predefined and reserved words in Python that have special
meanings. The keyword cannot be used as an identifier, function, or variable name.
All the keywords in Python are written in lowercase except True and False. There are
35 keywords in Python 3.11.
Here is a list of all keywords in python programming.
Python Identifiers:
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-
sensitive.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _).
• It should not contain any special character other than an underscore ( _).
Ex:
myVariable="hello world"
print(myVariable)
var1=1
print(var1)
var2=2
print(var2)
Output:
Hello world
1
2
Literals
Literals in Python is defined as the raw data assigned to variables or constants .
Python supports the following literals:
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single
as well as double quotes to create a string.
Ex:
"Aman" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a) Single-line String- Strings that are terminated within a single-line are known as
Single line Strings.
Example:
text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as
multiple lines string.
There are two ways to create multiline strings:
1) Adding black slash at the end of each line.
Example:
text1='hello\
user'
print(text1)
'hellouser'
2) Using triple quotation marks: -
Example:
str2='''welcome
to
SSSIT'''
print str2
Output:
welcome
to
SSSIT
2. Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
Example:
x = 0b10100 #Binary Literals
y = 100 #Decimal Literal
z = 0o215 #Octal Literal
u = 0x12d #Hexadecimal Literal
#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:
20 100 141 301
100.5 150.0
(5+3.14j) 3.14 5.0
3. Boolean literals:
A Boolean literal can have any of the two values: True or False.
Example:
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
4. Special literals:
Python contains one special literal i.e., None.
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
5.Literal Collections:
Python provides the four types of literal collection such as List literals, Tuple literals,
Dict literals, and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by comma(,) and enclosed within square
brackets([]). We can store different types of data in a List.
Ex:
list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
Dictionary:
Python dictionary stores the data in the key-value pair.
It is enclosed by curly-braces {} and each pair is separated by the commas(,).
Ex:
dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
Python tuple is a collection of different data-type. It is immutable which means it
cannot be modified after creation.
It is enclosed by the parentheses () and each element is separated by the comma(,).
Ex:
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
Set:
Python set is the collection of the unordered dataset.
It is enclosed by the {} and each element is separated by the comma(,).
Ex:
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}
Operators
Operators are used to perform operations on variables and values.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
Ex:
a=7
b=2
print ('Sum: ', a + b)
print ('Subtraction: ', a - b)
print ('Multiplication: ', a * b)
print ('Division: ', a / b)
print ('Floor Division: ', a // b)
print ('Modulo: ', a % b)
print ('Power: ', a ** b)
Output:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
2. Python Relational Operators
Relational operators compare two values/variables and return a boolean
result: True or False.
Ex:
a=5
b=2
print('a == b =', a == b)
print('a != b =', a != b)
print('a > b =', a > b)
print('a < b =', a < b)
print('a >= b =', a >= b)
print('a <= b =', a <= b)
Output:
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
3. Logical or Boolean operator
Logical operators are used to check whether an expression is True or False. They are
used in decision-making.
AND
and a and b
True only if both the operands are True
OR
or a or b
True if at least one of the operands is True
NOT
not not a
True if the operand is False and vice-versa.
Ex:
print(True and True) # True
print(True and False) # False
print(True or False) # True
print(not True) # False
4. Assignment Operator
Assignment operators are used to assign values to variables.
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
Ex:
a = 10
b=5
a += b #a=a+b
print(a)
# Output: 15
5.Ternary operator
Ternary Operator determines if a condition is true or false and then returns the
appropriate value as the result.
Syntax:
true_value if condition else false_value
Ex:
a = 10
b = 20
min = "a is minimum" if a < b else "b is minimum"
print(min)
Output:
a is minimum
6.Bit wise operator
Bitwise operators act on operands as if they were strings of binary digits. They operate
bit by bit.
Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Defining Functions
Functions:
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
Ex:
def greet():
print('Hello World!')
Calling a Function
To call a function, use the function name followed by parenthesis:
Ex:
def greet():
print('Hello World!')
greet()
Python Function Arguments
Arguments are inputs given to the function.
def greet(name):
print("Hello", name)
greet("John")
Output:
Hello John
Example: Function to Add Two Numbers
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)
add_numbers(5, 4)
Output:
Sum: 9
The return Statement
We return a value from the function using the return statement.
Ex:
def find_square(num):
result = num * num
return result
square = find_square(3)
print('Square:', square)
Output:
Square: 9