• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Assert Statement in Python

Assert Statement in Python

Author: Aditya Raj
Last Updated: December 10, 2021

Debugging is one of the important parts of a software developer’s journey. Python programming language also provides various constructs for debugging programs. One such construct is an assert statement. In this article, we will discuss what an assert statement is, how it works, and how we can use an assert statement in python.

What is an assert statement in Python?

In Python, Assert statement is a construct used to enforce some condition in the program. The syntax for the assert statement in python is as follows.

assert  condition, message
  • Here assert is a keyword.
  • condition contains the conditional statement that needs to be True. 
  • message is the statement that will be shown when the condition is False. It is optional to use the message in an assert statement.

How does an assert statement work?

An assert statement works by using the AssertionError exception. Whenever the condition given in the assert statement evaluates to True, the program works normally. 

name = "Bill"
age = 20
assert age >= 0
print("{} is {} years old.".format(name,age))

Output:

Bill is 20 years old.

On the contrary, If the condition in the assert statement evaluates to False, the AssertionError exception occurs and the program is terminated. 

name = "Bill"
age = -20
assert age >= 0
print("{} is {} years old.".format(name,age))

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
    assert age >= 0
AssertionError

If we pass a message in the assert statement, the message is also printed when AssertionError occurs.

name = "Bill"
age = -20
assert age >= 0, "Age cannot be negative."
print("{} is {} years old.".format(name,age))

Output:

Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
    assert age >= 0, "Age cannot be negative."
AssertionError: Age cannot be negative.

So, we can say that the assert statement does nothing when the condition in the assert statement is True. If the condition in the assert statement is False, the python interpreter raises the AssertionError with a proper message.

How to use an assert statement in python?

An assert statement should not be used in a python program to implement any business logic. The assert statement is only used to debug python programs. When your program is not producing the intended output, you can use assert statements to detect where an error occurred. 

For example, suppose that your program is running into an error because a variable like “age” has negative value, which is not a desired situation.

To detect where the error is happening, you can put an assert statement before each statement where you are using the “age” variable. In each assert statement, you can check if the value of “age” is greater than the zero or not. You can also add a message to identify the place at which the IndexError occurs as follows.

name = "Bill"
age = 10
assert age >= 0, "Age takes negative before first print statement."
print("{} is {} years old.".format(name, age))
name = "Sam"
age = -20
assert age >= 0, "Age takes negative before second print statement."
print("{} is {} years old.".format(name, age))

Output:

Bill is 10 years old.
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 7, in <module>
    assert age >= 0, "Age takes negative before second print statement."
AssertionError: Age takes negative before second print statement.

In the above example, the program terminates prematurely. To avoid this, you can use python try except block. Here, you can write your code in the try block and handle the AssertionError that is raised by the assert statement in the except block as follows. 

try:
    name = "Bill"
    age = 10
    assert age >= 0, "Age takes negative before first print statement."
    print("{} is {} years old.".format(name, age))
    name = "Sam"
    age = -20
    assert age >= 0, "Age takes negative before second print statement."
    print("{} is {} years old.".format(name, age))
except AssertionError as e:
    print(e.args)

Output:

Bill is 10 years old.
('Age takes negative before second print statement.',)

Conclusion

In this article, we have discussed the assert statement in python. We have also discussed how assert statements work and how we can use them in debugging our programs. To learn more about errors, you can read this article on exceptions in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us