Programming in Python Module 1
MODULE – I
Introduction to Python
Introduction to Python programming:
What Is Python?
Python refers to the Python programming language (with syntax rules for writing what is
considered valid Python code) and the Python interpreter software that reads source code
(written in the Python language) and performs its instructions. The Python interpreter is free
to download from [Link] and there are versions for Linux, OS X, and Windows.
It was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation
The most recent major version of Python is Python 3. However, Python 2, although not
being updated with anything other than security updates, is still quite popular.
Python is Interpreted −. You do not need to compile your program before executing
it. This is similar to PERL and PHP. When you write Python programs, it converts
source code written by the developer into intermediate language which is again
translated into the native language / machine language that is executed.
Python is Interactive − Python offers a comfortable command line interface with
the Python Shell, which is also known as the "Python Interactive Shell”.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Python is Compiled or Interpreted?
“compile” means to convert a program in a high-level language into a binary executable
full of machine code (CPU instructions). When you compile a C program, this is what
happens.
SNPSU Department of CSE Page 1
Programming in Python Module 1
In the simple definition of “interpreted”, executing a program means reading the source
code a line at a time, and doing what it says
Python is interpreted !! Why ?
When you write Python programs, it converts source code written by the developer
into intermediate language, which is again translated into the native language / machine
language that is executed.
The python code you write is compiled into python bytecode, which creates file with
extension .pyc . The bytecode compilation happened internally and almost completely
hidden from developer. Compilation is simply a translation step, and byte code is a lower-
level, and platform-independent, representation of your source code
The .pyc file , created in compilation step, is then executed by appropriate virtual
machines. The Virtual Machine just a big loop that iterates through your byte
code instructions, one by one, to carry out their operations. The Virtual Machine is the
runtime engine of Python and it is always present as part of the Python system, and is the
component that truly runs the Python scripts.
Beginning with Python programming:
1) Finding an Interpreter: Before we start Python programming, we need to have an
interpreter to interpret and run our programs. There are certain online interpreters like
[Link] [Link] or [Link] that can be
used to start Python without installing an interpreter. Windows: There are many
interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from
[Link]
2) Writing first program:
# Script Begins Statement1
Statement2
Statement3
# Script Ends
Python Interactive Shell:
The interactive shell is also interactive in the way that it stands between the commands or
actions and their execution. In other words, the shell waits for commands from the user,
which it executes and returns the result of the execution. Afterwards, the shell waits for the
next input.
Python offers a comfortable command line interface with the Python Shell, which is also
known as the "Python Interactive Shell". It looks like the term "Interactive Shell" is a
tautology, because "shell" is interactive on its own.
SNPSU Department of CSE Page 2
Programming in Python Module 1
Using Python interactive shell:
With the Python interactive interpreter, it is easy to check Python commands. The Python
interpreter can be invoked by typing the command "python" without any parameter followed
by the "return" key at the shell prompt:
Understanding Hello World Program in Python:
# This is a comment. It will not be executed.
print("Hello, World!")
Output
Hello World!
How does this work:
print() is a built-in Python function that instructs the computer to display text on the screen.
"Hello, World!" is a string, which is a sequence of text. In Python, strings are enclosed in
quotes (either single ' or double ").
The integer, floating-Point, and String data types:
Note that expressions are just values combined with operators, and they always evaluate
down to a single value. A data type is a category for values, and every value belongs to
exactly one data type. The most common data types in Python are listed in table below The
values -2 and 30, for example, are said to be integer values. 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). Note that even though the value 42 is an integer, the
value 42.0 would be a floating-point [Link] programs can also have text values
called strings, or strs (pronounced “stirs”).
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. If you ever see the error message Syntax Error:
EOL while scanning string literal, you probably forgot the final single quote character at the
end of the string, such as in this example
: >>> 'Hello world!
SNPSU Department of CSE Page 3
Programming in Python Module 1
Syntax Error: EOL while scanning string literal.
Storing Values in Variables:
A variable is like a box in the computer’s memory where you can store a single value. If you
want to use the result of an evaluated expression later in your program, you can save it inside
a variable.
Assignment Statements
You’ll 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.
Think of a variable as a labelled box that a value is placed in, as in figure below.
For example, enter the following into the interactive shell:
A variable is initialized (or created) the first time a value is stored in it u. After that, you can
use it in expressions with other variables and values v. When a variable is assigned a new
value w, the old value is forgotten, which is why spam evaluated to 42 instead of 40 at the
end of the example. This is called overwriting the variable. Enter the following code into the
interactive shell to try overwriting a string:
SNPSU Department of CSE Page 4
Programming in Python Module 1
Just like the box in Figure above the spam variable in this example stores 'Hello' until you
replace it with 'Goodbye'.
Variable Names
Table below has examples of legal variable names. You can name a variable anything as long
as it obeys the following three rules:
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.
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.
Comments
The following line is called a comment.
# this line is comment line
Python ignores comments, and you can use them to write notes or remind yourself what the
code is trying to do. Any text for the rest of the line following a hash mark (#) is part of a
comment. Sometimes, programmers will put a # in front of a line of code to temporarily
remove it while testing a program. This is called commenting out code, and it can be useful
when you’re trying to figure out why a program doesn’t work. You can remove the # later
when you are ready to put the line back in. Python also ignores the blank line after the
comment. You can add as many blank lines to your program as you want. This can make
your code easier to read, like paragraphs in a book.
SNPSU Department of CSE Page 5
Programming in Python Module 1
Input and output functions:
The print() Function:
The print() function displays the string value inside the parentheses on the screen.
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.
Notice that the quotes are not printed to the screen. They just mark where the string begins
and ends; they are not part of the string value. note You can also use this function to put a
blank line on the screen. They just mark where the string begins and ends; they are not part of
the string value.
You can also use this function to put a blank line on the screen; just call print() with nothing
in between the parentheses. When writing a function name, the opening and closing
parentheses at the end identify it as the name of a function. This is why in this book you’ll see
print() rather than print.
The input() Function
The input() function waits for the user to type some text on the keyboard and press enter.
This function call evaluates to a string equal to the user’s text, and the previous line of code
assigns the myName variable to this string value. You can think of the input() function call as
an expression that evalu ates to whatever string the user typed in. If the user entered 'Al', then
the expression would evaluate to myName = 'Al'.
The len() Function
You can pass the len() function a string value (or a variable containing a string), and the
function evaluates to the integer value of the number of characters in that string.
SNPSU Department of CSE Page 6
Programming in Python Module 1
Just like those examples, len(myName) evaluates to an integer. It is then passed to print() to
be displayed on the screen. Notice that print() allows you to pass it either integer values or
string values.
Type Conversion:
The str(), int(), and float() Functions:
If you want to concatenate an integer such as 29 with a string to pass to print(), you’ll need to
get the value '29', which is the string form of 29. The str() function can be passed an integer
value and will evaluate to a string value version of it, as follows:
Because str(29) evaluates to '29', the expression 'I am ' + str(29) + ' years old.' evaluates to 'I
am ' + '29' + ' years old.', which in turn evaluates to 'I am 29 years old.'. This is the value that
is passed to the print() function. The str(), int(), and float() functions will evaluate to the
string, integer, and floating-point forms of the value you pass, respectively. Try converting
some values in the interactive shell with these functions like below,
The previous examples call the str(), int(), and float() functions and pass them values of the
other data types to obtain a string, integer, or floating-point form of those values. The str()
function is handy when you have an integer or float that you want to concatenate to a string.
The int() function is also helpful if you have a number as a string value that you want to use
in some mathematics. For example, the input() function always returns a string, even if the
user enters a number. Enter spam = input() into the interactive shell and enter 101 when it
waits for your text.
SNPSU Department of CSE Page 7
Programming in Python Module 1
The value stored inside spam isn’t the integer 101 but the string '101'. If you want to do math
using the value in spam, use the int() function to get the integer form of spam and then store
this as the new value in spam.
The int() function is also useful if you need to round a floating-point number down.
In your program, you used the int() and str() functions in the last three lines to get a value of
the appropriate data type for the code.
The myAge variable contains the value returned from input(). Because the input() function
always returns a string (even if the user typed in a num ber), you can use the int(myAge) code
to return an integer value of the string in myAge. This integer value is then added to 1 in the
expression int(myAge) + 1. The result of this addition is passed to the str() function:
str(int(myAge) + 1). The string value returned is then concatenated with the strings 'You will
be ' and ' in a year.' to evaluate to one large string value. This large string is finally passed to
print() to be displayed on the screen. Let’s say the user enters the string '4' for myAge. The
string '4' is con verted to an integer, so you can add one to it. The result is 5. The str() func
tion converts the result back to a string, so you can concatenate it with the second string, 'in a
year.', to create the final message.
SNPSU Department of CSE Page 8
Programming in Python Module 1
round():
round() is a built-in Python function used to round numbers to a specified number of decimal
places.
If only the number is provided, it rounds to the nearest integer.
If the second argument (ndigits) is given, it rounds the number to that many decimal
places.
It follows Python’s rounding rule (ties are rounded to the nearest even number).
It returns either an int or a float depending on the input.
Example: This example rounds a decimal number to the nearest integer.
n = 45.7
print(round(n))
Output:46
Syntax
round(number, ndigits)
Parameters:
number: The numeric value to round.
ndigits (optional): Number of decimal places to round to.
Return: Returns a rounded int or float.
round() Without ndigits
When the second parameter (ndigits) is not provided, round() automatically rounds the
number to the nearest integer. If the number is already an integer, it remains unchanged.
For decimal numbers, Python rounds to the closest integer using its standard rounding rule.
print(round(15))
print(round(51.6))
print(round(51.5))
print(round(51.4))
weddsszOutput:
15
52
52
51
Explanation:
round(15) returns 15 because it is already an integer.
round(51.6) returns 52 since .6 is greater than .5.
round(51.5) returns 52 because it rounds to the nearest even integer.
round(51.4) returns 51 since .4 is less than .5.
SNPSU Department of CSE Page 9
Programming in Python Module 1
round() With ndigits
When the second parameter (ndigits) is provided, round() rounds the number to the specified
number of decimal places.
It checks the digit after the required decimal place and rounds accordingly using Python’s
standard rounding rule.
print(round(2.665, 2))
print(round(2.676, 2))
print(round(2.673, 2))
output:
2.67
2.68
2.67
Explanation:
round(2.665, 2) rounds to two decimal places and returns 2.67.
round(2.676, 2) increases the second decimal because the next digit is greater than 5.
round(2.673, 2) keeps the second decimal unchanged because the next digit is less than 5.
round() with Negative Numbers
round() works the same way for negative numbers as it does for positive numbers. It rounds
to the nearest integer (or specified decimal place) based on closeness. When the value ends in
.5, Python applies the “round to nearest even” rule.
print(round(-3.2))
print(round(-4.7))
print(round(-2.5))
print(round(-2.675, 2))
print(round(-1234, -2))
output:
-3
-5
-2
-2.67
-1200
Abs() in python:
The Python abs() function return the absolute value. The absolute value of any number is
always positive it removes the negative sign of a number in Python.
Example: input= -12
Output = 12
SNPSU Department of CSE Page 10
Programming in Python Module 1
The abs() function in Python has the following syntax:
Syntax: abs(number)
number: Integer, floating-point number, complex number.
Return: Returns the absolute value.
Python abs() Function Example
Let us see a few examples of the abs() function in Python.
abs() Function with an Integer Argument
In this example, we will pass an Integer value as an argument to the abs() function in Python
and print its value to see how it works.
# An integer
var = -94
print('Absolute value of integer is:', abs(var))
output:
Absolute value of integer is: 94
abs() Function with a Floating-Point Number
In this example, we will pass a float data into the abs() function and it will return an absolute
value.
# floating point number
float_number = -54.26
print('Absolute value of float is:',
abs(float_number))
Absolute value of integer is:54.26
abs() Function with a Complex Number
In this example, we will pass Python complex number into the abs() function and it will
return an absolute value
# A complex number
complex_number = (3 - 4j)
print('Absolute value or Magnitude of complex is:', abs(complex_number))
Absolute value or Magnitude of complex is: 5.0
Python Operators:
Operators are used to perform operations on variables and values. Python divides the
operators in the following groups:
Arithmetic operators Logical operators Relational operators Assignment operators
Bitwise operators and order of precedence.
SNPSU Department of CSE Page 11
Programming in Python Module 1
1. Arithmetic Operators:
Arithmetic operators in Python are used to perform basic mathematical operations like
addition, subtraction, multiplication, etc.
Here are the main arithmetic operators with examples:
Addition (+)
Adds two numbers
a = 10
b=5
print(a + b) # Output: 15
Subtraction (-)
Subtracts second number from first
print(10 - 5) # Output: 5
Multiplication (*)
Multiplies two numbers
print(10 * 5) # Output: 50
Division (/)
Returns quotient (float result)
print(10 / 5) # Output: 2.0
Floor Division (//)
print(10 // 3) # Output: 3
Modulus (%)
Returns remainder
print(10 % 3) # Output: 1
Exponentiation (**)
Raises power
print(2 ** 3) # Output: 8
SNPSU Department of CSE Page 12
Programming in Python Module 1
Logical operators:
Relational Operators:
Assignment Operators:
SNPSU Department of CSE Page 13
Programming in Python Module 1
Bitwise Operator:
Precedence operator:
Operator precedence affects how an expression is evaluated.
For example,
x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first
multiplies 3*2 and then adds into 7.
Example :
>>> 3+4*2 11
Multiplication gets evaluated before the addition operation
>>> (10+10)*2 40
Parentheses () overriding the precedence of the arithmetic operators.
Control Structures:
Flow control statements often start with a part called the condition, and all are followed by a
block of code called the clause.
Conditions:
The Boolean expressions you’ve seen so far could all be considered con ditions, which are
the same thing as expressions; 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.
SNPSU Department of CSE Page 14
Programming in Python Module 1
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.
Conditional (if):
The if statement contains a logical expression using which data is compared and a decision is
made based on the result of the comparison. Syntax: if expression: statement(s) If the boolean
expression evaluates to TRUE, then the block of statement(s) inside the if statement is
executed. If boolean expression evaluates to FALSE, then the first set of code after the end of
the if statement(s) is executed.
if Statements:
if 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 plain English,
an if statement could be read as, “If this condition is true, execute the code in the clause.” 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)
Flowchart of if Statement
SNPSU Department of CSE Page 15
Programming in Python Module 1
Example:
a=3
if a > 2:
print(a, "is greater")
else Statements:
An if clause can optionally be followed by an else statement. The else clause is executed only
when the if statement’s condition is False. In plain English, an else statement could be read
as, “If this condition is true, execute this code. Or else, execute that code.” An else statement
doesn’t have a condi tion, and in code, an else statement always consists of the following:
• The else keyword
• A colon
• Starting on the next line
If –else control Statement
Flow chart if-else statement
Example of if - else:
a=int(input('enter the number'))
if a>5:
print("a is greater")
else:
print("a is smaller than the input given")
SNPSU Department of CSE Page 16
Programming in Python Module 1
output:
enter the number
2
a is smaller than the input given
a=10
b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")
output: B is Greater than A
elif Statements:
While only one of the if or else clauses will execute, you may have a case where you want
one of many possible clauses to execute. The elif statement is an “else if” statement that
always follows an if or another elif statement. It provides another condition that is checked
only if any of the previous conditions were False. In code, 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)
The order of the elif statements does matter, however. Let’s rearrange them to introduce a
bug. Remember that the rest of the elif clauses are automatically skipped once a True
condition has been found. Optionally, you can have an else statement after the last elif
statement. In that case, it is guaranteed that at least one (and only one) of the clauses will be
executed. If the conditions in every if and elif statement are False, then the else clause is
executed.
Syntax of if – elif - else :
If test expression:
Body of if stmts
elif test expression:
Body of elifstmts
else:
Body of else stmt
SNPSU Department of CSE Page 17
Programming in Python Module 1
Example of if - elif – else:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")
output:
enter the number5
enter the number2
enter the number9
a is greater >>>
enter the number2
enter the number5
enter the number9
c is greater
SNPSU Department of CSE Page 18
Programming in Python Module 1
Looping Statements:
A loop statement allows us to execute a statement or group of statements multiple times as
long as the condition is true. Repeated execution of a set of statements with the help of loops
is called iteration. Loops statements are used when we need to run same code again and
again, each time with a different value.
Statements: In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While Loop:
These Loops are either infinite or conditional. Python while loop keeps reiterating a block of
code defined inside it until the desired condition is met.
The while loop contains a boolean expression and the code inside the loop is repeatedly
executed as long as the boolean expression is true.
The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
Flowchart for While Loop:
SNPSU Department of CSE Page 19
Programming in Python Module 1
Example Programs:
1. i=1
while i<=6:
print("Hi John")
i=i+1
output:
Hi John
Hi John
Hi John
H John
Hi John
Hi John
For Loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects.
Flowchart for For Loop:
SNPSU Department of CSE Page 20
Programming in Python Module 1
Sample Program:
numbers = [1, 2, 4, 6, 11, 20]
seq=0
for val in numbers:
seq=val*val
print(seq)
Output:
1
4
16
36
121
400
Nested For loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
statements
# Example 1 of Nested For Loops (
Pattern Programs)
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output:
1
22
333
4444
5 5 5 5 5 ---------------------
Break and continue:
In Python, break and continue statements can alter the flow of a normal [Link] we
wish to terminate the current iteration or even the whole loop without checking test
[Link] break and continue statements are used in these cases.
Break: The break statement terminates the loop containing it and control of the program
flows to the statement immediately after the body of the [Link] break statement is inside a
nested loop (loop inside another loop), break will terminate the innermost loop.
SNPSU Department of CSE Page 21
Programming in Python Module 1
Flowchart:
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
Example:
for val in "THANKS":
if val == " ":
break
print(val)
print("The end")
Output:
T
H
A
N
K
S
The end
SNPSU Department of CSE Page 22
Programming in Python Module 1
Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Flowchart:
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
while test expression
# code inside while loop
If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop
SNPSU Department of CSE Page 23
Programming in Python Module 1
Example: # Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")
output:
s
t
r
n
g
The end
Pass:
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not
ignored. pass is just a placeholder for functionality to be added later.
Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Using Else with Loops in Python
In most of the programming languages (C/C++, Java, etc), the use of else statement has
been restricted with the if conditional statements. But Python also allows us to use the else
condition with for loops.
The else block just after for/while is executed only when the loop is NOT terminated by a
break statement.
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break")
Output:
1
2
SNPSU Department of CSE Page 24
Programming in Python Module 1
3
No Break
SNPSU Department of CSE Page 25