You are on page 1of 116

APPLICATION DEVELOPMENT USING PYTHON

(Effective from the academic year 2018 -2019)


SEMESTER – V

Course Code: 18CS55 IA Marks : 40


Number of Lecture Hours/Week : 03 Exam Marks: 60
Total Number of Lecture Hours : 40 Exam Hours : 03

CREDITS – 03
Course Learning Objectives: This course will enable students to-

• Learn the syntax and semantics of Python programming language.


• Illustrate the process of structuring the data using lists, tuples and
dictionaries.
• Demonstrate the use of built-in functions to navigate the file system.
• Implement the Object Oriented Programming concepts in Python.
• Appraise the need for working with various documents like Excel, PDF,
Word and Others.
Syllabus
Module – 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,
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 Value, Keyword Arguments and print(), Local and
Global Scope, The global Statement, Exception Handling, A Short Program:
Guess the Number
Textbook 1: Chapters 1 – 3
Syllabus
Module – 2
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,
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing,
Using Data Structures to Model Real-World Things,
Manipulating Strings: Working with Strings, Useful String Methods, Project:
Password Locker, Project: Adding Bullets to Wiki Markup
Textbook 1: Chapters 4 – 6
Module – 3 Syllabus
Pattern Matching with Regular Expressions: Finding Patterns of Text Without Regular
Expressions, Finding Patterns of Text with Regular Expressions,More Pattern Matching with
Regular Expressions, Greedy and Nongreedy Matching, The findall() Method, Character
Classes, Making Your Own Character Classes, The Caret and Dollar Sign Characters, The
Wildcard Character, Review of Regex Symbols, Case-Insensitive Matching, Substituting Strings
with the sub() Method, Managing Complex Regexes, Combining re .IGNORECASE, re .DOTALL,
and re .VERBOSE, Project: Phone Number and Email Address Extractor,
Reading and Writing Files: Files and File Paths, The os.path Module, The File Reading/ Writing
Process, Saving Variables with the shelve Module, Saving Variables with the pprint.pformat()
Function, Project: Generating Random Quiz Files, Project: Multiclipboard,
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 into a ZIP File,
Debugging: Raising Exceptions, Getting the Traceback as a String, Assertions, Logging, IDLE’s
Debugger.
Textbook 1: Chapters 7 – 10
Syllabus
Module – 4
Classes and objects: Programmer-defined types, Attributes, Rectangles,
Instances as return values, Objects are mutable, Copying,
Classes and functions: Time, Pure functions, Modifiers, Prototyping versus
planning,
Classes and methods: Object-oriented features, Printing objects, Another
example, A more complicated example, The init method, The __str__ method,
Operator overloading, Type-based dispatch, Polymorphism, Interface and
implementation,
Inheritance: Card objects, Class attributes, Comparing cards, Decks, Printing the
deck, Add, remove, shuffle and sort, Inheritance, Class diagrams, Data
encapsulation
Textbook 2: Chapters 15 – 18
Module – 5 Syllabus
Web Scraping, Project: MAPIT.PY with the web browser Module, Downloading Files from
the Web with the requests Module, Saving Downloaded Files to the Hard Drive, HTML,
Parsing HTML with the BeautifulSoup Module, Project: “I’m Feeling Lucky” Google
Search, Project: Downloading All XKCD Comics, Controlling the Browser with the
selenium Module,
Working with Excel Spreadsheets, Excel Documents, Installing the openpyxl Module,
Reading Excel Documents, Project: Reading Data from a Spreadsheet, Writing Excel
Documents, Project: Updating a Spreadsheet, Setting the Font Style of Cells, Font
Objects, Formulas, Adjusting Rows and Columns, Charts,
Working with PDF and Word Documents, PDF Documents, Project: Combining Select
Pages from Many PDFs, Word Documents,
Working with CSV files and JSON data, The csv Module, Project: Removing the Header
from CSV Files, JSON and APIs, The json Module, Project: Fetching Current Weather Data
Textbook 1: Chapters 11 – 14
Course Outcomes:
After studying this course, students will be able to
• Demonstrate proficiency in handling of loops and creation of functions.
• Identify the methods to create and manipulate lists, tuples and dictionaries.
• Discover the commonly used operations involving regular expressions and file
system.
• Interpret the concepts of Object-Oriented Programming as used in Python.
• Determine the need for scraping websites and working with CSV, JSON and
other file formats.
Text Books:
1. Al Sweigart,“Automate the Boring Stuff with Python”,1stEdition, No Starch Press, 2015.
(Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/) (Chapters 1 to
18)
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2nd Edition, Green
Tea Press, 2015. (Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf) (Chapters 15, 16, 17, 18) (Download
pdf/html files from the above links)
Reference Books:
1. Gowrishankar S, Veena A, “Introduction to Python Programming”, 1st Edition, CRC Press/Taylor
& Francis, 2018. ISBN-13: 978-0815394372
2. Jake VanderPlas, “Python Data Science Handbook: Essential Tools for Working with Data”, 1st
Edition, O’Reilly Media, 2016. ISBN-13: 978-1491912058
3. Charles Dierbach, “Introduction to Computer Science Using Python”, 1st Edition, Wiley India Pvt
Ltd, 2015. ISBN-13: 978-8126556014
4. Wesley J Chun, “Core Python Applications Programming”, 3rd Edition, Pearson Education India,
2015. ISBN-13: 978-9332555365
Module – 1

