Unit-1
Introduction to Python Programming
Introduction:
● Python is an interpreted, object-oriented, high-level programming language.
● Python is a powerful multipurpose 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 runtime by the interpreter. You do not need to compile
your program before executing 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 applications from simple text processing to WWW
browsers to games.
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
“statically 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 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
_ ).
● Variables in Python names are case-sensitive (name, Name, and NAME are three different
variables).
● The reserved words(keywords) in Python cannot be used to name the variable in Python.
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 multiple values to multiple 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 multiple 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 HelloWorld
Can we use + for different Data Types also?
NO
Python Assign Values to Multiple 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 function. We can not
call this variable outside the function.
Example:
# This function 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 function, and we
need to use them inside a function.
Example:
x = 15
def change():
# using a global keyword
global x
# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)
Output:
Value of x inside a function: 20
Value of x inside a function: 20
Python Basic Operators: The operator is a symbol that performs a certain operation between two
operands, according to one definition. In a particular programming language, operators serve as the
foundation upon which logic is constructed in a programme.
The different operators that Python offers are listed here.
1. Arithmetic Operators: Arithmetic operations between two operands are carried out using
arithmetic operators. It includes the exponent (**) operator as well as the + (addition), - (subtraction),
* (multiplication), / (divide), % (remainder), and // (floor division) operators.
Operator Description
+ (Addition)
It is used to add two operands. For example, if a = 10,
b = 10 => a+b = 20
- (Subtraction)
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 negative. For
example, if a = 20, b = 5 => a - b = 15
/ (divide)
It returns the quotient after dividing the first operand by the second operand. For example, if a =
20, b = 10 => a/b = 2.0
*(Multiplication)
It is used to multiply one operand with the other. For
example, if a = 20, b = 4 => a * b = 80
% (reminder)
It returns the remainder after dividing the first operand by the second operand. For example, if a =
20, b = 10 => a%b = 0
** (Exponent)
As it calculates the first operand's power to the second operand, it is an exponent operator.
// (Floor division)
It provides the quotient'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 Description
==
If the value of two operands is equal, then the condition becomes true.
!=
If the value of two operands is not equal, then the condition becomes true.
<=
The condition is met if the first operand is smaller than or equal to the second.
>=
The condition 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 condition becomes true.
<
If the first operand is less than the second operand, then the condition becomes true.
3. Assignment Operators: The right expression's value is assigned to the left operand using the
assignment operators.
Operator Description
=
It assigns the value of the right expression to the left operand.
+=
By multiplying the value of the right operand by the value of the left operand, the left 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 left operand using the
assignment operators.
Operator Description
=
It assigns the value of the right expression to the left operand.
+=
By multiplying the value of the right operand by the value of the left operand, the left 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 left operand by the value of the right operand and assigns the modified
value back to
the left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*=
It multiplies the value of the left operand by the value of the right operand and assigns the modified
value back to
the left 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 left operand by the value of the right operand and assigns the reminder back
to the left
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 Description
& (binary and)
A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is
copied.
| (binary or)
The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor)
If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation)
The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1, and vice
versa.
<< (left shift)
The number of bits in the right operand is multiplied by the leftward shift of the value of the left
operand.
>> (right shift)
The left 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 Description
and
The condition 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 condition 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 Exponentiation: **
3 Unary plus or minus, complement: -a , +a , ~a
4 Multiply, Divide, Modulo: /, *, //, %
5 Addition & Subtraction: +, –
6 Shift Operators: >>, <<
7 Bitwise AND: &
8 Bitwise XOR: ^
9 Bitwise OR: |
10 Comparison Operators: >=, <=, >, <
11 Equality Operators: ==, !=
12 Assignment Operators: =, +=, -=, /=, *=
13 Identity 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:
# Multi-operator expression
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output:
22
52
Operator Associativity:
The term "operator associativity" refers to the order in which operators of the same precedence are
evaluated when they appear consecutively in an expression. In Python, most operators have left-to-
right associativity, which means they are evaluated from left to right.
Here's a summary of the operator associativity in Python:
1. Left-to-Right Associativity:
● Arithmetic Operators: +, -, *, /, %, //, **
● Assignment Operators: =, +=, -=, *=, /=, %=, //=, **=
● Bitwise Operators: &, |, ^, <<, >>
● Comparison Operators: ==,!=, >, <, >=, <=
● Logical Operators: and, or
2. Right-to-Left Associativity:
● Exponentiation Operator: **
● Unary Operators: - (negation), + (unary plus), ~ (bitwise NOT)
It's important to note that associativity 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 associativity.
For example, consider the expression a + b - c. Both + and - have the same left-to-right associativity,
so the expression is evaluated from left to right: (a + b) - c.
On the other hand, for the exponentiation operator (**), it has right-to-left associativity. So, in the
expression a ** b ** c, the exponentiation is evaluated from right to left: a ** (b ** c).
Understanding Python Blocks:
In Python, blocks of code are defined by their indentation level. Unlike many other programming
languages that use curly braces `{}`or keywords like `begin` and `end` to define blocks, Python uses
indentation 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 ("Still in the loop")
print ("Outside the loop")
`In this example, the block of code `print(i)`and `print ("Still in the loop")`is executed for each iteration
of the loop, while the `print("Outside the loop")`statement is only executed once, after the loop has
finished. Similarly, in conditional statements like `if`, `elif`, and `else`, the block of code that is executed
conditionally 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 indentation throughout your code. The standard convention is to
use four spaces for each level of indentation.
Python Data Types:
Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. The following are the standard or built-in
data types in Python:
What is Python type () Function?
To define the values of various data types and check their data types we use the type() function.
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, dictionary, 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} #dictionary
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 floating 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 positive or negative whole numbers
(without fractions 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 floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive
or negative integer may be appended to specify scientific notation.
● 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 () function 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 collection of similar or different data types.
Sequences allow storing of multiple values in an organised and efficient fashion. There are several
sequence types in Python –
● Python String
● Python List
● Python Tuple
a. String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote, or triple-quote. In Python there is no character
data type, a character is a string of length one. It is represented by str class.
str =” This is HelloWorld”
print(str) #This is HelloWorld
b. List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
list = [‘HelloWorld’]
print(list) #[‘HelloWorld’]
c. Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a
tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by a tuple class.
tuple = (‘Hello’, ‘World’)
print(tuple) # (‘Hello’, ‘World’)
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
In Python, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
set1 = {'James', 2, 3,'Python'}
#Printing Set value
print(set1) #{3, 'Python', 'James', 2}
5. Dictionary Data Type in Python:
A dictionary in Python is an unordered collection of data values, used to store data values like a map,
unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value
pair. Key-value is provided in the dictionary to make it more optimised. Each key-value pair in a
Dictionary is separated by a colon: , whereas each key is separated by a ‘comma’.
Dict = {1: ‘Hello’, 2: 'For', 3: ‘World’}
print (Dict) # {1: ‘Hello’, 2: 'For', 3: ‘World’}