
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialUse of Python interpreter’s interactive mode and script mode has been explained in earlier chapter of this tutorial series (Python Getting started). So far we learned about Python data types mainly using interactive mode. From here on scripted mode will be used most of the time.
Interactive mode is a good way to try out the language syntax get comfortable with Python. However, interactive mode is not suitable when it comes to automate certain process. Instead of writing and executing one statement at a time from Python prompt, it is better to store all statements in a text file with .py extension. This script is normally called as Python program. Instructions stored in a text file and executed at once by interpreter from command line as follows:
First enter following code and save as test.py and is called Python script.
price=50
quantity=5
amount=price*quantity
print ("price : {} quantity : {} amount : {}".format(price, quantity, amount))
Then execute it from command line. Shown below are windows and Linux command line examples to execute test.py
C:\python36>python test.py
price : 50 quantity : 5 amount : 250
$python test.py
price : 50 quantity : 5 amount : 250
In computer science, program is a sequence of instructions submitted to computer processor. When the instructions are executed in the defined sequence, processor will accomplish a certain task, or solve given problem.
To make computer processor solve a problem, its algorithm should first be planned and then it is translated into a sequence of instructions which when executed by computer processor, the desired task will be accomplished.
Python provides a predefined set of keywords using which the algorithm is coded. This code is what we call a program. Python’s interpreter software translates the code in processor readable format so that it can be executed to perform desired task.
Writing a script of statements provides following advantages
Python script can be converted in self executable. In Linux, use chmod command to do so. For Windows py2exe utility converts script with .py extension to executable.
An expression that evaluates to Boolean values either True or False if it contains comparison operators. (explained in previous chapter Python Operators). Python keywords And, Or and Not combine two Boolean expressions. Assuming x=True and y=False, their result is as shown in following table:
And | True if both are true | x and y returns True |
Or | True if at least one is true | x or y returns true |
Not | True only if false | not x returns False |
Comparison operators along with above keywords are useful in controlling flow of program.
By default, statements in script are executed sequentially from first to last. If the processing logic requires, sequential flow can be altered in two ways.
Conditional execution: block of one or more statements will be executed if a certain expression is true.
Repetitive execution: Block of one or more statements is repetitively executed till a certain expression remains true.
In this chapter we shall discuss decision control statements in Python.
A simple sequential process follows input-process-output path. A program involving one or more inputs to compute an unknown result is an example of such a sequential process. However, real life computer applications require that computer takes appropriate decisions depending on varying situations. Following flowchart describes how block of one or more statements is executed conditionally.

Python uses if keyword to implement decision control. Python’s syntax for executing block conditionally is as below:
if expr==True:
stmt1
stmt2
Any Boolean expression evaluating to True or False appears after if keyword. Use : symbol and press Enter after the expression to start a block with increased indent. One or more statements written with same level of indent will be executed if the Boolean expression evaluates to True. To end the block, press backspace to de-dent. Subsequent statements after the block will be executed if expression is false or after the block if expression is true.
Let us write a Python program that calculates amount payable from price and quantity input by user and applies 10% discount if the amount exceeds 1000, and no discount otherwise.
Discounts needs to applied only if amount is greater than 1000, hence the process is put in a block with increased indent following the conditional expression.
The print() statement is written after conditional block is over, hence it will be executed if expression is false (i.e. amount not greater than 1000) as well as after applying discount if expression is true (i.e. amount is greater than 1000)
price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>1000:
print ("10% discount applicable")
discount=amt*10/100
amt=amt-discount
print ("amount payable:",amt)
Save above script as discount.py and run it from command line as:
python discount.py
Two scenarios of running the code are shown below. In first, inputs for price and quantity are such that amount is greater than 1000. Payable amount after applying discount will be displayed.
enter price100
enter quantity20
10% discount applicable
amount payable: 1800.0
In second case, inputs are such that the expression doesn’t become true. Hence, print statement will display payable amount which will not have discount.
enter price10
enter quantity20
amount payable: 200
Along with if statement, else clause can also be optionally used to define alternate block of statements to be executed if the Boolean expression (in if statement) is not true. Following flowchart shows how else block is used.