Python Basics, Flow control, Functions


Chapter-1
Python Basics
Python Basics
• The Python programming language has a wide range of syntactical
constructions, standard library functions, and interactive development
environment features.
• Python interactive shell: Allows to execute Python instructions one at a
time and shows the results instantly.
• We run the interactive shell by launching IDLE.
Entering Expressions into the Interactive Shell
• When we launch IDLE, a window with the >>> prompt should appear; that’s
the interactive shell.
Example: Enter 2 + 2 at the prompt to have Python do some simple math.
>>> 2 + 2 # >>> interactive shell & 2+2 is an expression
4 # result

• Expression: In Python, 2 + 2 is called an expression, which is the most basic


kind of programming instruction in the language.
• Expressions consist of values and operators, and they can always evaluate
down to a single value.
• We can use expressions anywhere in Python code that we could also use a
value.
Arithmetic Operators
Entering Expressions into the Interactive Shell
Arithmetic Operators
Entering Expressions into the Interactive Shell
• The order of operations (also called precedence) of Python math operators is
similar to that of mathematics.
• The ** operator is evaluated first
• *, / , //, and % operators are evaluated next, from left to right
• + and - operators are evaluated last (also from left to right)
• We can use parentheses to override the usual precedence if required.
Entering Expressions into the Interactive Shell
• Enter the following expressions into the interactive shell and observe the output:
>>> 2 + 3 * 6
20 >>> 23 // 7
3
>>> (2 + 3) * 6
30 >>> 23 % 7
2
>>> 48565878 * 578453
28093077826734 >>> 2 + 2
4
>>> 2 ** 8
256 >>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0
>>> 23 / 7
3.2857142857142856
Entering Expressions into the Interactive Shell
• When we enter the expression, Python evaluating it down to a single value.

• Python will keep evaluating parts of the expression until it becomes a single value
Entering Expressions into the Interactive Shell
If you type in a bad Python instruction, Python won’t be able to understand it
and will display a SyntaxError error message.

>>> 5 +
File "<stdin>", line 1
5+
^
SyntaxError: invalid syntax

>>> 42 + 5 + * 2
File "<stdin>", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax
Comparison Operators

20
Logical Operators
Bitwise Operators
Operator Precedence
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.

The integer values are whole numbers.


