Python Notes 1
Python Notes 1
Python Notes 1
INTRODUCTION TO PYTHON
PROGRAMMING- MODULE1
Contents
No Syllabus Page
1.1 Python Basics: 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,
2- 31
1.2 Flow control: Boolean Values, Comparison Operators, Boolean Operators, 31-67
Mixing Boolean and Comparison Operators, Elements of Flow Control,
Program Execution, Flow Control Statements, Importing Modules, Ending a
Program Early with [Link](),
1
1.3 Functions: def Statements with Parameters, Return Values and return 68-97
Statements,The None Value, Keyword Arguments and print(), Local and
Global Scope, The global Statement, Exception Handling, A Short Program:
Guess the Number
2.1 Lists: The List Data Type, Working with Lists, Augmented Assignment
Operators, Methods, Example Program: Magic 8 Ball with a List, List-like
Types: Strings and Tuples, References,
2
2.2 Dictionaries and Structuring Data: The Dictionary Data Type, Pretty
Printing, Using Data Structures to Model Real-World Things,
3.1 Manipulating Strings: Working with Strings, Useful String Methods,
Project: Password Locker, Project: Adding Bullets to Wiki Markup
3.2 Reading and Writing Files: Files and File Paths, The [Link] Module, The
File Reading/Writing Process, Saving Variables with the shelve Module,Saving
3 Variables with the [Link]() Function, Project: Generating Random Quiz
Files, Project: Multiclipboard
4.1 Organizing Files: The shutil Module, Walking a Directory Tree,
Compressing Files with the zipfile Module, Project: Renaming Files with
American-Style Dates to European-Style Dates,Project: Backing Up a Folder
4
into a ZIP File,
4.2 Debugging: Raising Exceptions, Getting the Traceback as a String,
Assertions, Logging, IDLE‟s Debugger.
5.1 Classes and objects: Programmer-defined types, Attributes, Rectangles,
Instances as return values, Objects are mutable, Copying,
5.2 Classes and functions: Time, Pure functions, Modifiers, Prototyping versus
planning,
5 5.3 Classes and methods: Object-oriented features, Printing objects, Another
example, A more complicated example, Theinit method, The __str__ method,
Operator overloading, Type-based dispatch, Polymorphism, Interface and
implementation,
1|Page
h琀琀ps://[Link]/
Python Programming is a fun, crea琀椀ve and rewarding ac琀椀vity. Python is one of the
most widely used programming language across the world for developing so昀琀ware
applica琀椀ons. It is named as one of top picked programming languages of most of
the universi琀椀es and industries. Python developer is one of the “10 Most in Demand
Tech Jobs of 2019”[ Source : h琀琀ps://[Link]/ ] As of February 23,
2|Page
h琀琀ps://[Link]/
2019, the average salary for a Python developer is $123,201 per year in the
United States, making it one of the most popular and lucrative careers today
[source: [Link]
Python can be used on the following:
1. Multiple Programming Paradigms
2. Web Testing
3. Data Extraction
4. Artificial Intelligence
5. Machine Learning
6. Data Science
7. Web Application and Internet Development
8. Cybersecurity
Entering expressions into the Python interactive shell allows you to evaluate and
execute code in real-time. You can use the shell as a convenient way to test and
experiment with Python code. Here are some examples of entering expressions into
the Python interactive shell:
Arithmetic Operations:
You can perform basic arithmetic operations, such as addition, subtraction,
multiplication, and division, directly in the shell. For example:
>>> 2 + 3
5
>>> 4 * 5
20
>>> 10 / 3
3.3333333333333335
3|Page
h琀琀ps://[Link]/
Variable Assignment:
You can assign values to variables and use those variables in expressions. For
example:
>>> x = 5
>>> y = 2
>>> x + y
7
>>> x * y
10
Function Calls:
You can call built-in functions or user-defined functions within the shell. For
example:
>>> abs(-10)
10
>>> len("Hello, World!")
13
>>> def add(a, b):
... return a + b
...
>>> add(3, 4)
7
Boolean Expressions:
You can use boolean operators like and, or, and not to evaluate logical expressions.
For example:
>>> True and False
False
>>> True or False
True
>>> not True
False
Conditional Statements:
You can use conditional statements like if, elif, and else to perform different actions
based on conditions. For example:
>>> x = 10
4|Page
h琀琀ps://[Link]/
>>> if x > 0:
... print("Positive")
... elif x < 0:
... print("Negative")
... else:
... print("Zero")
...
Positive
Examples :
x = 10 # integer
y = 3.14 # 昀氀oa琀椀ng-point number
z = 2 + 3j # complex number
name = "John" # string
message = 'Hello, World!' # string
is_true = True # Boolean Value
is_false = False
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
coordinates = (10, 20)
person = ("John", 30, "USA")
student = {"name": "John", "age": 20, "grade": "A"}
5|Page
h琀琀ps://[Link]/
type() func琀椀on :
In Python, the type() func琀椀on is used to determine the type of a given object or
value. It returns the data type of the object as a result. The type() func琀椀on is
par琀椀cularly useful when you need to programma琀椀cally determine the type of a
variable or check if a value belongs to a speci昀椀c data type. Here's an example:
Example: 1,2 and “Hello, World!”. Types are the data types to which the Values
belong.
type(arg) func琀椀on returns the data type of the argument as illustrated below :
x=5
y = 3.14
name = "John"
is_true = True
fruits = ["apple", "banana", "orange"]
student = {"name": "John", "age": 20}
6|Page
h琀琀ps://[Link]/
Data types
In Python, data types represent the classi昀椀ca琀椀on or categoriza琀椀on of values. Each
data type de昀椀nes the opera琀椀ons that can be performed on the values, the storage
format, and the behavior of the values. Python supports several built-in data types.
Here are the commonly used data types supported in Python, along with examples:
str: Strings represent sequences of characters enclosed in single quotes (' ') or
double quotes (" ").
Example: name = "John"
list: Lists are ordered collec琀椀ons of items enclosed in square brackets ([]). They can
contain values of any type and are mutable.
Example: fruits = ["apple", "banana", "orange"]
tuple: Tuples are similar to lists but are enclosed in parentheses (()). They are
immutable, meaning their values cannot be changed once de昀椀ned.
Example: coordinates = (10, 20)
7|Page
h琀琀ps://[Link]/
None Type:
None: The None type represents the absence of a value or a null value. It is o昀琀en
used to indicate the absence of a meaningful result.
Example: result = None
String Concatena琀椀on:
8|Page
h琀琀ps://[Link]/
In this example, the + operator is used to concatenate the strings gree琀椀ng, a space
(" "), and name, resul琀椀ng in the string "Hello John". The concatenated string is then
stored in the message variable and printed.
String Replica琀椀on:
String replica琀椀on allows you to repeat a string mul琀椀ple 琀椀mes. In Python, you can
replicate a string by using the * operator. Here's an example:
fruit = "apple"
repeated_fruit = fruit * 3
print(repeated_fruit) # Output: appleappleapple
In this example, the * operator is used to replicate the string "apple" three 琀椀mes,
resul琀椀ng in the string "appleappleapple". The replicated string is stored in the
repeated fruit variable and printed.
word = "Hi"
punctua琀椀on = "!"
gree琀椀ng = word * 3 + punctua琀椀on
print(gree琀椀ng) # Output: HiHiHi!
9|Page
h琀琀ps://[Link]/
Variables:
A variable is a name that refers to a value. In Python, a variable is a named storage
loca琀椀on that holds a value. It allows you to assign values to iden琀椀昀椀ers and refer to
those values by using the iden琀椀昀椀ers later in the program. An assignment statement
creates new variables as illustrated in the example below:
x = 10
In this example, the value 10 is assigned to the variable x. Now, x holds the value
10, and you can refer to it later in the program.
Examples:
To know the type of the variable one can use type () func琀椀on. Ex: type(p)
To display the value of a variable, you can use a print statement:
Ex: print (Si) ; print(pi)
10 | P a g e
h琀琀ps://[Link]/
Note:
Variable names are case-sensi琀椀ve, meaning that velocity, VELOCITY, Velocity, and
velocity are four di昀昀erent variables. It is a Python conven琀椀on to start your variables
with a lowercase le琀琀er.
Example 1:
x = 40
In this example, the value 10 is assigned to the variable x. The variable x now holds
the value 10, and you can use x to refer to that value throughout the program.
Example 2:
a, b, c = 1, 2, 3
In this example, the values 1, 2, and 3 are assigned to variables a, b, and c respectively.
Each value is assigned to its corresponding variable based on the order of appearance.
11 | P a g e
h琀琀ps://[Link]/
Example 3:
x=5
y=3
result = x + y
In this example, the variables x and y hold the values 5 and 3 respectively. The
expression x + y is evaluated, and the result 8 is assigned to the variable result.
Example 4:
x = 10
x = x + 5 # x is updated to 15
In this example, the variable x initially holds the value 10. The expression x + 5
evaluates to 15, and that value is assigned back to the variable x.
12 | P a g e
h琀琀ps://[Link]/
My First Program :
The program starts with a comment explaining the purpose of the program.
The print() function is used to display the welcome message.
The input() function is used to prompt the user to enter a word or phrase. The value
entered by the user is stored in the text variable.
13 | P a g e
h琀琀ps://[Link]/
The len() function is used to determine the length of the text string, and the result is
stored in the length variable.
The program displays a message with the length of the entered text using the print()
function.
The input() function is used again to get the user's name and age. The values entered
by the user are stored in the name and age variables, respectively.
The int() function is used to convert the age value from a string to an integer.
The program calculates the user's age in 10 years by adding 10 to the age variable,
and the result is stored in the age_in_future variable.
The program displays a message with the user's name, age, and the calculated age in
10 years using the print() function.
The str() function is used to convert the age integer back to a string so that it can be
concatenated with other strings in the message variable.
The final message is displayed using the print() function.
The program demonstrates the usage of these functions: print() for displaying
messages, len() for determining the length of a string, input() for obtaining user
input, int() for converting a string to an integer, and str() for converting an integer to
a string.
Comments:
14 | P a g e
h琀琀ps://[Link]/
Example:
# Printing a message
print(“ Enter your Name “)
myName = input (“ Enter Your Name”) # Read your name to myName
Example:
# It is a
# multiline
# comment
2. Using String Literals ''' at the beginning and end of multiple lines
Example:
'''
I am a
Multiline comment!
'''
The print() Function :
The print function is used to display the string value written within pair of double
quotes inside the parentheses on the screen .
The line print('The length of your name is:') means “Print out the text in the string ‘'The
length of your name is:’ . When Python executes the print statement, python interpreter
calls the print()function and the string value is being passed to the function. The value
within print() is called argument . Quotes within parentheses marks where the string
begins and ends ; they are not part of the string value.
15 | P a g e
h琀琀ps://[Link]/
This function is used to take the input from the user . Whatever the user enter as input,
input() function convert it into a string . if you enter an integer value still input()
function convert it into a string . The programmer is needed to convert it into an integer
in your code using typecasting.
Myname = input(“Enter your name”)
Programmer often want as user to enter multiple values in one line . In Python user
can take multiple values or inputs in one line by using split() method . It breaks the
given input by the specified separator. If separator is not provided then any white
space is a separator. Generally, user use a split() method to split a Python string but
one can used it in taking multiple input.
Example:
>>> x, y,z = input ("Enter three values").split()
Enter three values 2 3 4
>>> x
'2'
>>> y
'3'
>>> z
'4'
16 | P a g e
h琀琀ps://[Link]/
The str(), int(), and float() functions in Python are used to convert values between
different data types. Here's an explanation of each function with examples:
str() Function:
The str() function is used to convert a value to a string data type. It takes any valid
Python object as an argument and returns a string representation of that object. Here's
an example:
number = 10
number_str = str(number)
print(number_str) # Output: "10"
str() function can be used convert integer or floating numbers into string data type.
int() Function:
The int() function is used to convert a value to an integer data type. It can convert a
string or a float to an integer by truncating any decimal places. Here are some
examples:
number_str = "20"
number_int = int(number_str)
print(number_int) # Output: 20
float_num = 3.14
float_int = int(float_num)
print(float_int) # Output: 3
In the first example, the int() function converts the string "20" to an integer value 20.
In the second example, the int() function converts the float value 3.14 to an integer by
truncating the decimal places, resulting in the value 3.
float() Function:
The float() function is used to convert a value to a floating-point data type. It can
convert a string or an integer to a float. Here's an example:
number_str = "3.14"
number_float = float(number_str)
print(number_float) # Output: 3.14
17 | P a g e
h琀琀ps://[Link]/
integer_num = 10
integer_float = float(integer_num)
print(integer_float) # Output: 10.0
In the first example, the float() function converts the string "3.14" to a floating-point
value 3.14. In the second example, the float() function converts the integer value 10 to
a float value 10.0.
These functions are useful when you need to convert values between different data
types in Python. They allow you to perform operations and manipulate values in the
desired format.
18 | P a g e
h琀琀ps://[Link]/
Order of opera琀椀ons
• When more than one operator appears in an expression, the order of
evalua琀椀on depends on the rules of precedence.
PEMDAS order of opera琀椀on is followed in Python:
• Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
• Exponen琀椀a琀椀on has the next highest precedence,
• Mul琀椀plica琀椀on and Division have the same precedence, which is higher than
• Addi琀椀on and Subtrac琀椀on, which also have the same precedence.
• Operators with the same precedence are evaluated from le昀琀 to right.
19 | P a g e
h琀琀ps://[Link]/
Python interpreter evaluates parts of the expression as per the PEMDAS rule un琀椀l
it becomes a single value as illustrated below:
(5-2)*((8+4)/(5-2))
3 * ((8+4)/(5-2))
3*(12/(5-2))
3*(12/3)
3*4.0
12.0
Note: If you type invalid expressions, python interpreter will not be able to
understand it and will display a SyntaxError message as illustrated below:
20 | P a g e
h琀琀ps://[Link]/
Python Tokens:
A token (lexical unit) is the smallest element of Python script that is meaningful to
the interpreter. Python has following categories of tokens: Iden琀椀昀椀ers, Keywords,
Literals , operators and delimiters.
Iden琀椀昀椀ers: Iden琀椀昀椀ers are names that you give to a variable, class or Func琀椀on.
There are certain rules for naming iden琀椀昀椀ers similar to the variable declara琀椀on
rules, such as : No Special character except_ , Keywords are not used as iden琀椀昀椀ers
, the 昀椀rst character of an iden琀椀昀椀er should be _ underscore or a character , but a
number is not valid for iden琀椀昀椀ers and iden琀椀昀椀ers are case sensi琀椀ve .
21 | P a g e
h琀琀ps://[Link]/
22 | P a g e
h琀琀ps://[Link]/
Delimiters: Delimiters are the symbols which can be used as separators of values or
to enclose some values.
Examples : Comma (,),Colon (:),Parentheses (( and )),Square brackets ([ and
]),Curly braces ({ and }),Quota琀椀on marks (' and ") and Backslash (\)
Note : Comments and # symbol used to insert a comment is not a token.
Keywords: The reserved words of Python which have a special 昀椀xed meaning for
the interpreter are called keywords. No keyword can be used as an iden琀椀昀椀er or
variable names. There are 35 keywords in python as listed below:
Keyword Description
and Logical and operator
as Alias
assert Used for debugging
async Used to make a function asynchronous by adding the async keyword before the
function’s regular definition
await Used in asynchronous functions to specify a point in the function where control is
given back to the event loop for other functions to run. You can use it by placing
the await keyword in front of a call to any async function
break To break out of a loop
class To define a class
continue For skipping the statements and conitinuing the next iteration
def For defining user defined functions
del To delete an object
elif Conditional statement, same as else if
else Conditional statement
except Used in exception handling
False Boolean Value
finally Used in exception handling , to execute a block of code no matter whether
exception is there or not
for Used to create for loop – iterative statement
from Used to import specific parts of a module
global Used to declare global variable
if Conditional /decision making statement
import Used to import a module or library
in Used to check if a value if present in list, tuple, dictionaries , sets ,etc.
is To check if two variables are equal
lambda Used for defining an anonymous function
None Used to represent a null value
nonlocal To declare a non-local variable
23 | P a g e
h琀琀ps://[Link]/
Following code segment can be used to obtain the list of python keywords :
import keyword
# Get the list of keywords
print([Link])
print("\n Total Number of Keywords: ",len([Link]))
# Output :
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'con琀椀nue', 'def', 'del', 'elif', 'else', 'except', '昀椀nally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Total Number of Keywords: 36
24 | P a g e
h琀琀ps://[Link]/
# output
Enter 昀椀rst number 3
Enter second number 2
Sum: 5
Product: 6
25 | P a g e
h琀琀ps://[Link]/
Di昀昀erence: 1
Division: 1.5
Integer Division: 1
Modulo Division: 1
# output
Enter the radius of the circle: 2.5
The area of the circle is: 19.634954084936208
3. To 昀椀nd the simple interest
# Take input for principal amount, rate, and 琀椀me
principal = 昀氀oat(input("Enter the principal amount: "))
rate = 昀氀oat(input("Enter the interest rate: "))
琀椀me = 昀氀oat(input("Enter the 琀椀me period (in years): "))
# Output
Enter the principal amount: 10000
Enter the interest rate: 2.5
Enter the 琀椀me period (in years): 3
The simple interest is: 750.0
26 | P a g e
h琀琀ps://[Link]/
27 | P a g e
h琀琀ps://[Link]/
28 | P a g e
h琀琀ps://[Link]/
Output :
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are
30 | P a g e
h琀琀ps://[Link]/
Boolean Values: A Boolean value is either true or false. It is named a昀琀er the Bri琀椀sh
mathema琀椀cian, George Boole, who 昀椀rst formulated Boolean algebra. In Python the
two Boolean Values are True and False and the Python type is bool. Enter the
following into the Python shell and observe the output.
type(True) # output : bool
type(False) # output : bool
type(true) # output: Name Error : name “ true” is not defined
type(false) # output: Name Error : name “ false” is not defined
context = True
print(context) #output : True
5 == 6 # output: False
In the 昀椀rst statement the two operands evaluate to equal values, so the expression
evaluates to True; in the second statement, 5 is not equal to 6 we get False.
P = “hel”
P + “lo” == “hello” # output: True
In the above example since the concatenated value P + “lo” is “hello” the
expression evaluates to True .
31 | P a g e
h琀琀ps://[Link]/
Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean
value. The == operator is one of six common comparison operators which all
produce a bool result. Table lists all the comparison operators:
Operator Meaning
== Equal to
!= Not Equal to
< Less than
> Greater than
<= Les than or equal to
>= Greater than or equal to
Boolean Operators:
Boolean operators evaluate the expression to Boolean Values True/False. Python
supports three Boolean operators and, or & not. Based on the number of operands
required they can be classi昀椀ed into Binary Boolean operators and Unary Boolean
Operators.
Binary Boolean operators : and & or
Since both and & or operators takes two operands, they are considered as binary
operators. The and operator returns true value if both operands are true and return
false otherwise. While or operator returns false when both operands are false and
returns true otherwise.
True and True # output : True
True and False # output : False
False and True # output : False
False and False # output :False
33 | P a g e
h琀琀ps://[Link]/
Following truth tables illustrates all possible logical combina琀椀ons and values for OR
and AND Boolean binary operators.
Not operator: It is a unary operator and evaluates the expression to opposite value
true or false as illustrated below :
not True # output : False
not False # output : True
not not not not True # output : True
Examples for Mixing Boolean and Comparison Operators: Boolean operators and
comparison operators can be used in combina琀椀on as illustrated below :
x = 10
y = 20
x<y and x>y # output : False
(x<y) and (x!=y) or (x*2) and (x<20 or y<20) # output : True
2+2 == 4 and not 2+2 == 5 and 2*2 == 2+2 #output : True
5*7 +8 == 7 or not 5+7 ==10 and 5*4 ==20 #output : True
34 | P a g e
h琀琀ps://[Link]/
a) Conditions:
Conditions are Boolean expressions with the boolean values True or False. Flow
control statements decides what to do based on the condition whether it is true or
false.
Example 1:
x = int(input(“Enter a number: “)) # Block
if x>=10: # Condition
x = x + 25 # Block belonging to if
y=x
print(x,y)
print(“Next statement”) # Next Block
35 | P a g e
h琀琀ps://[Link]/
Flow control statements in Python are used to control the order of execution and
make decisions based on certain conditions. The main flow control statements in
Python include:
Conditional Control Statements:
• if statement: Executes a block of code if a specified condition is true.
• elif statement: Allows you to check additional conditions if the previous if or
elif conditions are false.
• else statement: Executes a block of code if none of the previous conditions
are true.
Looping Statements:
• for loop: Iterates over a sequence (such as a list, tuple, string, or range) and
executes a block of code for each item in the sequence.
• while loop: Repeats a block of code as long as a specified condition is true.
36 | P a g e
h琀琀ps://[Link]/
1. if statement:
It is basically a two-way decision statement and it is used in conjunction
with an expression. It is used to execute a set of statements if the condition
is true. If the condition is false it skips executing those set of statements.
The syntax and flow chart of if statement is as illustrated below:
Entry
False
Is Condition?
True
S1
S2
S3
---
Sn
Sn+1
37 | P a g e
h琀琀ps://[Link]/
2. If else statement:
38 | P a g e
h琀琀ps://[Link]/
True False
Is
Condition?
Statement x
Example: Program to check whether a given number is even or odd using if else.
3. Nested if else:
When a series of decisions are involved, we may have to use more than one if else
statement in nested form. The nested if else statements are multi decision statements
which consist of if else control statement within another if or else section. The syntax
and flow diagram for nested if else is as shown below:
39 | P a g e
h琀琀ps://[Link]/
False
True
Cond1
True False
False True
Cond3 Cond2
S3 S4 S2 S1
Statement x
Fig : Syntax and flow diagram for nested if else statement
Example:
40 | P a g e
h琀琀ps://[Link]/
4. if – elif ladder:
Cascaded if elif else is a multipath decision statements which consist of chain of
if elseif where in the nesting take place only in else block. As soon as one of the
conditions controlling the ‘if’ is true , then statement /statements associated with
that ‘if’ are executed and the rest of the ladder is bypassed. If condition is false
then it checks the first elif condition , if it is found true then first elif is executed.
However, if none of the elif ladder is correct then the final else statement will be
executed and control flows from top to down.
The syntax and flow diagram for cascaded if else is as shown in figure.
Syntax
T F
if C1: C1
S1 F
elif C2: T C2
S2 S1
elif C3: S2
T F
S3 C3
elif C4:
S3
S4
T
------- Cn
elif Cn:
F
Sn
else: Sn
default
default stmnt statement
Statement x;
Statement x
41 | P a g e
h琀琀ps://[Link]/
Example:
3. Iteration or looping:
The statement which are used to repeat a set of statements repeatedly for a given
number of times or until a given condition is satisfied is called as looping
constructs or looping statements. The set or block of statements used for looping
is called loop.
Types of Looping statements:
Depending on the position of the control statement in the loop the looping
statements are classified into the following two types:
1. Entry controlled Loop
2. Exit Controlled Loop
42 | P a g e
h琀琀ps://[Link]/
FALSE
Is
Condi琀椀on?
TRUE
Body of the
Loop
[Link] Controlled Loop: In the exit controlled loop the test is performed at the
end of the body of the loop and therefore the body is executed unconditionally
for the first time. It is also known as posttest loop. Here the body of the loop will
get executed at least once before [Link] flow chart for the exit controlled
loop is as illustrated in fig .
43 | P a g e
h琀琀ps://[Link]/
Body of the
Loop
TRUE
Is
Condi琀椀on?
FALSE
44 | P a g e
h琀琀ps://[Link]/
ini琀椀aliza琀椀on
45 | P a g e
h琀琀ps://[Link]/
Example: Program to find the sum of n natural numbers using while loop.
For loop:
The for loop is another entry-controlled loop. It is used to execute the set of
statements repeatedly over a range of values or a sequence. With every iteration of
the loop, the control variable checks whether each of the values in the range has been
traversed or not. When all the items in the range are traversed the control is then
transferred to the statement immediately following for loop.
46 | P a g e
h琀琀ps://[Link]/
Flow Chart:
47 | P a g e
h琀琀ps://[Link]/
48 | P a g e
h琀琀ps://[Link]/
The argument of range() function must be integers. The step parameter can be any
positive or negative integer other than zero.
Infinite Loop: A loop becomes in昀椀nite loop if a condi琀椀on never becomes FALSE.
You must use cau琀椀on when using while loops because of the possibility that this
condi琀椀on never resolves to a FALSE value. This results in a loop that never ends.
Such a loop is called an in昀椀nite loop.
An in昀椀nite loop might be useful in client/server programming where the server
needs to run con琀椀nuously so that client programs can communicate with it as and
when required.
Nested Loops:
Python programming language allows to use one loop inside another loop.
49 | P a g e
h琀琀ps://[Link]/
Example:
50 | P a g e
h琀琀ps://[Link]/
Jump statements:
You might face a situa琀椀on in which you need to exit a loop completely when an
external condi琀椀on is triggered or there may also be a situa琀椀on when you want to
skip a part of the loop and start next execu琀椀on.
Python provides break and con琀椀nue statements to handle such situa琀椀ons and to
have good control on your loop.
The break statement in Python terminates the current loop and resumes
execu琀椀on at the next statement, just like the tradi琀椀onal break found in C.
The most common use for break is when some external condi琀椀on is triggered
requiring a hasty exit from a loop. The break statement can be used in
both while and for loops.
The con琀椀nue statement in Python returns the control to the beginning of the while
loop. The con琀椀nue statement rejects all the remaining statements in the current
itera琀椀on of the loop and moves the control back to the top of the loop.
51 | P a g e
h琀琀ps://[Link]/
The con琀椀nue statement can be used in both while and for loops.
Example:
52 | P a g e
h琀琀ps://[Link]/
Example :
The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 through 20.
Similar way you can use else statement with while loop.
53 | P a g e
h琀琀ps://[Link]/
54 | P a g e
h琀琀ps://[Link]/
Importing Modules
Python func琀椀on de昀椀ni琀椀on can, usefully, be stored in one or more separate 昀椀les for
easier maintenance and to allow them to beused in several programs without
copying the de昀椀ni琀椀ons into each one. Each 昀椀le storing func琀椀on de昀椀ni琀椀ons is called
a “module” and the module name is the 昀椀le name with “.py” extension.
Example:
Func琀椀ons stored in the module are made available to a program using the Python
import keyword followed by the module name. Although not essen琀椀al, it is
customary to put any import statements at the beginning of the program.
Imported func琀椀ons can be called using their name dot -su昀케xed a昀琀er the module
name. For example, a “f1()” func琀椀on from an imported module named
“userde昀椀ned” can be called with userde昀椀ned.f1() .
Design a new Python module called userde昀椀ned by de昀椀ning all func琀椀ons as
illustrated below. Save the 昀椀le as userde昀椀[Link] and run the 昀椀le.
userde昀椀[Link]
Start a new script with name [Link] (/ipynb). Next call each func琀椀on
with and without arguments as per the requirements. Run the program and get the
output as illustrated below:
55 | P a g e
h琀琀ps://[Link]/
Impor琀椀ng Modules:
Python includes “sys” and “keyword” modules that are useful for interroga琀椀ng the
Python system itself. The keyword module contains a list of all Python keywords in
its kwlist a琀琀ribute and provides as iskeyword () method if you want to rest a word.
56 | P a g e
h琀琀ps://[Link]/
57 | P a g e
h琀琀ps://[Link]/
Performing Mathema琀椀cs
Random
58 | P a g e
h琀琀ps://[Link]/
59 | P a g e
h琀琀ps://[Link]/
60 | P a g e
h琀琀ps://[Link]/
61 | P a g e
h琀琀ps://[Link]/
62 | P a g e
h琀琀ps://[Link]/
[Link] a program to find the best of two test average marks out of
three tests marks accepted from the user.
[Link] a program to find the largest of three numbers . [ VTU June
/July 2019]
[Link] a program to check whether the given year is leap or not. [
VTU June /July 2019]
[Link] a program to generate and print prime number between 2
to 50.
[Link] a program to find those numbers which are divisible by 7
and multiple of 5 , between 1000 and 3000.
[Link] a program to guess a number between 1 to 10.
[Link] a program that accepts a word from the user and reverse it.
[Link] a program to count the number of even and odd numbers
from a series of numbers.
[Link] a program that prints all the numbers from 0 to 10 except
3, 7 and 10.
[Link] a program to generate Fibonacci series between 0 and 50.
[Link] a program which iterates the integers from 1 to 50. For
multiple of three print “Fizz” instead of the numbers and fro the
multiples of five print “Buzz” . For numbers which are multiples of
both three and five print “FizzBuzz”.
[Link] a program that accepts a string and calculate the number
of digits and letters.
[Link] a program to check the validity of password input by users.
[Link] a program to find the numbers between 100 and 400
where each digit of a number is an even number . The numbers
obtained should be printed in a comma-separated sequence.
[Link] a program to print alphabet patterns ‘A’ ,D, ‘E’, ‘G’,’L’, ‘T’
and ‘S’ with * symbol.
63 | P a g e
h琀琀ps://[Link]/
1
22
333
4444
55555
666666
7777777
88888888
999999999
*
* *
* * *
* * * *
* * * * *
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
64 | P a g e
h琀琀ps://[Link]/
A
B B
C CC
D DDD
E EEEE
* * * * *
* * * *
* * *
* *
*
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
65 | P a g e
h琀琀ps://[Link]/
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1
2 3
4 5 6
7 8 9 10
66 | P a g e
h琀琀ps://[Link]/
1.3 Func琀椀ons
1.3.1 Introduc琀椀on
A func琀椀on is a group (or block ) of statements that perform a speci昀椀c task .
Func琀椀ons run only when it is called. One can pass data into the func琀椀on in the form
of parameters. Func琀椀on can also return data as a result. Instead of wri琀椀ng a large
program as one long sequence of instruc琀椀ons , it can be wri琀琀en as several small
func琀椀on , each performing a speci昀椀c part of the task . They cons琀椀tute line of code(s)
that are executed sequen琀椀ally from top to bo琀琀om by Python interpreter. A python
func琀椀on is wri琀琀en once and is used / called as many 琀椀me as required . Func琀椀ons
are the most important building blocks for any applica琀椀on in Python and work on
the divide and conquer approach. Func琀椀ons can be conquered into the following
three types :
(i) User De昀椀ned
(ii) Built in
(iii) Modules
67 | P a g e
h琀琀ps://[Link]/
Statements below def begin with four spaces. This is called indenta琀椀on. It is a
requirement of Python that the code following a colon must be indented. A
func琀椀on de昀椀ni琀椀on consists of the following components;
1. Keyword def marks the start of function header
2. A function name to uniquely identify it. Function naming follows the same
rules as rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function . They
are optional.
4. A colon (: ) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function
does.
6. One or more valid Python statements that make up the function body.
Statements must have same indentation level (usually) 4 spaces)
7. An optional return statement to return a value from the function .
Example :
def cube(n):
ncube = n**3
return ncube
fun_name(parameter list)
Example: cube(3)
68 | P a g e
h琀琀ps://[Link]/
69 | P a g e
h琀琀ps://[Link]/
70 | P a g e
h琀琀ps://[Link]/
The None-Value
In Python there is a value called None, which represents the absence of a value. None is the only
value of the None Type data type. (Other programming languages might call this value null, nil,
or unde昀椀ned.) Just like the Boolean True and False values, None must be typed with a capital N.
71 | P a g e
h琀琀ps://[Link]/
72 | P a g e
h琀琀ps://[Link]/
If you run this program the output will look like this
73 | P a g e
h琀琀ps://[Link]/
The error happens because the x variable exists only in the local scope created
when fun1() is called. Once the program execu琀椀on returns from fun1(), that local
scope is destroyed, and there is no longer a variable named x. So when your
program tries to run print(x), Python gives you an error saying that x is not de昀椀ned.
This makes sense if you think about it; when the program execu琀椀on is in the global
scope, no local scopes exist, so there can’t be any local variables. This is why only
global variables can be used in the global scope.
Local Scopes Cannot Use Variables in Other Local Scopes
A new local scope is created whenever a func琀椀on is called, including when a
func琀椀on is called from another func琀椀on. Consider this program:
When the program starts the func1() is called and a local scope is created . The local
variable x is set to 10. Then fun2() is called and a second local scope is created .
Mul琀椀ple local scopes can exist at the same 琀椀me . In this new local scope , the local
variable y is set to 21 and a local variable x which is di昀昀erent from the one in fun1()’s
local scope is also created and set to 0. When fun2() returns the local scope for the
call to fun1() s琀椀ll exists here the x variable is set to 10. This is what the programs
prints.
The local variables in one func琀椀on are completely separate the local variable in
another func琀椀on.
74 | P a g e
h琀琀ps://[Link]/
Since there is no parameter named x or any code that assigns x a value in the fun1()
func琀椀on , when x is used in fun1(), Python considers it a reference to the global
variable x. This is why 42 is printed when the previous program is run.
75 | P a g e
h琀琀ps://[Link]/
There are actually three di昀昀erent variables in this program, but confusingly they are
all named x.
A variable named x that exists in a local scope when fun1() is called.
A variable named x that exists in a local scope when fun2() is called
A variable named x that exists in the global scope
Since these three separate variables all have the same name, it can be confusing
to keep of which one is being used at any given 琀椀me . This is why you should
avoid using the same variable name in di昀昀erent scopes.
Global Statement
If you need to modify a global variable from within a func琀椀on , used the global
statement . If you have a line such as global x at the top of a func琀椀on , it tells
Python, In this func琀椀on, x refers to the global variable, so don’t create a local
variable with this name.” For example, type the following code and run
When you run this program the 昀椀nal print() call will output this :
Because x is declared global at the top of spam() , when x is set to 'spam' , this
assignment is done to the globally scoped x. No local x variable is created.
There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all func琀椀ons),
then it is always a global variable.
2. If there is a global statement for that variable in a func琀椀on, it is a global
variable.
76 | P a g e
h琀琀ps://[Link]/
Excep琀椀onal Handling
Right now, ge琀�ng an error, or excep琀椀on, in your Python program means the en琀椀re
program will crash. You don’t want this to happen in real-world programs. Instead,
you want the program to detect errors, handle them, and then con琀椀nue to run. For
example, consider the following program, which has a “divide-byzero” error. Open
a new 昀椀le editor window and enter the following code, saving it as [Link]:
We’ve de昀椀ned a func琀椀on called spam, given it a parameter, and then printed the value of that func琀椀on
with various parameters to see what happens. This is the output you get when you run the previous
code:
A ZeroDivisionError happens whenever you try to divide a number by zero. From the line number given
in the error message, you know that the return statement in spam() is causing an error.
77 | P a g e
h琀琀ps://[Link]/
Errors can be handled with try and except statements. The code that could poten琀椀ally have an error is
put in a try clause. The program execu琀椀on moves to the start of a following except clause if an error
happens. You can put the previous divide-by-zero code in a try clause and have an except clause contain
code to handle what happens when this error occurs.
When code in a try clause causes an error, the program execu琀椀on immediately moves to the code in the
except clause. A昀琀er running that code, the execu琀椀on con琀椀nues as normal. The output of the previous
program is as follows:
Note that any errors that occur in func琀椀on calls in a try block will also be caught. Consider the following
program, which instead has the spam() calls in the try block:
78 | P a g e
h琀琀ps://[Link]/
The reason print(spam(1)) is never executed is because once the execu琀椀on jumps to the code in the
except clause, it does not return to the try clause. Instead, it just con琀椀nues moving down as normal.
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
dela琀琀r() Deletes the speci昀椀ed a琀琀ribute (property or method) from the speci昀椀ed object
divmod() Returns the quo琀椀ent and the remainder when argument1 is divided by argument2
79 | P a g e
h琀琀ps://[Link]/
map() Returns the speci昀椀ed iterator with the speci昀椀ed func琀椀on applied to each item
range() Returns a sequence of numbers, star琀椀ng from 0 and increments by 1 (by default)
80 | P a g e
h琀琀ps://[Link]/
iii. Modules :
As the programs become more lengthy and complex, there arises a need for the
tasks to be split into smaller segments called modules.
A module is a 昀椀le containing func琀椀ons and variable de昀椀ned in separate 昀椀les. A
module is simply a 昀椀le that contains Python code or a series of instruc琀椀ons . When
we break a program into modules , each module should contain func琀椀ons that
performs related tasks . There are some commonly used modules in Python that
are used for certain prede昀椀ned tasks and they are called libraries.
Modules also make it easier to reuse the same code in more than one program. If
we have wri琀琀en a ste of func琀椀ons that is needed in several di昀昀erent programs , we
can place those func琀椀ons that is needed in several di昀昀erent programs, we can place
those func琀椀ons in a module. Then we can import the module in each program that
needs to call one of the func琀椀ons . Once we import a module we can refer to any
of its func琀椀ons or variable in our program.
A module in Python is a 昀椀le that contains a collec琀椀on of related func琀椀ons.
81 | P a g e
h琀琀ps://[Link]/
Output
82 | P a g e
h琀琀ps://[Link]/
83 | P a g e
h琀琀ps://[Link]/
84 | P a g e
h琀琀ps://[Link]/
-Example :
Example :
Example:
Example:
85 | P a g e
h琀琀ps://[Link]/
Example:
Example :
Example :
86 | P a g e
h琀琀ps://[Link]/
Example :
Example :
Example :
Example :
87 | P a g e
h琀琀ps://[Link]/
Sample Programs
Example1: A Short Program , Guess the Number
88 | P a g e
h琀琀ps://[Link]/
Simple Project:
89 | P a g e
h琀琀ps://[Link]/
90 | P a g e
h琀琀ps://[Link]/
91 | P a g e
h琀琀ps://[Link]/
45.A polygon can be represented by a list of (x, y) pairs where each pair is a
tuple: [ (x1, y1), (x2, y2), (x3, y3) , … (xn, yn)]. Write a Recursive function to
compute the area of a polygon. This can be accomplished by “cutting off” a
triangle, using the fact that a triangle with corners (x1, y1), (x2, y2), (x3, y3)
has area (x1y1 + x2y2 + x3y2 – y1x2 –y2x3 – y3x1) / 2.
[Link] is a lambda function?
[Link] Do We Write A Function In Python?
[Link] Is “Call By Value” In Python?
[Link] Is “Call By Reference” In Python?
[Link] It Mandatory For A Python Function To Return A Value? Comment?
[Link] Does The *Args Do In Python?
[Link] Does The **Kwargs Do In Python?
[Link] Python Have A Main() Method?
[Link] Is The Purpose Of “End” In Python?
[Link] Does The Ord() Function Do In Python?
[Link] are split(), sub(), and subn() methods in Python?
[Link] the syntax for the following functions and explain with an
example: a) abs() b) max() c) divmod() d) pow() e) len()
92 | P a g e
h琀琀ps://[Link]/
1. Function showChoice: This function shows the options to the user and explains how
to enter data.
2. Function add: This function accepts two number as arguments and returns sum.
3. Function subtract: This function accepts two number as arguments and returns their
difference.
4. Function mulitiply: This function accepts two number as arguments and returns
product.
5. Function divide: This function accepts two number as arguments and returns
quotient.
Define a function main() and call functions in main().
93 | P a g e
h琀琀ps://[Link]/
94 | P a g e
h琀琀ps://[Link]/
be “perfect number” if its factors, including 1(but not the number itself),
sum to the number. E.g., 6 is a perfect number because 6=1+2+3].
[Link] a function to check if a number is even or not.
[Link] a function to check if a number is prime or not.
[Link] a function to find factorial of a number but also store the factorials
calculated in a dictionary as done in the Fibonacci series example.
31. Write a function to calculate area and perimeter of a rectangle.
[Link] is the output of the following Code ?
def foo(u, v, w=3):
return u * v * w
def bar(x):
y = 4
return foo(x, y)
print(foo(4,5,6))
print(bar(10))
def change(t1,t2):
t1 = [100,200,300]
t2[0]= 8
list1 = [10,20,30]
list2 = [1,2,3]
change(list1, list2)
print(list1)
print(list2)
x = [10,20,30]
y = [1,2,3,4]
dot(x,y)
95 | P a g e
h琀琀ps://[Link]/
def bar(arr,n):
for i in range(n-1):
buz(arr,n-i)
t = [19,7,4,1]
bar(t,len(t))
n1 = 150
n2 = 100
change(n1,n2)
change(n2)
change(num2=n1,num1=n2)
96 | P a g e
h琀琀ps://[Link]/