This is how else block is used in Python:
if expr==True:
stmt1
else:
stmt2
stmt3
As earlier, indented block started by : symbol after Boolean expression in front of if keyword gets executed when it is true. We have another block that should be executed when the expression is false. First, complete the if block by backspace and write else, put : symbol in front of it to start another block and put required statements in it. De-dent the else block and enter statements that should be executed irrespective of the Boolean expression being true or false.
Let us extend earlier code for applying discount and provide for computation of 5% discount if amount is not greater than 1000. To do that, use else and : after first block. New indented block will start. Enter two statements to apply 5% discount and subtracting it from amount in it. Statement to print payable amount should be executed in both cases. So, de-dent second block and enter it.
price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>1000:
print ("10% discount applicable")
discount=amt*10/100
amt=amt-discount
else:
print ("5% discount applicable")
discount=amt*5/100
amt=amt-discount
print ("amount payable:",amt)
Let us run this code to test first possibility, price and quantity having inputs such that amount greater than 1000. We should see 10% discount being applied
enter price200
enter quantity10
10% discount applicable
amount payable: 1800.0
In second run, inputs are such that amount is not greater than 1000. We see 5% discount deducted from amount.
enter price150
enter quantity6
5% discount applicable
amount payable: 855.0
Let us modify the discount example further. Discounts applicable are 10%, 5%, 2% and 1% for amount exceeding 10000, between 5,000 to 10,000, between 2,000 and 5000 and between 1000 and 2000 respectively. No discount is applicable for amount less than 2000.
Following code implements above graded computation of discount, setting aside one possibility at a time by successive if statements.
price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>10000:
print ("10% discount applicable")
discount=amt*10/100
amt=amt-discount
else:
if amt>5000:
print ("5% discount applicable")
discount=amt*5/100
amt=amt-discount
else:
if amt>2000:
print ("2% discount applicable")
discount=amt*2/100
amt=amt-discount
else:
if amt>1000:
print ("1% discount applicable")
discount=amt/100
amt=amt-discount
else:
print ("no discount applicable")
print ("amount payable:",amt)
If above code is executed to test all discount scenarios, following output will be displayed
enter price1000
enter quantity11
10% discount applicable
amount payable: 9900.0
========================
enter price1000
enter quantity6
5% discount applicable
amount payable: 5700.0
========================
enter price1000
enter quantity4
2% discount applicable
amount payable: 3920.0
========================
enter price500
enter quantity3
1% discount applicable
amount payable: 1485.0
========================
enter price250
enter quantity3
no discount applicable
amount payable: 750
In above program indent level of each block increases because if block starts after empty else. More elegant way to avoid these indentations is to combine empty else and subsequent if by elif keyword.
General syntax of if – elif – else usage is as below:
if expr1==True:
#Block To Be Executed If expr1 is True
elif expr2==True:
#Block To Be Executed If expr1 is false and expr2 is true
elif expr3==True:
#Block To Be Executed If expr2 is false and expr3 is true
elif expr4==True:
#Block To Be Executed If expr3 is false and expr4 is true
else:
#Block To Be Executed If all preceding expressions false
In this code, one if block, followed by one or more elif blocks and one else block at the end will appear. Boolean expression in front of elif is evaluated if previous expression fails. Last else block is run only when all previous expressions turn out to be not true. Importantly all blocks have same level of indentation.
price=int(input("enter price"))
qty=int(input("enter quantity"))
amt=price*qty
if amt>10000:
print ("10% discount applicable")
discount=amt*10/100
amt=amt-discount
elif amt>5000:
print ("5% discount applicable")
discount=amt*5/100
amt=amt-discount
elif amt>2000:
print ("2% discount applicable")
discount=amt*2/100
amt=amt-discount
elif amt>1000:
print ("1% discount applicable")
discount=amt/100
amt=amt-discount
else:
print ("no discount applicable")
print ("amount payable:",amt)
Identical output will be shown when above code is run to test different discount scenarios.