Numbers with a decimal point are called floating-point numbers (or floats).
Note: even though the value 42 is an integer, the value 42.0 would be a floating-point
number.
The Integer, Floating-Point, and String Data Types
• Python programs can also have text values called strings.
• A string is surrounded by single quote (') characters. Python knows where the
string begins and ends.
Example: 'Hello' or 'Goodbye’
• A string with no characters in it, '', called a blank string.

• Observe the error message when the following instruction executed


>>> 'Hello world!
SyntaxError: EOL while scanning string literal

(There is no final single quote character at the end of the string)


String Concatenation and Replication
+ is also used as the string concatenation operator. It is used to join two string values.
>>> 'Alice' + 'Bob'
'AliceBob‘

We can’t use the + operator on a string and an integer value


>>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
'Alice' + 42
TypeError: Can't convert 'int' object to str implicitly
String Concatenation and Replication
• When the * operator is used on one string value and one integer value, it
becomes the string replication operator.
>>> '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). Otherwise, Python
will just display an error message.
>>> '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‘
String Concatenation and Replication
>>> 'Alice' * 5.0
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'
Storing Values in Variables
• A variable is like a box in the computer’s • Think of a variable as a labeled
memory where you can store a single box that a value is placed in.
value.
Assignment Statements:
• We can 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 • “The variable spam now has the
stored. integer value 42 in it.”
Example:
spam = 42
Storing Values in Variables
Examples:
>>> spam = 40
>>> spam
40
>>> eggs = 2
>>> spam + eggs
42
>>> spam + eggs + spam
82
>>> spam = spam + 2
>>> spam
42
Storing Values in Variables
• A variable is initialized (or created) the first time a value is
stored in it.
• When a variable is assigned a new value , the old value is
forgotten. This is called overwriting the variable.
Example:
>>> spam = 'Hello'
>>> spam
'Hello‘

>>> spam = 'Goodbye'


>>> spam When a new value is assigned
'Goodbye' to a variable, the old one is
forgotten.
Variable Names
• While naming a variable, follow 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.
Valid variable names Invalid variable names
balance current-balance (hyphens are not allowed)
currentBalance current balance (spaces are not allowed)
current_balance 4account (can’t begin with a number)
_spam 42 (can’t begin with a number)
SPAM total_$um (special characters like $ are not allowed)
account4 'hello' (special characters like ' are not allowed)
Variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are
four different variables.
It is a Python convention to start variables with a lowercase letter.
Your First Program
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?') # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?') # ask for their age
myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
Your First Program
Output
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.
Dissecting Your Program
• Comments
• Any text for the rest of the line following a hash mark (#) is part of a comment.
• Python ignores comments, and can be used to write notes.
• Python also ignores the blank line after the comment.
Example: # This program says hello and asks for my name.

• The print() Function


• The print() function displays the string value inside the parentheses on the screen.
Example:
print('Hello world!') • calling the print() function and the string
value is being passed to the function.
print('What is your name?')
• A value that is passed to a function call is
an argument.
Dissecting Your Program
• The input() Function
• The input() function waits for the user to type some text on the keyboard and
press ENTER.
• When the user presses Enter key, the program resumes and input returns what
the user typed as a string.
Example: myName = input()
• Printing the User’s Name
• The following call to print() actually contains the expression 'It is good to meet
you, ' + myName between the parentheses.
Example: print('It is good to meet you, ' + myName)
• The len() Function
• The function evaluates to the integer value of the number of characters in that
string.
Example: print('The length of your name is:')
print(len(myName))
Dissecting Your Program
Enter the following into the interactive shell to try this:
>>> len('hello')
5

>>> len(‘i am going to college’)


21

>>> len('')
0
Dissecting Your Program
The error that shows up when the following is typed into the interactive shell
>>> print('I am ' + 29 + ' years old.')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print('I am ' + 29 + ' years old.')
TypeError: Can't convert 'int' object to str implicitly

The expression you tried to pass to print() causing the error.

Python gives an error because you can use the + operator only to add two integers
together or concatenate two strings. You can’t add an integer to a string.
>>> 'I am ' + 29 + ' years old.'
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
'I am ' + 29 + ' years old.'
TypeError: Can't convert 'int' object to str implicitly
Dissecting Your Program -The str(), int(), and float() Functions
• The str() function can be passed an integer value and will evaluate to a string value
version of it, as follows:
>>> 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.
Examples:

>>> str(0) >>> int(1.99)


'0' 1

>>> str(-3.14) >>> float('3.14')


'-3.14' 3.14

>>> int('42') >>> float(10)


42 10.0

>>> int('-99') >>> spam = input()


-99 101

>>> int(1.25) >>> spam


1 '101‘
Examples:
>>> spam = int(spam)
>>> spam
101
>>> spam * 10 / 5
202.0

• The int() function is also useful if you need to round a floating-point number down.
• If you want to round a floating-point number up, just add 1 to it afterward.
>>> int(7.7)
7
>>> int(7.7) +1
8
• Note that if you pass a value to int() that it cannot evaluate as an integer, Python will
display an error message.
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99‘

>>> int('twelve')
The int() function is also useful
Traceback (most recent call last): if you need to round a floating-
File "<pyshell#19>", line 1, in <module> point number down.
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve‘
• In the program, we have used the int() and str() functions in the last three lines
to get a value of the appropriate data type for the code.

print('What is your age?') # ask for their age


myAge = input()
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
evaluation steps
Text And Number Equivalence
Text and Number Equivalence
Although the string value of a number is considered a completely different value
from the integer or floating-point version, an integer can be equal to a floating
point.
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this distinction because strings are text, while integers and floats are
both numbers.
Chapter-2
Flow Control
Flow Control
• The real strength of programming isn’t just running (or executing) one instruction
after another.
• Based on how the expressions evaluate, the program can decide to skip
instructions, repeat them, or choose one of several instructions to run.
• Flow control statements can decide which Python instructions to execute under
which conditions.
Flow Control
A flowchart for what to do if it’s raining.
Flow Control
• To learn about flow control statements, we need to-
 learn how to represent those yes and no options, and
 understand how to write those branching points as Python code

Boolean values, comparison operators, and Boolean operators


Boolean Values:
Boolean data type has only two values: True and False
Examples:
>>> spam = True
>>> spam
True
Flow Control
• If you don’t use the proper case or you try to use True and False for variable
names, Python will give you an error message.
>>> true
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
true
NameError: name 'true' is not defined
>>> True = 2 + 2
SyntaxError: assignment to keyword
Comparison Operators
• Expressions with comparison operators evaluate to a Boolean value.
• Below table lists the comparison operators.
Examples: >>> True == True
True
>>> 42 == 42 >>> True != False
True True
>>> 42 == 99 >>> 42 == 42.0
False True
>>> 2 != 3 >>> 42 == '42'
True False
>>> 2 != 2 >>> 42 < 100
False True
>>> 'hello' == 'hello' >>> 42 > 100
False
True
>>> 42 < 42
>>> 'hello' == 'Hello' False
False >>> eggCount = 42
>>> 'dog' != 'cat' >>> eggCount <= 42
True True
The Difference Between the == and = Operators

Just remember these points:


• The == operator (equal to) asks whether two values are the same as
each other.
• The = operator (assignment) puts the value on the right into the
variable on the left.
Boolean Operators
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.
Examples:
>>> True and True
True
>>> True and False
False
Boolean Operators
• 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.

Example:
>>> False or True
True
>>> False or False
False
The not Operator
• Unlike and and or, the not operator operates on only one Boolean value (or
expression).
• The not operator simply evaluates to the opposite Boolean value.

Example:
>>> not True
False
>>> not not not not True
True
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
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.

Conditions
• The Boolean expressions can be considered conditions, which are the same thing
as expressions;
• Conditions always evaluate down to a Boolean value, True or False.
• 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.
Elements of Flow Control
Blocks of Code
Lines of Python code can be grouped together in blocks.
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.
Example: if name == 'Mary':
print('Hello Mary')
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
Program Execution
• Python starts executing instructions at the top of the program going down, one
after another.
• The program execution (or simply, execution) is a term for the current instruction
being executed.
Flow Control Statements
Flow control statements can decide which Python instructions to execute
under which conditions.

• if Statements
• else Statements
• elif Statements
• while Loop Statements
• break Statements
• continue Statements
• for Loops and the range() Function
if Statements
• 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.

• 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)

Example:
if name == 'Alice':
print('Hi, Alice.')
else Statements
• An if clause can be followed by an else statement.
The else clause is executed only when the if
statement’s condition is False.
• 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)
Example:
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
elif Statements
• elif statement is used when we want one of many possible clauses to execute. It provides
another condition that is checked only if any of the previous conditions were False.
• 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)

