unit 1
unit 1
High Level Language: Python don’t let you worry about low-level details, like memory
management, hardware-level operations etc.
Python is Interpreted: Code is executed line-by-line directly by interpreter, and no need for
separate compilation. Which means –
You can run the same code across different platforms.
You can make the changes in code without restarting the program.
Dynamic Typed: Python is a dynamic language, meaning there are no need to explicitly
declare the data type of a variable. Type is checked during runtime, not at compile time.
Object Oriented: Python supports object-oriented concepts like classes, inheritance, and
polymorphism etc. OOPs empowers Python with modularity, reusability and easy to maintain
code.
Extensive Library are Available: Python has huge set of library and modules, which can
make development lot easier and faster.
Open-Source with Huge community Support: Along with opensource, Python is blessed
with very large community contributing to its further development.
Cross Platform: Same Python code can run on Windows, macOS and Linux, without any
modification in code.
Good Career Opportunities: Python is in high demand across industries like Software
development, AI, finance, and cloud computing etc.
Python Interpreter
Python is an interpreted language because it executes line-by-line instructions. There are
actually two way to execute python code one is in Interactive mode and another thing is
having Python prompts which is also called script mode. Python does not convert high level
code into low level code as many other programming languages do rather it will scan the
entire code into something called bytecode. every time when Python developer runs the code
and start to execute the compilation part execute first and then it generate an byte code which
get converted by PVM Python Virtual machine that understand the analogy and give the
desired output.
Interpreters
Interpreters are the computer program that will convert the source code or an high level
language into intermediate code (machine level language). It is also called translator in
programming terminology. Interpreters executes each line of statements slowly. This process
is called Interpretation. For example Python is an interpreted language, PHP, Ruby, and
JavaScript.
Working of Interpreter
Example: Here is the simple Python program that takes two inputs as a and b and prints the
sum in the third variable which is c. It follows sequential as well as functional execution of
programs
a=3
b=7
c=a+b
print(c) # output 10
Output
10
Python Syntax
Python syntax is like grammar for this programming language. Syntax refers to the set of
rules that defines how to write and organize code so that the Python interpreter can
understand and run it correctly. These rules ensure that your code is structured, formatted,
and error-free.
Indentation in Python
Python Indentation refers to the use of whitespace (spaces or tabs) at the beginning of code
line. It is used to define the code blocks. Indentation is crucial in Python because, unlike
many other programming languages that use braces "{}" to define blocks, Python uses
indentation. It improves the readability of Python code, but on other hand it became difficult
to rectify indentation errors. Even one extra or less space can leads to indentation error.
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
Python Data Types
Python 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. Since everything is
an object in Python programming, Python data types are classes and variables are instances
(objects) of these classes. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have
a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and
so on. An integer can be any length you want in Python. Its worth has a place with int.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate
to within 15 decimal places.
Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like
2.14j, 2.0 + 2.3j, etc.
Sequence Type
String
The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Example - 1
Output:
List
Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections [].
Output:
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
Output:
<class 'tuple'>
('hi', 'Python', 2)
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
Example.
Output:
Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. True and False can be represented by 0 or any
value that is not zero.
Example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used to
create the set. It can contain different kinds of values.
Output:
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other
value.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer
results after all computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b =5
c =a /b
print(c)
Output
2.6
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is
equal to 9. As we know it is not correct, so it will return False. Studying logical expressions,
we also come across some logical operators which can be seen in logical expressions most
often. Here are some logical operators in Python:
Example:
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
But when we combine different types of expressions or use multiple operators in a single
expression, operator precedence comes into play.
It’s a quite simple process to get the result of an expression if there is only one operator in an
expression. But if there is more than one operator in an expression, it may give different
results on basis of the order of operators executed. To sort out these confusions, the operator
precedence is defined. Operator Precedence simply defines the priority of operators that
which operator is to be executed first. Here we see the operator precedence in Python, where
the operator higher in the list has more precedence or priority:
# Multi-operator expression
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
Control flow refers to the order in which statements within a program execute. While programs
typically follow a sequential flow from top to bottom, there are scenarios where we need more
flexibility.
Control flow statements are fundamental components of programming languages that allow
developers to control the order in which instructions are executed in a program. They enable
execution of a block of code multiple times, execute a block of code based on conditions,
terminate or skip the execution of certain lines of code, etc.
1. Conditional statements
2. Iterative statements.
3. Transfer statements
Conditional statements
In Python, condition statements act depending on whether a given condition is true or false.
Different blocks of codes can be executed depending on the outcome of a condition.
Condition statements always evaluate to either True or False.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
Iterative statements
In Python, iterative statements allow us to execute a block of code repeatedly as long as the
condition is True. It can all as loop statements.
Python provides us the following two loop statement to perform some actions repeatedly
1. for loop
2. while loop
Transfer statements
In Python, transfer statements are used to alter the program’s way of execution in a certain
manner. For this purpose, we use three types of transfer statements.
1. break statement
2. continue statement
3. pass statements
If statement in Python
In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False.
If the condition is True, then the True block of code will be executed, and if the condition is
False, then the block of code is skipped, and The controller moves to the next line
if condition:
statement 1
statement 2
statement n
Python if statements
Let’s see the example of the if statement. In this example, we will calculate the square of a
number if it greater than 5
Example
number = 6
if number > 5:
# Calculate square
print(number * number)
print('Next lines of code')
Output
36
Next lines of code
If – else statement
The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.
if condition:
statement 1
else:
statement 2
If the condition is True, then statement 1 will be executed If the condition is False, statement
2 will be executed. See the following flowchart for more detail.
Example
if password == "PYnative@#29":
print("Correct password")
else:
print("Incorrect Password")
Output 1:
In Python, the if-elif-else condition statement has an elif blocks to chain multiple
conditions one after another. This is useful when you need to check multiple conditions.
With the help of if-elif-else we can make a tricky decision. The elif statement checks
multiple conditions one by one and if the condition fulfills, then executes that code.
if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement
Example
def user_check(choice):
if choice == 1:
print("Admin")
elif choice == 2:
print("Editor")
elif choice == 3:
print("Guest")
else:
print("Wrong entry")
user_check(1)
user_check(2)
user_check(3)
user_check(4)
Output:
Admin
Editor
Guest
Wrong entry
In Python, the nested if-else statement is an if statement inside another if-else statement.
It is allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is useful
when we want to make a series of decisions.
if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement ot outer if
else:
Outer else
statement outside if block
Output 1:
Output 2:
Instead of writing a block after the colon, we can write a statement immediately after the
colon.
Example
number = 56
if number > 0: print("positive")
else: print("negative")
Similar to the if statement, while loop also consists of a single statement, we can place that
statement on the same line.
Example
x = 1
while x <= 5: print(x,end=" "); x = x+1
Output
1 2 3 4 5
Output
1
2
3
4
5
6
7
8
9
10
In a while-loop, every time the condition is checked at the beginning of the loop, and if it is
true, then the loop’s body gets executed. When the condition became False, the controller
comes out of the block.
Syntax of while-loop
while condition :
body of while loop
num = 10
sum = 0
i = 1
while i <= num:
sum = sum + i
i = i + 1
print("Sum of first 10 number is:", sum)
Output
Sum of first 10 number is: 55
Output
0
1
2
3
4
5
stop processing.
Let’s see how to skip a for a loop iteration if the number is 5 and continue executing the body
of the loop for other numbers.
Output
3
4
6
7
A pass statement is a Python null statement. When the interpreter finds a pass statement in
the program, it returns no operation. Nothing happens when the pass statement is executed.
Example
Output
Unit II
List Comprehensions
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of list comprehension:
Syntax: output_list = [output_exp for var in input_list if (var satisfies this condition)]
It creates a new list named list_using_comp by iterating through each element var in the
input_list. Elements are included in the new list only if they satisfy the condition, which
checks if the element is even. As a result, the output list will contain all even numbers.
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Output:
Dictionary Comprehensions
Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}
Example 1: Generating odd number with their cube values without using dictionary
comprehension
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
Output:
Example 2: Generating odd number with their cube values with using dictionary
comprehension
input_list = [1,2,3,4,5,6,7]
Output:
Set Comprehensions
Set comprehensions are pretty similar to list comprehensions. The only difference between
them is that set comprehensions use curly brackets { }
Suppose we want to create an output set which contains only the even numbers that are
present in the input list. Note that set will discard all the duplicate values.
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
Output:
We will use set comprehension to initializes a list with integer values. The code then creates a
new set using set comprehension. It iterates through the elements of the input_list, and for
each element, it checks whether it’s even. If the condition is met, the element is added to the
set. The printed output which will contain unique even numbers from the list.
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp)
Output:
Generator Comprehensions
Generator Comprehensions are very similar to list comprehensions. One difference between
them is that generator comprehensions use circular brackets whereas list comprehensions use
square brackets. The major difference between them is that generators don’t allocate memory
for the whole list. Instead, they generate each value one by one which is why they are
memory efficient.
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
Output: