Module 1
Module 1
Module 1
Python Basics
Python Basics, Python language features, History , Entering Expressions into the Interactive Shell, The
Integer, Floating-Point, and String Data Types, String Concatenation and Replication, Storing Values in
Variables, Your First Program, Dissecting Your Program, Flow control, Boolean Values, Comparison
Operators, Boolean Operators, Mixing Boolean and Comparison Operators, Elements of Flow Control,
Program Execution, Flow Control Statements, Importing Modules, Ending a Program Early with
sys.exit(), Functions, def Statements with Parameters, Return Values and return Statements, The None
in
Value, Keyword Arguments and print(), Local and Global Scope, The global Statement, Exception
Handling, A Short Program: Guess the Number
.
artificial intelligence. Python is a dynamic, high-level, free open source, and interpreted
ud
programming language. It supports object- oriented programming as well as
procedural-oriented programming. In Python, we don’t need to declare the type of
variable because it is a dynamically typed language. For example, x = 10 Here, x can
be anything such as String, int, etc.
Salient features of Python:
1. Free and Open Source
lo
Python language is freely available at the official website and you can download it from
the given download link below click on the Download Python keyword. Download
Python Since it is open- source, this means that source code is also available to the
public. So you can download it, use it as well as share it.
uc
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 very easy to code
in the Python language and anybody can learn Python basics in a few hours or days. It
is also a developer-friendly language.
3. Object-Oriented Language
vt
Page 1
Python Programming-21EC643
in
Python is an Interpreted Language because Python code is executed line by line at a
time. like other languages C, C++, Java, etc. there is no need to compile Python code
this makes it easier to debug our code. The source code of Python is converted into an
immediate form called bytecode.
.
9. Large Standard Library
ud
Python has a large standard library that provides a rich set of modules and functions
so you do not have to write your own code for every single thing. There are many
libraries present in Python such as regular expressions, unit-testing, web browsers,
etc.
10. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int,
lo
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.
uc
Expressions consist of values (such as 2) and operators (such as +), and they can
always evaluate (that is, reduce) down to a single value.
>>>2
2
Page 2
Python Programming-21EC643
. in
ud
lo
The order of operations (also called precedence) of Python math operators is similar
to that of mathematics.
The ** operator is evaluated first; the *, /, //, and % operators are evaluated next,
from left to right; and the + and - operators are evaluated last (also from left to right).
uc
You can use parentheses to override the usual precedence if you need to.
Whitespace in between the operators and values doesn’t matter for Python.
Page 3
Python Programming-21EC643
in
The integer (or int) data type indicates values that are whole numbers.
.
Numbers with a decimal point, such as 3.14, are called floating-point
numbers (or floats).
ud
Python programs can also have text values called strings, or strs always
surrounded in single quote (').
You can even have a string with no characters in it, '', called a blank string or
an empty string.
lo
String Concatenation and Replication
The meaning of an operator may change based on the data types of the values next
to it. For example, + is the addition operator when it operates on two integers or
uc
floating-point values. However, when + is used on two string values, it joins the strings
as the string concatenation operator. Enter the following into the interactive shell:
However, if you try to use the + operator on a string and an integer value, Python
will not know how to handle this, and it will display an error message.
>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'Alice' + 42
TypeError: can only concatenate str (not "int") to str
Page 4
Python Programming-21EC643
>>> 'Alice' * 5
'AliceAliceAliceAliceAlice‘
The * operator can be used with only two numeric values (for multiplication), or one
string value and one integer value (for string replication).
in
>>> 'Alice' * 'Bob'
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
.
'Alice' * 'Bob'
TypeError: can't multiply sequence by non-int of type 'str'
>>> 'Alice' * 5.0
ud
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float'
lo
Storing Values in Variables
Variable is a named placeholder to hold any type of data which the program can use
to assign and modify during the course of execution. Variables should be valid
identifiers. An identifier is a name given to a variable, function, class or module.
uc
An identifier cannot start with a digit but is allowed everywhere else. 1plus is
invalid, but plus1 is perfectly fine.
Keywords cannot be used as identifiers. Keywords are a list of reserved words that
have predefined meaning. Keywords are special vocabulary and cannot be used by
programmers as identifiers for variables, functions, constants or with any identifier
name.
Spaces and special symbols like !, @, #, $, % etc. as identifiers.
Identifier can be of any length.
Page 5
Python Programming-21EC643
in
Assignment Statements
.
An assignment statement consists of a variable name, an equal sign (called
'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye'
In Python, built-in functions are pre-defined functions that are part of the
programming language and are available for use without the need to define
Page 6
Python Programming-21EC643
them. They can be used to perform various tasks such as input/output, data
type conversions, mathematical calculations, etc. Here are some examples of
commonly used built-in functions in Python:
print(): This function is used to output data to the screen. It takes one or more
arguments, which can be strings, numbers, or variables, and prints them to the
screen.
print('Hello,world!')
in
print('What is your name?') # ask for their name.
The line print('Hello, world!') means “Print out the text in the string 'Hello,
world!'.”
.
input(): This function is used to take input from the user. It takes a string as an
argument, which is used as a prompt for the user, and returns the input as a
string.
ud
name = input("What's your name? ")
print("Hello, " + name + "!")
myName=input()
print('The length of your name is:')
print(len(myName))
for i in range(5):
print(i)
These are just a few examples of the many built-in functions that are available in
Python. Some other commonly used built-in functions include abs(), pow(), round(),
sorted(), type(), etc. With the help of documentation, you can explore more built-in
functions and their usage.
Page 7
Python Programming-21EC643
Exercise:
in
7. to find area and perimeter of a circle.
.
2. print('hello world ' +int(100)+ ' how are you')
FLOW CONTROL
which conditions.
ud
Flow control statements can decide which Python instructions to execute under
In a flowchart, there is usually more than one way to go from the start to the end.
The starting and ending steps are represented with rounded rectangles.
uc
vt
Page 8
Python Programming-21EC643
Boolean Values
While the integer, floating-point, and string data types have an unlimited number of
possible values, the Boolean data type has only two values: True and False.
When entered as Python code, the Boolean values True and False lack the quotes
you place around strings, and they always start with a capital T or F, with the rest of
the word in lowercase.
>>> spam=True
in
>>> spam
True
.
>>> spam=true
ud
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError:
name 'true' is not defined. Did you mean: 'True'?
>>> True=2+2
Page 9
Python Programming-21EC643
. in
ud
lo
uc
Assignment Operators
Assignment operators are used for assigning the values generated after evaluating
the right operand to the left operand.
vt
Assignment operation always works from right to left. Assignment operators are
either simple assignment operator or compound assignment operators.
Simple assignment is done with the equal sign (=) and simply assigns the value of
its right operand to the variable on the left.
Page 10
Python Programming-21EC643
in
.
ud
lo
Solve:
3/2*4+3+(10/4)**3-3
uc
= 3/2*4+3+(2.5)**3-3
= 3/2*4+3+2.5**3-3
= 3/2*4+3+ 15.625-3
vt
= 1.5*4+3+ 15.625-3
= 6.0+3+ 15.625-3
= 9.0+ 15.625-3
= 24.625-3
= 21.625
Page 11
Python Programming-21EC643
. in
Boolean Operators
ud
The three Boolean operators (and, or, and not) are used to compare Boolean values.
Like comparison operators, they evaluate these expressions down to a Boolean value.
Let’s explore these operators in detail.
lo
Binary Boolean Operators:
The and and or operators always take two Boolean values (or expressions), so
they’re considered binary operators.
uc
The and operator evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.
Page 12
Python Programming-21EC643
A truth table shows every possible result of a Boolean operator. Table is the truth
table for the and operator.
in
On the other hand, the or operator evaluates an expression to True if either of the
two Boolean values is True. If both are False, it evaluates to False.
.
>>> False or True
True
Unlike and and or, the not operator operates on only one Boolean value (or
vt
expression). This makes it a unary operator. The not operator simply evaluates to the
opposite Boolean value.
Page 13
Python Programming-21EC643
Examples:
in
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
.
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
ud
Write a Python program to illustrate the Comparison operators
a=input()
lo
print("Enter the value of b: ")
b=input()
c=int(a)==int(b)
uc
print(c)
c=int(a)!=int(b)
print(c)
vt
c=int(a)<int(b)
print(c)
c=int(a)>int(b)
print(c)
c=int(a)<=int(b)
Page 14
Python Programming-21EC643
print(c)
c=int(a)>=int(b)
print(c)
in
a=input()
b=input()
.
c=(int(a)==int(b)) and (int(a)!=int(b))
print(c)
ud
c=(int(a)==int(b)) or (int(a)!=int(b))
print(c)
lo
c=not (int(a)==int(b))
print(c)
a. if statement
b. if else statement
Page 15
Python Programming-21EC643
c. if elif statement
a. if statement:
in
# execute code block
Example:
If i % 2 ==0:
print(“Number is Even”)
.
If i%2==1:
Flowchart:
ud
print(“Number is Odd”)
lo
uc
vt
Exercise:
Page 16
Python Programming-21EC643
b. if else statement
The if statement executes the code block when the condition is true. Similarly, the else
statement works in conjuncture with the if statement to execute a code block when the
defined if condition is false.
Syntax
if condition:
in
else:
.
Flowchart
ud
lo
uc
vt
Example:
If a>b:
print(“A is big”)
else:
print(“B is big”)
Page 17
Python Programming-21EC643
Exercise:
c. If elif statement:
in
The elif statement is used to check for multiple conditions and execute the code
block within if any of the conditions evaluate to be true.
The elif statement is similar to the else statement in the context that it is optional
.
but unlike the else statement, there can be multiple elif statements in a code
block following an if statement.
Syntax:
if condition1: ud
# execute this statement
elif condition2:
# execute this statement
lo
.
.
else:
# if non of the above conditions
uc
# evaluate to True
# execute this statement
Example:
num = int(input(‘Enter a number’))
if num > 0:
vt
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Page 18
Python Programming-21EC643
Flowchart
. in
Exercise: ud
1. WAP to check if the number is positive, negative or equal to zero.
lo
2. WAP to check the greatest of 3 numbers.
4.
In Python, break and continue are loop control statements executed inside a loop.
These statements either skip according to the conditions inside the loop or terminate
the loop execution at some point.
vt
Break Statement
The break statement is used to terminate the loop immediately when it is
encountered. The syntax of the break statement is:
break
A break statement is used inside both the while and for loops. It terminates the loop
immediately and transfers execution to the new statement after the loop. For
example, have a look at the code and its output below:
Page 19
Python Programming-21EC643
count = 0
while count <= 100:
print (count)
count += 1
if count == 3:
break
Program output:
0
1
in
2
In the above example loop, we want to print the values between 0 and 100, but there
is a condition here that the loop will terminate when the variable count becomes
equal to 3.
.
ud
lo
uc
vt
Continue Statement
The continue statement causes the loop to skip its current execution at some point
and move on to the next iteration. Instead of terminating the loop like a break
statement, it moves on to the subsequent execution. The continue statement is used
to skip the current iteration of the loop and the control flow of the program goes to
the next iteration.
for i in range(0, 5):
if i == 3:
continue
Page 20
Python Programming-21EC643
print(i)
Program output:
0
1
2
4
In the above example loop, we want to print the values between 0 and 5, but there is
in
a condition that the loop execution skips when the variable count becomes equal to
3.
.
ud
lo
uc
vt
Page 21
Python Programming-21EC643
password = input()
if password == 'swordfish':
print('Access granted.')
break
. in
ud
lo
uc
The main Difference between break and continue in python is loop terminate. In this
tutorial, we will explain the use of break and the continue statements in the python
language. The break statement will exist in python to get exit or break for and while
conditional loop. The break and continue can alter flow of normal loops and iterate
over the block of code until test expression is false.
Page 22
Python Programming-21EC643
Basis for
break continue
comparison
in
The ‘continue’ will
‘break’ will resume control of resume the control of the
Control after
program to the end of loop program to next iteration
break/continue
enclosing that ‘break’. of that loop enclosing
.
‘continue'
causes ud
It early terminates the loop.
It causes the early
execution of
the next iteration.
lo
The ‘continue’ does not
The ‘break ‘stop the continuation stop the continuation of
continuation
of the loop. loop and it stops the
current.
uc
while conditional_expression:
#Code block of while
Page 23
Python Programming-21EC643
. in
Python While Loop Example
ud
Here we will sum of squares of the first 15 natural numbers using a while loop.
lo
Code
num = 15
summation = 0
c=1
uc
Output:
vt
name = ''
Page 24
Python Programming-21EC643
name = input()
print('Thank you!')
. in
ud
lo
Alternative way
uc
name = ''
name = input()
break
print('Thank you!')
Page 25
Python Programming-21EC643
. in
ud
lo
for Loops and the range() Function:
The for loop is used to run a block of code for a certain number of times. It is used to
iterate over any sequences such as list, tuple, string, etc.
uc
Here, val accesses each item of sequence on each iteration. Loop continues until we
reach the last item in the sequence.
vt
for i in range(5):
• A variable name
Page 26
Python Programming-21EC643
• The in keyword
• A colon
• Starting on the next line, an indented block of code (called the for clause)
Flowchart:
. in
ud
lo
Example:
for i in digits:
print(i)
else:
vt
for i in range(5):
Page 27
Python Programming-21EC643
print(i)
in
Output:
12
13
.
14
15
ud
The range() function can also be called with three arguments. The first two
arguments will be the start and stop values, and the third will be the step argument.
The step is the amount that the variable is increased by after each iteration.
lo
for i in range(0, 10, 2):
print(i)
uc
Output:
2
vt
Page 28
Python Programming-21EC643
print(i)
Output:
in
3
.
0
Exercise:
ud
Write a Python program for the following:
Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left(
fills 1 in the case of a negative number) as a result. Similar effect as of dividing the
number with some power of two.
Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
Page 29
Python Programming-21EC643
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids right as
a result. Similar effect as of multiplying the number with some power of two.
Example 1:
a = 5 = 0000 0101 (Binary)
in
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)
.
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
ud
Precedence and associatively of operators:
Operator precedence determines the way in which operators are parsed with respect
to each other. Operators with higher precedence become the operands of operators
with lower precedence. Associativity determines the way in which operators of the
lo
same precedence are parsed.
uc
vt
Page 30
Python Programming-21EC643
Example:
In the expression: 10 + 20 * 30
. in
ud
Operator Associativity: If an expression contains two or more operators with the
same precedence then Operator Associativity is used to determine. It can either be Left
to Right or from Right to Left. Example: ‘*’ and ‘/’ have the same precedence and
their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as
“(100 / 10) * 10”.
lo
Operator Description Associativit
y
() Parentheses left-to-right
uc
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Relational less than/less than or equal to left-to-right
< <= Relational greater than/greater than or equal to left-to-right
> >= Bitwise shift left, Bitwise shift right
== != Relational is equal to/is not equal to left-to-right
vt
in
providing information about certain conversion functions.
There are two types of Type Conversion in Python:
Implicit Type Conversion
Explicit Type Conversion
.
Implicit Type Conversion
ud
In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
Example:
x = 10
print("x is of type:",type(x)) y = 10.6
lo
print("y is of type:",type(y)) z = x + y
print(z)
print("z is of type:",type(z))
Output:
x is of type: <class 'int'>
uc
Page 32
Python Programming-21EC643
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the
base in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
in
8. list() : This function is used to convert any data type to a list type.
9. dict() : This function is used to convert a tuple of order (key,value) into a
dictionary.
10. str() : Used to convert integer into a string.
.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.
Example:
s = "10010"
ud
12. chr(number): This function converts number to its
lo
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
e = float(s)
uc
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
vt
Page 33
Python Programming-21EC643
Sequence Type
Boolean
Set
Dictionary
. in
1. Numeric Data Type
ud
In Python, numeric data type represent the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers. These values are
defined as int, float and complex class in Python.
lo
Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fraction or decimal). In Python there is no limit to how long
an integer value can be.
uc
Float – This value is represented by float class. It is a real number with 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.
Page 34
Python Programming-21EC643
in
consist of various elements.
e. Dictionary
Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which unlike other Data Types that hold only single value as an
element, Dictionary holds key:value pair. Key-value is provided in the dictionary to
.
make it more optimized. Each key-value pair in a Dictionary is separated by a colon :,
Examples: ud
whereas each key is separated by a ‘comma’.
1. Write a program to read the marks of three subjects and find the average of
them.
lo
m1= int(input("Enter Marks of 1 Subject:"))
m2= int(input("Enter Marks of 2 Subject:"))
m3= int(input("Enter Marks of 3 Subject:"))
uc
average = (m1+m2+m3)/3
print("Average Marks = {}".format(average))
f = 9/5 * c + 32
Page 35
Python Programming-21EC643
customer. Units consumed by the user should be taken from the keyboard and
display the total amount to be pay by the customer. The charges are as follows:
Unit Charge/unit
upto 199 @1.20
200 and above but less than 400 @1.50
400 and above but less than 600 @1.80
600 and above @2.00
If the bill exceeds Rs. 400 then a surcharge of 15% will be charged. If the bill is
in
less than Rs. 400 then a minimum surcharge amount should be Rs. 100/-.
.
if units<=199:
bill=units*1.20
elif units<400:
bill=units*1.50
ud
lo
elif units<600:
bill = units*1.80
uc
elif units>=600:
bill = units*2.00
surcharge=0
vt
if bill>400:
surcharge=bill*0.15
if bill<400:
surcharge=100
bill=bill+surcharge
Write a program that uses a while loop to display all the even numbers between
100 and 130
if i%2==0:
print(i)
in
Write a program that uses a while loop to add up all the even numbers between
100 and 200
.
sum =0
if i%2==0:
sum=sum+i
ud
print("Sum of all even numbers between 100 and 200 is : ", sum)
lo
Write a program to find factorial of a number using for loop.
uc
fact=1
if n>0:
for i in range(1,n+1):
vt
fact=fact*I
Page 37
Python Programming-21EC643
a. 1 + ½ + 1/3 +. …. + 1/n
. in
ud
lo
uc
vt
Page 38
Python Programming-21EC643
. in
ud
lo
uc
vt
Page 39