Example:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
Example
It is not guaranteed that at least one of the clauses will
be executed. When there is a chain of elif statements,
only one or none of the clauses will be executed.
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.')
Example
The order of the elif statements does matter

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.')
Example
• Optionally, an else statement can be used 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.

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.')
Program Example
Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range,
print an error. If the score is between 0.0 and 1.0, print a grade using the following table

Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
while Loop Statements
• We 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)

while Boolean_Expression:
statement(s)
Example :
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1

In the while loop, the condition is always checked


at the start of each iteration (that is, each time the
loop is executed). If the condition is True, then the
clause is executed, and afterward, the condition is
checked again.
The first time the condition is found to be False,
the while clause is skipped.
An Annoying while Loop
Example:
name = ''
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')

Output
Please type your name.
Al
Please type your name.
Albert
Please type your name.
%#@#%*(^&!!!
Please type your name.
your name
Thank you!
break Statements
• A shortcut way 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.

while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
continue Statements
• Like break statements, continue statements are used inside loops. When the program
execution reaches a continue statement, the program execution immediately jumps
back to the start of the loop and re-evaluates the loop’s condition.
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
“Truthy” and “Falsey” Values
• There are some values in other data types that conditions will consider
equivalent to True and False. When used in conditions, 0, 0.0, and '' (the empty
string) are considered False, while all other values are considered True.name = '‘

