22-10-2023
Introduction to Python Programming
Module-1
By
Dr. Banuprakash R
Assistant Professor,
Dept. of ETE
Introduction
The Python programming language has a
wide range of syntactical constructions,
standard library functions, and
interactive development environment
features.
[Link] R, ETE,BMSIT&M 2
1
22-10-2023
Entering Expressions into the Interactive Shell
• Run the interactive shell by launching IDLE, which is installed
with Python.
• On Windows, open the Start menu, select All Programs 4
Python 3.3, and then select IDLE (Python GUI).
• On OS X, select Applications 4 MacPython 3.3 4 IDLE.
• On Ubuntu, open a new Terminal window and enter idle3
• A window with the >>> prompt should appear; that’s the
interactive shell.
>>> 2 + 2
4
[Link] R, ETE,BMSIT&M 3
The IDLE window should now show some text like this:
• Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53)
[MSC v.1600 64 bit (AMD64)] on win32 Type "copyright",
"credits" or "license()" for more information.
>>> 2 + 2
4
>>>
• In Python, 2 + 2 is called an expression, which is the most basic
kind of programming instruction in the language.
• Expressions consist of values (such as 2) and operators (such as
+), and they can always evaluate (that is, reduce) down to a single
value.
[Link] R, ETE,BMSIT&M 4
2
22-10-2023
>>> 2
2
• A single value with no operators is also considered an expression,
though it evaluates only to itself.
• The order of operations (also called precedence) of Python math
operators is similar to that of mathematics
[Link] R, ETE,BMSIT&M 5
• You can use parentheses to override the usual precedence if you
need to.
• >>> 2 + 3 * 6
20
• >>> (2 + 3) * 6
30
• >>> 48565878 * 578453
28093077826734
• >>> 2 ** 8
256
• >>> 23 / 7
3.2857142857142856
• >>> 23 // 7
3
• >>> 23 % 7
2
• >>> 2 + 2
4
• >>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
[Link] R, ETE,BMSIT&M 6
3
22-10-2023
• (5 - 1) * ((7 + 1) / (3 - 1))
• 4 * ((7 + 1) / (3 - 1))
• 4 * ( 8 ) / (3 - 1))
• 4*(8)/(2)
• 4 * 4.0
• 16.0
Figure 1-1: Evaluating an expression reduces it to a single value.
• >>> 5 +
• File "<stdin>", line 1
• 5+
• ^
• SyntaxError: invalid syntax
• >>> 42 + 5 + * 2
• File "<stdin>", line 1
• 42 + 5 + * 2
• ^
• SyntaxError: invalid syntax
[Link] R, ETE,BMSIT&M 7
The Integer, Floating-Point, and String Data Types
• A data type is a category for values, and every value belongs to
exactly one data type
• Always surround your string in single quote (') characters (as in
'Hello' or 'Goodbye cruel world!') so Python knows where the
string begins and ends.
• You can even have a string with no characters in it, '', called a
blank string
>>> 'Hello world!
Syntax Error: EOL while scanning string literal
[Link] R, ETE,BMSIT&M 8
4
22-10-2023
String Concatenation and Replication:
• When + is used on two string values, it joins the strings as the
string concatenation operator
• >>> 'Alice' + 'Bob'
'AliceBob‘
>>> 'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly
• >>> 'Alice' * 5
'AliceAliceAliceAliceAlice‘
• The expression evaluates down to a single string value that
repeats the original a number of times equal to the integer value.
[Link] R, ETE,BMSIT&M 9
>>> 'Alice' * 'Bob'
TypeError: can't multiply sequence by non-int of type 'str'
>>> 'Alice' * 5.0
TypeError: can't multiply sequence by non-int of type 'float‘
Storing Values in Variables:
• A variable is like a box in the computer’s memory where you can
store a single value.
• Store values in variables with an assignment statement.
• An assignment statement consists of a variable name, an equal sign
(called the assignment operator), and the value to be stored.
• If you enter the assignment statement spam = 42, then a variable
named spam will have the integer value 42 stored in it.
[Link] R, ETE,BMSIT&M 10
5
22-10-2023
1. >>> spam = 40 #A variable is initialized (or created) the first time a value is stored
in it .
>>> spam
40
2. >>> eggs = 2 #expressions with other variables and values.
>>> spam + eggs
42
>>> spam + eggs + spam
82
3. >>> spam = spam + 2 # variable is assigned a new value w, the old value is forgotten
>>> spam # This is called overwriting the variable.
42
[Link] R, ETE,BMSIT&M 11
overwriting a string:
>>> spam = 'Hello'
>>> spam
'Hello'
>>> spam = 'Goodbye'
>>> spam
'Goodbye‘
Variable Names:
Anything as long as it obeys the following three rules can be a variable:
1. It can be only one word.
2. It can use only letters, numbers, and the underscore (_) character.
3. It can’t begin with a number.
[Link] R, ETE,BMSIT&M 12
6
22-10-2023
• Variable names are case-sensitive, meaning that spam, SPAM, Spam,
and sPaM are four different variables.
• It is a Python convention to start your variables with a lowercase
letter
[Link] R, ETE,BMSIT&M 13
1 # This program says hello and asks for my name.
2 print('Hello world!')
print('What is your name?') # ask for their name
3 myName = input()
4 print('It is good to meet you, ' + myName)
5 print('The length of your name is:')
print(len(myName))
6 print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
[Link] R, ETE,BMSIT&M 14
7
22-10-2023
>>>
Hello world!
What is your name?
Al
It is good to meet you, Al
The length of your name is:
2
What is your age?
4
You will be 5 in a year.
>>>
[Link] R, ETE,BMSIT&M 15
• The line print('Hello world!') means “Print out the text in the string
'Hello world!'.” When Python executes this line, you say that Python
is calling the print() function and the string value is being passed to
the function.
• A value that is passed to a function call is an argument
The input() Function:
• The input() function waits for the user to type some text on the
keyboard and press enter.
Printing the User’s Name:
print('It is good to meet you, ' + myName)
• The single string value is then passed to print(), which prints it on the
screen.
The len() Function:
• Pass the len() function a string value and the function evaluates to
the integer value of the number of characters in that string.
[Link] R, ETE,BMSIT&M 16
8
22-10-2023
>>> len('hello')
5
>>> len('My very energetic monster just scarfed nachos.')
46
>>> len('')
0
[Link] R, ETE,BMSIT&M 17
The str(), int(), and float() Functions:
>>> str(29)
'29'
>>> print('I am ' + str(29) + ' years old.')
I am 29 years old.
• The str(), int(), and float() functions will evaluate to the string, integer,
and floating-point forms of the value you pass, respectively
[Link] R, ETE,BMSIT&M 18
9
22-10-2023
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
>>> int('42')
42
>>> int('-99')
-99
>>> int(1.25)
1
>>> int(1.99)
1
>>> float('3.14')
3.14
>>> float(10)
10.0
[Link] R, ETE,BMSIT&M 19
>>> spam = input()
101
>>> spam
'101‘
• The value stored inside spam isn’t the integer 101 but the string '101'.
>>> spam = int(spam)
>>> spam
101
>>> spam * 10 / 5
202.0
>>> int('99.99')
ValueError: invalid literal for int() with base 10: '99.99‘
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve‘
>>> int(7.7)
7
>>> int(7.7) + 1
8
[Link] R, ETE,BMSIT&M 20
10
22-10-2023
FLOW CONTROL
• Flow control statements can decide which Python instructions to
execute under which conditions.
[Link] R, ETE,BMSIT&M 21
Boolean Values:
• The Boolean data type has only two values: True and False.
• They always start with a capital T or F, with the rest of the word in
lowercase.
>>> spam = True
>>> spam
True
>>> true
NameError: name 'true' is not defined
>>> True = 2 + 2
SyntaxError: assignment to keyword
[Link] R, ETE,BMSIT&M 22
11
22-10-2023
Comparison Operators:
• Comparison operators compare two values and evaluate down
to a single Boolean value.
[Link] R, ETE,BMSIT&M 23
[Link] R, ETE,BMSIT&M 24
12
22-10-2023
Boolean Operators:
• The three Boolean operators (and, or, and not) are used to
compare Boolean values.
Binary Boolean Operators:
• The and and or operators always take two Boolean values (or
expressions), so they’re considered binary operators.
The and operator :
• evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.
>>> True and True
True
>>> True and False
False
[Link] R, ETE,BMSIT&M 25
The or operator:
• It 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
>>> False or False
False
The not Operator:
• The not operator operates on only one Boolean value. The not operator
simply evaluates to the opposite Boolean value.
>>> not True
False
>>> not not not not True
True
[Link] R, ETE,BMSIT&M 26
13
22-10-2023
Mixing Boolean and Comparison Operators:
>>> (4 < 5) and (5 < 6)
True
>>> (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
• After any math and comparison operators evaluate, Python
evaluates the not operators first, then the and operators, and then
the or operators.
[Link] R, ETE,BMSIT&M 27
Elements of Flow Control:
• Flow control statements often start with a part called the condition,
and all are followed by a block of code called the clause.
• Condition is just a more specific name in the context of flow control
statements.
• Conditions always evaluate down to a Boolean value, True or
False.
• A flow control statement decides what to do based on whether its
condition is True or False, and almost every flow control
statement uses a condition.
Blocks of Code:
• Lines of Python code can be grouped together in blocks. You can tell
when a block begins and ends from the indentation of the lines of
code.
There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing
block’s indentation
[Link] R, ETE,BMSIT&M 28
14
22-10-2023
if name == 'Mary':
print('Hello Mary')
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
[Link] R, ETE,BMSIT&M 29
Flow Control Statements:
• The most common type of flow control statement is the if
statement.
• An if statement’s clause (that is, the block following the if
statement) will execute if the statement’s condition is True.
• The clause is skipped if the condition is False
In Python, an if statement consists of the following:
• The if keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the if
clause)
[Link] R, ETE,BMSIT&M 30
15
22-10-2023
[Link] R, ETE,BMSIT&M 31
else Statements:
• The else clause is executed only when the if statement’s condition is
False.
• “If this condition is true, execute this code. Or else, execute that
code.”
• An else statement doesn’t have a condition
An else statement always consists of the following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else
clause)
[Link] R, ETE,BMSIT&M 32
16
22-10-2023
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
[Link] R, ETE,BMSIT&M 33
elif Statements:
• The elif statement is an “else if” statement that always follows
an if or another elif statement.
An elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or
False)
• A colon
• Starting on the next line, an indented block of code (called the
elif clause)
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
[Link] R, ETE,BMSIT&M 34
17
22-10-2023
[Link] R, ETE,BMSIT&M 35
Lab program 1b
print("Enter the name of the Person")
name=input( )
print("Enter the Year of birth of the person")
age=input( )
senior=2023-int(age)
print("HI",name)
if (int(senior) >= 55):
print("you are senior citizen--Age: ",senior)
else:
print("you are not senior citizen---Age: ",senior)
[Link] R, ETE,BMSIT&M 36
18
22-10-2023
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age > 100:
print('You are not Alice, grannie.')
[Link] R, ETE,BMSIT&M 37
[Link] R, ETE,BMSIT&M 38
19
22-10-2023
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
[Link] R, ETE,BMSIT&M 39
[Link] R, ETE,BMSIT&M 40
20
22-10-2023
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
[Link] R, ETE,BMSIT&M 41
[Link] R, ETE,BMSIT&M 42
21
22-10-2023
while Loop Statements:
• You can make a block of code execute over and over again with a
while statement.
• The code in a while clause will be executed as long as the while
statement’s condition is True.
A while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the
while clause)
• At the end of a while clause, the program execution jumps back to
the start of the while statement.
• The while clause is often called the while loop or just the loop.
[Link] R, ETE,BMSIT&M 43
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
spam = 0
if spam < 5:
print('Hello, world.')
spam = spam + 1
[Link] R, ETE,BMSIT&M 44
22
22-10-2023
An Annoying while Loop:
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
[Link] R, ETE,BMSIT&M 45
break Statements:
• There is a shortcut to getting the program execution to break out of
a while loop’s clause early.
• If the execution reaches a break statement, it immediately exits the
while loop’s clause
EX:
while True: # infinite loop
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
[Link] R, ETE,BMSIT&M 46
23
22-10-2023
[Link] R, ETE,BMSIT&M 47
for Loops and the range() Function:
In code, a for statement looks something like for i in range(5): and
always includes the following
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for
clause)
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
[Link] R, ETE,BMSIT&M 48
24
22-10-2023
• The code in the for loop’s clause is run five times.
• The first time it is run, the variable i is set to 0. The print() call in the
clause will print Jimmy Five Times (0).
• After Python finishes an iteration through all the code inside the for
loop’s clause, the execution goes back to the top of the loop, and the
for statement increments i by one.
• This is why range(5) results in five iterations through the clause, with i
being set to 0, then 1, then 2, then
• 3, and then 4.
• The variable i will go up to, but will not include, the integer passed to
range().
[Link] R, ETE,BMSIT&M 49
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
[Link] R, ETE,BMSIT&M 50
25
22-10-2023
total = 0
for num in range(101):
total = total + num
print(total)
• The result should be 5,050
print('My name is')
i=0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i=i+1
[Link] R, ETE,BMSIT&M 51
The Starting, Stopping, and Stepping Arguments to range():
for i in range(12, 16):
print(i)
• The first argument will be where the for loop’s variable starts, and the
second argument will be up to, but not including, the number to stop
at.
12
13
14
15
for i in range(0, 10, 2):
print(i)
So calling range(0, 10, 2) will count from zero to eight by intervals of two
[Link] R, ETE,BMSIT&M 52
26
22-10-2023
0
2
4
6
8
for i in range(5, -1, -1):
print(i)
5
4
3
2
1
0
[Link] R, ETE,BMSIT&M 53
Importing Modules
• All Python programs can call a basic set of functions called built-in
functions, including the print(), input(), and len()
• Each module is a Python program that contains a related group of
functions that can be embedded in your programs.
In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by
commas
• Random module, which will give us access to the [Link]()
function.
import random
for i in range(5):
print([Link](1, 10))
[Link] R, ETE,BMSIT&M 54
27
22-10-2023
4
1
8
4
1
import random, sys, os, math
• import statement that imports four different modules:
[Link] R, ETE,BMSIT&M 55
Ending a Program Early with [Link]():
• We can cause the program to terminate, or exit, by calling the [Link]()
function.
• Since this function is in the sys module, you have to import sys before
your program can use it.
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
[Link]()
print('You typed ' + response + '.')
[Link] R, ETE,BMSIT&M 56
28
22-10-2023
Functions:
• A function is like a mini-program within a program.
def hello():
print('Howdy!')
print('Howdy!!!')
print('Hello there.')
hello()
hello()
hello()
• Since this program calls hello() three times, the code in the hello()
function is executed three times
[Link] R, ETE,BMSIT&M 57
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
Howdy!
Howdy!!!
Hello there.
[Link] R, ETE,BMSIT&M 58
29
22-10-2023
def Statements with Parameters:
• When you call the print() or len() function, you pass in values, called
arguments in this context, by typing them between the parentheses.
def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')
Output
Hello Alice
Hello Bob
• The definition of the hello() function in this program has a parameter
called name .
• A parameter is a variable that an argument is stored in when a
function is called.
• The first time the hello() function is called, it’s with the argument
'Alice' .
• The program execution enters the function, and the variable name is
automatically set to 'Alice', which is what gets printed by the print()
statement .
[Link] R, ETE,BMSIT&M 59
Return Values and return Statements:
• In general, the value that a function call evaluates to is called the
return value of the function.
A return statement consists of the following:
• The return keyword
• The value or expression that the function should return
[Link] R, ETE,BMSIT&M 60
30
22-10-2023
[Link] R, ETE,BMSIT&M 61
31