Unit-1
Introduc on to Python Programming
Introduc on to Python: Python variables, Python basic Operators, Understanding
python blocks. Python Data Types, Declaring and using Numeric data types: int,
float etc.
Introduc on:
● Python is an interpreted, object-oriented, high-level programming language.
● Python is a powerful mul purpose programming language created by Guido van Rossum.
● It has a simple and easy-to-use syntax, making it a popular first-choice programming language for
beginners.
Python is Interpreted: Python is processed at run me by the interpreter. You do not need to compile
your program before execu ng it. This is similar to PERL and PHP.
Python is Object-Oriented: Python supports an Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for beginner-level programmers and
supports the development of a wide range of applica ons from simple text processing to WWW
browsers to games.
Token in python:
Tokens in Python are the smallest individual units of a program that are meaningful to the
interpreter. They are the fundamental building blocks from which all Python code is constructed.
There are five main types of tokens in Python:
Keywords:
These are reserved words that have predefined meanings and cannot be used as iden fiers
(e.g., if, else, while, for, def, class, True, False, None).
Currently, Python has 35 keywords.
Fig: list of 35 keywords
Iden fiers:
These are names given by the programmer to iden fy various en es in the program, such as
variables, func ons, classes, modules, or objects. They must follow specific naming rules
(e.g., my_variable, calculate_sum, MyClass).
Literals:
These represent fixed values in the code. They can be numbers (integers, floats, complex numbers),
strings, booleans, or special literals like None (e.g., 10, 3.14, 'hello', True).
Operators:
These are symbols that perform opera ons on operands (values or variables). Examples include
arithme c operators (+, -, *, /), comparison operators (==, !=, <, >), logical operators (and, or, not),
and assignment operators (=, +=).
Punctuators:
These are symbols used to define the structure and grammar of the Python code. They include
parentheses (), square brackets [], curly braces {}, commas ,, colons :, semicolons ;, and dots ..
Python Variables:
Variables are like containers that store values. In Python, you can create a variable and assign a value
to it using the assignment operator (=). For example, name = "John" assigns the value "John" to the
variable name. Variables allow you to store and manipulate data in your programs. Python is not
“sta cally typed”. We do not need to declare variables before using them or declare their type.
Rules for Python variables
● A Python variable name must start with a le er 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
_ ).
● Variables in Python names are case-sensi ve (name, Name, and NAME are three different
variables).
● The reserved words(keywords) in Python cannot be used to name the variable in Python.
Valid Example of variables:
age = 21
_colour = "lilac"
total_score = 90
Invalid Example of variables:
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
1. Example: Var = "HelloWorld" print(Var)
Output: HelloWorld
2. Example: Changing the Value of a Variable in Python
site_name = 'HelloWorld' print(site_name)
# assigning a new value to site_name
site_name = ‘World’
print(site_name) Output:
HelloWorld
Desire
3. Example: Assigning mul ple values to mul ple
variables a, b, c = 5, 3.2, '‘Hello' print(a) # prints 5
print(b) # prints 3.2
print(c) # prints ‘Hello
4. Example: Assign the same value to mul ple variables
site1 = site2 = 'HelloWorld'
print(site1) # prints HelloWorld
print(site2) # prints HelloWorld
How does + operator work with variables?
The Python plus operator + provides a convenient way to add a value if it is a number and concatenate
if it is a string. If a variable is already created it assigns the new value back to the same variable.
a = 10
b = 20
print(a+b) #prints 30
a = "Edu"
b = "Desire"
print(a+b) #prints EduDesire
Can we use + for different Data Types also?
NO
Python Assign Values to Mul ple Variables
Also, Python allows assigning a single value to several variables simultaneously with “=” operators.
Example:
a = b = c = 10 print(a)
#prints 10 print(b)
#prints 10
print(c) #prints 10
Global and Local Python Variables
1. Local variables in Python are the ones that are defined and declared inside a func on. We can not
call this variable outside the func on.
Example:
# This func on uses global variable s def
f():
s = "Welcome HelloWorld"
print(s) f()
Output: Welcome HelloWorld
2. Global variables in Python are the ones that are defined and declared outside a func on, and we
need to use them inside a func on.
Example:
x = 10 # Global variable
def show():
print("Inside func on, x =", x)
show()
print("Outside func on, x =", x)
Output:
Inside func on, x = 10
Outside func on, x = 10
Global vs Local Variables:
x = 50 # Global variable
def test():
x = 20 # Local variable
print("Inside func on, local x =", x)
test()
print("Outside func on, global x =", x)
Output:
Inside func on, local x = 20
Outside func on, global x = 50
Python Basic Operators: The operator is a symbol that performs a certain opera on between two
operands, according to one defini on. In a par cular programming language, operators serve as the
founda on upon which logic is constructed in a programme.
The different operators that Python offers are listed here:
1. Arithme c Operators: Arithme c opera ons between two operands are carried out using arithme c
operators. It includes the exponent (**) operator as well as the + (addi on), - (subtrac on), *
(mul plica on), / (divide), % (remainder), and // (floor division) operators.
Operator Descrip on
+ (Addi on):
It is used to add two operands. For example, if a = 10,
b = 10 => a+b = 20
- (Subtrac on):
It is used to subtract the second operand from the first operand. If the first operand is less than the
second operand, the value results nega ve. For
example, if a = 20, b = 5 => a - b = 15
/ (divide):
It returns the quo ent a er dividing the first operand by the second operand. For example, if a = 20,
b = 10 => a/b = 2.0
*(Mul plica on) :
It is used to mul ply one operand with the other. For example,
if a = 20, b = 4 => a * b = 80
% (Modulus)/reminder
It returns the remainder a er dividing the first operand by the second operand. For example, if a = 20,
b = 10 => a%b = 0
** (Exponent)/Power:
As it calculates the first operand's power to the second operand, it is an exponent operator.
// (Floor division)
It provides the quo ent's floor value, which is obtained by dividing the two operands.
2. Comparison operator: Comparison operators compare the values of the two operands and return a
true or false Boolean value in accordance.
Operator Descrip on
==
If the value of two operands is equal, then the condi on becomes true.
!=
If the value of two operands is not equal, then the condi on becomes true.
<=
The condi on is met if the first operand is smaller than or equal to the second.
>=
The condi on is met if the first operand is greater than or equal to the second.
>
If the first operand is greater than the second operand, then the condi on becomes true.
<
If the first operand is less than the second operand, then the condi on becomes true.
3. Assignment Operators: The right expression's value is assigned to the le operand using the
assignment operators.
Operator Descrip on
=
It assigns the value of the right expression to the le operand.
+=
By mul plying the value of the right operand by the value of the le operand, the le operand receives
a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
3. Assignment Operators: The right expression's value is assigned to the le operand using the
assignment operators.
Operator Descrip on
=
It assigns the value of the right expression to the le operand.
+=
By mul plying the value of the right operand by the value of the le operand, the le operand receives
a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-=
It decreases the value of the le operand by the value of the right operand and assigns the modified
value back to the le operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*=
It mul plies the value of the le operand by the value of the right operand and assigns the modified
value back to the le operand. For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.
%=
It divides the value of the le operand by the value of the right operand and assigns the reminder back
to the le operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a
= 0.
**= a**=b will be equal to a=a**b, for example, if a = 4,
b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b
will assign 4//3 = 1 to a.
4. Bitwise Operators: The two operands' values are processed bit by bit by the bitwise operators.
Operator Descrip on
& (binary and)
A 1 is copied to the result if both bits in two operands at the same loca on are 1. If not, 0 is copied.
| (binary or)
The resul ng bit will be 0 if both the bits are zero; otherwise, the resul ng bit will be 1.
^ (binary xor)
If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (nega on)
The operand's bits are calculated as their nega ons, so if one bit is 0, the next bit will be 1, and vice
versa.
<< (le shi )
The number of bits in the right operand is mul plied by the le ward shi of the value of the le
operand.
>> (right shi )
The le operand is moved right by the number of bits present in the right operand.
Logical Operators: The assessment of expressions to make decisions typically makes use of the logical
operators. The following logical operators are supported by Python.
Operator Descrip on
and
The condi on will also be true if the expression is true. If the two expressions a and b are the same,
then a and b must both be true. or
The condi on will be true if one of the phrases is true. If a and b are the two expressions, then a or b
must be true if and is true and b is false. not
If an expression is true, then not (a) will be false and vice versa.
Operator Precedence:
Operator Precedence simply defines the priority of operators that which operator is to be executed
first.
Precedence Name Operator
1 Parenthesis: ( ), [ ], { }
2 Exponen a on: **
3 Unary plus or minus, complement: -a , +a , ~a
4 Mul ply, Divide, Modulo: /, *, //, %
5 Addi on & Subtrac on: +, –
6 Shi Operators: >>, <<
7 Bitwise AND: &
8 Bitwise XOR: ^
9 Bitwise OR: |
10 Comparison Operators: >=, <=, >, <
11 Equality Operators: ==, !=
12 Assignment Operators: =, +=, -=, /=, *=
13 Iden ty and membership operators: is, is not, in, not in
14 Logical Operators: and, or, not
● So, if we have more than one operator in an expression, it is evaluated as per operator precedence.
● For example, if we have the expression “10 + 3 * 4”. Going without precedence it could have given
two different outputs 22 or 52.
● But now looking at operator precedence, it must yield 22.
Let’s discuss this with the help of a Python program:
# Mul -operator expression a
= 10 + 3 * 4
print(a) b = (10
+ 3) * 4
print(b) c = 10
+ (3 * 4)
print(c)
Output:
22
52
Operator Associa vity:
The term "operator associa vity" refers to the order in which operators of the same precedence are
evaluated when they appear consecu vely in an expression. In Python, most operators have le -
toright associa vity, which means they are evaluated from le to right.
Here's a summary of the operator associa vity in Python:
1. Le -to-Right Associa vity:
● Arithme c Operators: +, -, *, /, %, //, **
● Bitwise Operators: &, |, ^, <<, >>
● Comparison Operators: ==,!=, >, <, >=, <=
● Logical Operators: and, or
2. Right-to-Le Associa vity:
● Exponen a on Operator: **
● Unary Operators: - (nega on), + (unary plus), ~ (bitwise NOT)
● Assignment Operators: =, +=, -=, *=, /=, %=, //=, **=
It's important to note that associa vity only comes into play when operators have the same
precedence. If operators have different precedencies, the one with higher precedence is evaluated first
regardless of associa vity.
For example, consider the expression a + b - c. Both + and - have the same le -to-right associa vity, so
the expression is evaluated from le to right: (a + b) - c.
On the other hand, for the exponen a on operator (**), it has right-to-le associa vity. So, in the
expression a ** b ** c, the exponen a on is evaluated from right to le : a ** (b ** c).
Understanding Python Blocks/Indenta ons:
In Python, blocks of code are defined by their indenta on level. Unlike many other programming
languages that use curly braces `{}`or keywords like `begin` and `end` to define blocks, Python uses
indenta on to indicate the beginning and end of blocks. Blocks are also used to define the scope of
variables. The scope of a variable is the part of the program where the variable is accessible. The scope
of a variable in a block is limited to the block itself. This means that a variable defined in a block cannot
be accessed outside of the block.
For example, in a `for` loop, the block of code to be executed inside the loop is indented:
for i in range (5):
print(i)
print ("S ll in the loop")
print ("Outside the loop")
`In this example, the block of code `print(i)`and `print ("S ll in the loop")`is executed for each itera on
of the loop, while the `print("Outside the loop")`statement is only executed once, a er the loop has
finished. Similarly, in condi onal statements like `if`, `elif`, and `else`, the block of code that is executed
condi onally is also indented:
x = 10
if x > 5:
print ("x is greater than 5")
else:
print ("x is not greater than 5")
It’s important to maintain consistent indenta on throughout your code. The standard conven on is to
use four spaces for each level of indenta on.
Python Data Types:
Data types are the classifica on or categoriza on of data items. It represents the kind of value that
tells what opera ons can be performed on a par cular data. The following are the standard or built-in
data types in Python:
What is Python type () Func on?
To define the values of various data types and check their data types we use the type() func on.
Consider the following examples. This code assigns variable ‘x’ different values of various data types in
Python. It covers string, integer, float, complex, list, tuple, range, dic onary, set, boolean, and the
special value ‘None’ successively. Each assignment replaces the previous value, making ‘x’ take on the
data type and value of the most recent assignment.
x = "HelloWorld" #string
x = 50 #integer
x = 60.5 #float
x = 3j #complex
x = ["geeks", "for", "geeks"] #list
x = ("geeks", "for", "geeks")#tuple
x = range(10) #range
x = {"name": "Suraj", "age": 24} #dic onary
x = {"geeks", "for", "geeks"} #set
x = True #boolean
x = None #none
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value can be
an integer, a floa ng number, or even a complex number. These values are defined as Python int,
Python float, and Python complex classes in Python.
● Integers: This value is represented by int class. It contains posi ve or nega ve whole numbers
(without frac ons or decimals). In Python, there is no limit to how long an integer value can be.
● Float: This value is represented by the float class. It is a real number with a floa ng-point
representa on. It is specified by a decimal point. Op onally, the character e or E followed by a posi ve
or nega ve integer may be appended to specify scien fic nota on.
● Complex Numbers: A complex number is represented by a complex class. It is specified as (real
part) + (imaginary part) j. For example – 2+3j
Note: type () func on is used to determine the type of data type.
Example:
a=5
print ("Type of a: ", type(a)) #Type of a: <class ‘int’>
b = 5.0
print ("\nType of b: ", type(b)) #Type of b: <class ‘float’>
c = 2 + 4j
print ("\nType of c: ", type(c)) #Type of c: <class ‘complex’>
2. Sequence Data Type in Python:
The sequence Data Type in Python is the ordered collec on of similar or different data types.
Sequences allow storing of mul ple values in an organised and efficient fashion. There are several
sequence types in Python –
● Python String
● Python List
● Python Tuple
a. String Data Type
• A string is a sequence of characters enclosed in single quote(‘ ‘) , double quotes (“ “) and triple
quotes(‘ ‘ ‘ ‘ ‘ ‘) for mul -line strings.
Examples:
string1 = "Hello, World!"
string2 = 'Python is fun’
String3= ‘ ‘ ‘ this is a mul line
String which is used for more than one line. ‘ ‘ ‘
Characteris cs:
• Immutable: Once defined, it cannot be changed.
• Supports indexing and slicing.
Immutable:
Strings in Python cannot be modified a er crea on. Any opera on that "modifies" a string actually
creates a new string.
text = "Python"
text[0] = "J" # Raises TypeError
Common String Methods:
text=“ My name is Preety Pandey ”
Print(len(text)) # Returns the length of the string.
Print([Link]())#Convert to uppercase.
Print([Link]()) # Convert to lowercase.
Print([Link](“name", “self"))# Replace substrings
Print(text.find(“preety”))# Returns index of the first occurrence.
Print([Link](“ is”))# Returns the number of overlapping occurrences of the substring in the string.
Print([Link]())#Remove spaces
lstrip() → removes characters from the le side.
rstrip() → removes characters from the right side.
String Concatena on and Repe on:
Concatena on:
Combine strings using the + operator.
first = "Hello"
second = "World"
print(first + " " + second) # Output: Hello World
Repe on:
Repeat a string mul ple mes using the * operator.
word = "Hello "
print(word * 3) # Output: "Hello Hello Hello "
String forma ng:
String forma ng in Python is the process of inser ng values, variables, or expressions into a string in
a structured way, without using manual concatena on.
It allows us to create dynamic and readable strings by placing placeholders inside the string and then
filling them with actual values.
Example:
name = "Preety"
age = 22
print(“My name is”+name+”and I am”+str(age)+”years old”)#without forma ng, using concatena on.
print(f"My name is {name} and I am {age} years old.")#forma ng
#both are same but a er using forma ng code becomes easier and there is no need to use type
conversion i.e it is flexible, works with string, float, int etc.
b. List Data Type
• An ordered, mutable (changeable) collec on of items.
• List is enclosed in square brackets [ ] and elements are separated by comma.
Characteris cs:
• Can contain elements of different types (int, float, str, etc.)
• Indexed star ng from 0.
• Supports various opera ons like append, remove, extend, reverse, sort, and slicing.
Syntax:
list = [1, 2, 3.0, "apple“, “fruits”]
Example:
fruits=[1,3,"apple","banana","cherry",4.0]
print(type(fruits))
print(fruits[2]) # print element at index 2
[Link]("orange") # Adds an element
print(fruits)
fruits[2]="blueberry“ # Modify an element
print(fruits)
print(fruits[1:5]) # Slicing
c. Tuple Data Type
Just like a list, a tuple is also an ordered collec on of Python objects. The only difference between a
tuple and a list is that tuples are immutable i.e. tuples cannot be modified a er it is created. It is
represented by a tuple class.
• An ordered, immutable (unchangeable) collec on of items.
• Tuple is enclosed in ( ) brackets.
Characteris cs:
• Once created, the items cannot be changed.
• It allows duplicate.
• Useful for storing fixed collec ons of data.
• Indexing and slicing work the same as lists.
Syntax:
numbers=(1,2,3,"apple")
Example:
numbers=(1,2,3,"apple“,2,4)
print(type(numbers))#datatype type
print(numbers[0]) # Accessing elements using index
print(numbers[1:4])# Slicing a tuple (ge ng a subset)
List vs Tuple:
3. Boolean Data Type in Python
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are
truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be evaluated
in a Boolean context as well and determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
print (type (True)) #<class ‘bool’>
print (type (False)) #<class ‘bool’>
4. Set Data Type in Python :
• Set is an unordered collec on of unique values.
• Defined using curly braces { } or ( ).
• Sets are mutable(changeable)
Characteris cs:
• Elements must be unique (no duplicates).
• Sets are unordered, meaning there is no indexing.
• O en used for opera ons like union, intersec on, difference, etc.
Syntax:
my_set={1,2,3,7,3,2,9,1}
my_set={1,2,3,7,3,2,9,1}
Print(my_set) # duplicates are automa cally removed.
my_set.add(6)
Print(my_set)# Adding elements to the set
my_set.remove(2)
Print(my_set)# Removing elements from the set
Set opera ons:
set_a={1,2,3}
set_b={3,4,5}
# Union: combines elements from both sets
print(set_a|set_b) # Output: {1, 2, 3, 4, 5}
# Intersec on: finds common elements
print(set_a&set_b) # Output: {3}
# Difference: elements in set_a but not in set_b
print(set_a - set_b) # Output: {1, 2}
5. Dic onary Data Type in Python:
• An unordered collec on of key-value pairs.
• We declare dic onaries using curly braces {} with key-value pairs separated by a colon :
Characteris cs:
• Keys must be unique and immutable objects (like strings, numbers, tuples).
• Values can be of any type and are changeable(mutable).
• Useful for mapping rela onships between keys and values (e.g., name to age).
Syntax:
my_dict={"name":"Preety","age":30,"city":"Indore"}
Examples:
my_dict={"name":"Preety","age":30,"city":"Indore"}
print(type(my_dict))
# Accessing values using keys
print(my_dict["name"])
print(my_dict['age'])
# Adding a new key-value pair
my_dict['email'] = '[Link]@[Link]'
print(my_dict)
# Modifying an exis ng value
my_dict['age'] = 26
print(my_dict['age'])