name =''
while not name:
print('Enter your name:')
name = input()
print('How many guests will you have?')
numOfGuests = int(input())
if numOfGuests:
print('Be sure to have enough room for all your guests.')
print('Done')
Program Examples
1) Write a program that uses a while loop to add up all the even numbers
between 100 and 200
2) Write a program to read N integers and find the sum and average ( N is the
input from the user)
3) Write python program to find the sum of all digits of a given number
4) Write python program to reverse a given number
5) Write a program to find the GCD of two positive numbers
for Loops and the range() Function
• If we want to execute a block of code only a certain number of times, then we can do
this with a for loop statement and the range() function.
for iteration_variable in sequence :
statement(s)
• 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)
The range() function generates a sequence of numbers which can be iterated through
using for loop. The syntax for range() function is,
range([start ,] stop [, step])
Example:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')

Output
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
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.

output
12
13
14
15
The Starting, Stopping, and Stepping Arguments to range()
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.
for i in range(0, 10, 2):
print(i)
output
0
2
4
6
8
The Starting, Stopping, and Stepping Arguments to range()
We can even use a negative number for the step argument to make the for
loop count down instead of up.

for i in range(5, -1, -1):


print(i)

output
5
4
3
2
1
0
Example: for Loop Using range() Function
output
# print("Only ''stop'' argument value specified in range function")
for i in range(3): 0
print(i) 1
2
# print("Both ''start'' and ''stop'' argument values specified in range
function") 2
for i in range(2, 5): 3
print(i) 4

# print("All three arguments ''start'', ''stop'' and ''step'' specified in


range function")
1
for i in range(1, 6, 3):
4
print(i)
break and continue statements inside for loops
• break and continue statements can be used inside for loops as well.
• The continue statement will continue to the next value of the for loop’s
counter, as if the program execution had reached the end of the loop and
returned to the start.
• We can use continue and break statements only inside while and for loops.
If you try to use these statements elsewhere, Python will give you an error.
Program Example
1) Write a program to find the factorial of a number
2) Write a program to display the fibonacci sequences up to nth term where n is
provided by the user ( hint: fibonacci sequence is 0,1,1,2,3,5,…..)
3) Write a program to find the sum of the series 1 + 1/2 + 1/3 +. …. + 1/n
4) Write a program to check whether a given number is prime or not
5) Write a program to generate first N prime numbers
6) Write a program to generate all the prime numbers between m and n
Importing Modules
• Python comes with a set of modules called the standard library. Each
module is a Python program that contains a related group of functions that
can be embedded in the programs.
• For example, the math module has mathematics related functions, the
random module has random number–related functions, and so on.
• Before the use of the functions in a module, we must import the module
with an import statement.
• 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
• Once you import a module, you can use all the functions of that module.
Contd…
Since randint() is in the random module, you
import random
must first type random. in front of the function
for i in range(5):
name to tell Python to look for this function
print(random.randint(1, 10)) inside the random module.

the output will look something like this


