
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 TutorialMost of the times, Python program encounters error because of violation of syntax in language keywords. Python interpreter immediately reports it usually along with the reason.
>>> print "hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?
In Python 3.x, print is a built-in function and requires parentheses. The statement violates this usage and hence syntax error is displayed.
Shown below is a definition of myfunction. First two statements inside the function are syntactically correct but the interpreter still flashes syntax error message immediately on encountering incorrect statement, without executing earlier correct statements. Enter following code as test.py and try to run it from command line.
def myfunction():
print ("hello")
x=10
y=2x
myfunction()
C:\python37>python test.py
File "test.py", line 4
y=2x
^
SyntaxError: invalid syntax
Many a times though, program results in an error after it is run even if it doesn’t have any syntax error. Such an error is a runtime error called as exception. Python has a Exception class and a number of built-in exceptions are defined in Python library. Look at following snippets:
It is shown when trying to access item at invalid index.
>>> numbers=[10,20,30,40]
>>> for n in range(5):
print (numbers[n])
10
20
30
40
Traceback (most recent call last):
File "<pyshell#2>", line 2, in <module>
print (numbers[n])
IndexError: list index out of range
This is displayed when module could not be found.
>>> import notamodule
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
import notamodule
ModuleNotFoundError: No module named 'notamodule'
It occurs as dictionary key is not found.
>>> D1={'1':"aa", '2':"bb", '3':"cc"}
>>> D1['4']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
D1['4']
KeyError: '4'
It is shown when specified function is not available for import.
>>> from math import cube
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
from math import cube
ImportError: cannot import name 'cube'
This error appears when next() function is called after iterator stream exhausts.
>>> it=iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
next(it)
StopIteration
This is shown when operator or function is applied to an object of inappropriate type.
>>> '2'+2
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
'2'+2
TypeError: must be str, not int
It is displayed when function’s argument is of inappropriate type.
>>> int('xyz')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
int('xyz')
ValueError: invalid literal for int() with base 10: 'xyz'
This is encountered when object could not be found.
>>> age
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
age
NameError: name 'age' is not defined
It is shown when second operator in division is zero.
>>> x=100/0
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
x=100/0
ZeroDivisionError: division by zero
When user hits the interrupt key normally Control-C during execution of program.
>>> name=input('enter your name')
enter your name^c
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
name=input('enter your name')
KeyboardInterrupt
As the word 'exception' suggests, exception in code doesn't occur because of syntax error due to rare and exceptional situations it encounters during execution. More often than not the factors external to the program cause the exception. For example, incorrect input or malfunction IO device etc. Exception results in abrupt termination of program. It may damage system resources such as files becoming inaccessible etc. Hence the exceptions should be properly handled so as to prevent abrupt termination of program.
Two keywords - try and except - perform exception handling.
The try: block contains statements which are susceptible for exception. In other words, you want interpreter to check whether it encounters exception in this block. If block is executed without exception, the except: block (which must appear immediately after try block) is skipped.
If there occurs some exception, remaining statements in try block are abandoned and program jumps to except: block. Purpose of except: block is to take appropriate action regarding the cause of exception appropriately. For example printing appropriate error message, closing files if any are opened before exception etc.
You can mention any type of built-in exception in front of except keyword. Subsequent block will be executed only if specified exception occurs.
Statements after except block will be executed, irrespective of exception encountered or not.
Following code has a dictionary containing name as key and marks as value. User is asked to input name and corresponding marks are displayed. If name input by user is not present, KeyError will occur which is handled by except clause as shown:
marks={'Meena':50, 'Tina':60,'Leena':70}
name=input("enter name:")
try:
print ('marks:',marks[name])
except KeyError:
print ('name {} not in the list'.format(name))
print ("end of program")
Two run cases of above program are shown below. One with input name in the list, and other not in the list.
Output:
enter name:Meena
marks: 50
end of program
enter name:Beena
name Beena not in the list
end of program
Also there may be multiple except blocks for different exceptions for a single try block. Of course, if type of exception doesn’t match with any of except blocks, it will remain unhandled and program will terminate. Following example uses two except blocks to process two different exception types:
a=[10,20,30,40,50]
try:
x=int(input('enter index: '))
print ('number at index {} is {}'.format(x,a[x]))
except IndexError:
print ("index is out of range")
except ValueError:
print ("index should be an integer")
Output:
enter index: 4
number at index 4 is 50
enter index: 7
index is out of range
enter index: aa
index should be an integer
In Python, else and finally keywords can also be used along with try and except clauses. While the except block is executed if exception occurs inside try block, the else block gets processed if try block is found to be free from exception.
try:
#statements in try block
except :
#executed when exception in try block
else:
#executed if try block has no exception
The finally block will be processed regardless of exception occurs in try block or not. When there is no exception in try block, except clause is skipped and program control enters else block and goes on to execute statements in finally block. If however, there’s an exception in try block, the corresponding except block will be processed, then statements in finally block will be processed.
The example below demonstrates uses else and finally blocks. Variable x is initialized before try block. Inside try block, an input statement tries to change its value. If however, you try to input a non-numeric value, ValueError is raised. Program goes on to enter finally block and reset x to 0.
On the other hand, valid value entered will update x. The else block prints it, and then finally block resets it to 0.
x=0
try:
x=int(input("enter number: "))
except ValueError:
print("ValueError raised")
else:
print(x)
finally:
x=0
print ("reset x to ",x )
Output:
enter number: 11
11
reset x to 0
enter number: aa
ValueError raised
reset x to 0
The finally block is typically employed to perform some kind of cleaning up operations in a process. For example you must close a file irrespective of errors in read/write operations.
Python's built-in errors are raised implicitly. The raise keyword is used to be generate exception explicitly.
Following code accepts a number from user. The try block raises an exception if the number is outside the allowed range.
try:
x=int(input('enter a number: '))
if x not in range(1,101):
raise Exception(x)
except:
print (x, "is out of allowed range")
else:
print (x, "is within the allowed range")
Output:
enter a number: 200
200 is out of allowed range
enter a number: 50
50 is within the allowed range
Here, Exception is not of any built-in type hence Except clause doesn't have any object .
The assert keyword checks whether given expression is true or false. Program execution terminates if it is false by raising AssertionError and proceeds only if the expression is true. Following code shows usage of assert statement
num=int(input('enter marks [out of 100] : '))
assert num>=0 and num<=100
print ('marks obtained: ', num)
The print statement will display only if entered number is between 0 and 100 (both included). Any other number results in aborting the program after showing AssertionError.
enter marks [out of 100] : 75
marks obtained: 75
enter marks [out of 100] : 125
Traceback (most recent call last):
File "C:\python36\assert.py", line 2, in <module>
assert num>=0 and num<=100
AssertionError
To display custom error message, put a string after the expression in assert statement as follows:
num=int(input('enter marks [out of 100] : '))
assert num>=0 and num<=100, "only numbers in 0-100 accepted"
print ('marks obtained: ', num)
Output:
enter marks [out of 100] : 125
Traceback (most recent call last):
File "C:\python36\assert.py", line 2, in <module>
assert num>=0 and num<=100, "only numbers in 0-100 accepted"
AssertionError: only numbers in 0-100 accepted
The AssertionError is also a built-in exception. So it can be used as argument in except block. When input causes AssertionError exception, it will be handled by except block. The except block treats string in assert statement goes as exception object.