4
1
8
4
1

Another example:
Following import statement that imports four different modules:
import random, sys, os, math
Contd… math module few examples
math.pow(x, y)
math.sqrt(x)
math.log2(x)
math.log(x[, base])
math.log10(x) Return the base-10 logarithm of x.
math.pow(x, y) Return x raised to the power y.
math.sqrt(x) Return the square root of x.
math.gcd(a, b)
math.ceil(x) Return the ceiling of x
math.fabs(x) Return the absolute value of x.
math.factorial(x) Return x factorial. Raises ValueError if x is not integral or is
negative.
math.floor(x)
math.exp(x) Return e**x.
Contd…
from import Statements

• An alternative form of the import statement is composed of the from keyword,


followed by the module name, the import keyword, and a star;
from random import *.
from random import randint
for i in range(10):
print(randint(10, 20))
• With this form of import statement, calls to functions in random will not need
the random. prefix.
Ending a Program Early with sys.exit()
• We can terminate, or exit the program by calling the sys.exit() function.
• Since this function is in the sys module, we have to import sys before the
program

import sys Output


while True: Type exit to exit.
print('Type exit to exit.') 4
response = input() You typed 4.
if response == 'exit': Type exit to exit.
sys.exit() 6
print('You typed ' + response + '.') You typed 6.
Type exit to exit.
exit
Chapter-3
Functions
Functions
• Python provides several builtin functions like- print(), input(), and len() etc.
• We can also write our own functions.
• A function is like a mini-program within a program.

Example:

def hello() : def statement, defines a function


print('Hello!') Output:
The body of the function is the code
print('WelCome!!!') in the block that follows the def
print('Hello there….') Hello!
statement
WelCome!!!
hello() Hello there….
function call: This code is executed
when the function is called, not
when the function is first defined.
def Statements with Parameters
• When we call the print() or len() function, we pass in values, called arguments
in this context, by typing them between the parentheses.
• We can also define our own functions that accept arguments.

Example:
def hello(name): The definition of the hello() function in this
print('Hello ' + name) program has a parameter called name.
A parameter is a variable that an argument is
hello('Alice') stored in when a function is called.
hello('Bob')
Output:
Hello Alice
Hello Bob
Return Values and return Statements
• In general, the value that a function call evaluates to is called the return value
of the function.
• When creating a function using the def statement, we can specify what the
return value should be with a return statement
• A return statement consists of the following:
• The return keyword
• The value or expression that the function should return

• When an expression is used with a return statement, the return value is what
this expression evaluates to.
Example
import random
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Try again'
elif answerNumber == 5:
return 'Ask again later'
r = random.randint(1, 5)
fortune = getAnswer(r)
print(fortune)
The None Value
• In Python, the value None represents the absence of a value.
• None is the only value of the NoneType data type
• None must be typed with a capital N.

Example:
>>> spam = print('Hello!')
Hello!

>>> None == spam Python adds return None to the end of any
True function definition with no return
statement.
>>> type(None)
<class 'NoneType'>
Keyword Arguments and print()
• Keyword arguments are identified by the keyword put before them in the
function call.
• Keyword arguments are often used for optional parameters.

Example-1: Example-2:

print('Hello', end='') >>> print('cats', 'dogs', 'mice')


print('World') cats dogs mice

The output >>> print('cats', 'dogs', 'mice', sep=',')


HelloWorld cats,dogs,mice
Local and Global Scope
• Parameters and variables that are assigned in a called function are said to
exist in that function’s local scope.
• Variables that are assigned outside all functions are said to exist in the global
scope.
• A variable that exists in a local scope is called a local variable.
• A variable that exists in the global scope is called a global variable.
• A variable must be one or the other; it cannot be both local and global.
Local and Global Scope
• When a scope is destroyed, all the values stored in the scope’s variables are
forgotten.

• There is only one global scope, and it is created when your program begins.
When your program terminates, the global scope is destroyed, and all its
variables are forgotten.

• A local scope is created whenever a function is called. Any variables assigned


in this function exist within the local scope. When the function returns, the
local scope is destroyed, and these variables are forgotten.
Local and Global Scope
Scopes matter for several reasons:

• Code in the global scope cannot use any local variables.


• However, a local scope can access global variables.

• Code in a function’s local scope cannot use variables in any other local scope.

• You can use the same name for different variables if they are in different
scopes. That is, there can be a local variable named spam and a global variable
also named spam.
Local Variables Cannot Be Used in the Global Scope
Example:
def spam():
eggs = 31337
spam()
print(eggs)

Traceback (most recent call last):


File "C:/test3784.py", line 4, in <module>
print(eggs)
NameError: name 'eggs' is not defined
Local Scopes Cannot Use Variables in Other Local Scopes
• local variables in one function are completely separate from the local
variables in another function.
Example:
def spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
Global Variables Can Be Read from a Local Scope
Example:
def spam():
print(eggs)

eggs = 42
spam()
print(eggs)
Local and Global Variables with the Same Name
def spam(): Output:
eggs = 'spam local'
print(eggs) # prints 'spam local'
bacon local
def bacon():
spam local
eggs = 'bacon local'
print(eggs) # prints 'bacon local' bacon local
spam() global
print(eggs) # prints 'bacon local'

eggs = 'global'
bacon()
print(eggs) # prints 'global'
The global Statement
• If you need to modify a global variable from within a function, use the
global statement.

def spam():
global eggs
eggs = 'spam'

eggs = 'global'
spam()
print(eggs)

When you run this program, the final print() call will output this:
spam
The global Statement
• 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
functions), then it is always a global variable.
2. If there is a global statement for that variable in a function, it is a global
variable.
3. Otherwise, if the variable is used in an assignment statement in the
function, it is a local variable.
4. But if the variable is not used in an assignment statement, it is a global
variable.
The global Statement
Example program
def spam():
global eggs
eggs = 'spam' # this is the global
def bacon():
eggs = 'bacon' # this is a local
def ham():
print(eggs) # this is the global

eggs = 42 # this is the global


spam()
print(eggs)
If we run the code, output will look like this:
spam
The global Statement
• In a function, a variable will either always be global or always be local.
There’s no way that the code in a function can use a local variable named
eggs and then later in that same function use the global eggs variable.

Note:
If you ever want to modify the value stored in a global variable from in a
function, you must use a global statement on that variable.
Exception Handling
• Errors detected during execution are called exceptions ( errors occur at runtime)
• Getting an error, or exception, in your Python program means the entire program will
crash. Instead, the program should detect errors, handle them, and then continue to
run.
Output:
Example:
21.0
def spam(divideBy): 3.5
return 42 / divideBy Traceback (most recent call last):
File "F:/python programs/except1.py", line 6, in <module>
print(spam(2)) print(spam(0))
print(spam(12)) File "F:/python programs/except1.py", line 2, in spam
print(spam(0)) return 42 / divideBy
print(spam(1)) ZeroDivisionError: division by zero
A ZeroDivisionError happens whenever you try to divide a number by zero.
Examples
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined

>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
Try clause
• We can handle exceptions in our program by using try block and except block.
• A critical operation which can raise exception is placed inside the try block and
the code that handles exception is written in except block.
• The syntax for try–except block
Try clause
Example: Output:
def spam(divideBy):
try: 21.0
return 42 / divideBy 3.5
except ZeroDivisionError: Error: Invalid argument.
print('Error: Invalid argument.')
None
print(spam(2)) 42.0
print(spam(12))
print(spam(0))
print(spam(1))
A Short Program: Guess the Number
Write a Python program so that when its executed, the output will look
something like this:
I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!
A Short Program: Guess the Number
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
for guessesTaken in range(1, 7): # Ask the player to guess 6 times.
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
Output
I am thinking of a number between 1 and 20.
Take a guess.
10
Your guess is too low.
Take a guess.
15
Your guess is too low.
Take a guess.
17
Your guess is too high.
Take a guess.
16
Good job! You guessed my number in 4 guesses!
Practice Questions
• What three functions can be used to get the integer, floating-point number,
or string version of a value?
• What is the difference between break and continue? Explain with example.
• How many global scopes are there in a Python program? How many local
scopes? Explain the local scope and global scope with an example.
• When does the code in a function execute: when the function is defined or
when the function is called?
END

You might also like