Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
as Keyword - Python
Next article icon

Python assert keyword

Last Updated : 05 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn’t allow the code to execute further. 

Assert Keyword in Python

In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution, but if the statement is False then it stops the execution of the program and throws an error.

Flowchart of Python Assert Statement

assert in Python

Flowchart of Python Assert Statement

Python assert keyword Syntax

In Python, the assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided. 

Syntax : assert condition, error_message(optional) 

Parameters:

  • condition : The boolean condition returning true or false. 
  • error_message : The optional argument to be printed in console in case of AssertionError

Returns: Returns AssertionError, in case the condition evaluates to false along with the error message which when provided. 

Python assert keyword without error message

This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError.
Since an exception is raised by the failed assert statement, the program terminates and does not continue to execute the print statement on the next line.

Python3




# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0
print(a / b)
 
 

Output:

The value of a / b is :  --------------------------------------------------------------------------- AssertionError                            Traceback (most recent call last) Input In [19], in <cell line: 10>()       8 # using assert to check for 0       9 print("The value of a / b is : ") ---> 10 assert b != 0      11 print(a / b)  AssertionError: 

Python assert keyword with an error message

This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError with the message “Zero Division Error”.
Since an exception is raised by the failed assert statement, the program terminates and does not continue to execute the print statement on the next line.

Python3




# Python 3 code to demonstrate
# working of assert
 
# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)
 
 

Output:

AssertionError: Zero Division Error

Assert Inside a Function

The assert statement is used inside a function in this example to verify that a rectangle’s length and width are positive before computing its area. The assertion raises an AssertionError with the message “Length and width must be positive” if it is false. If the assertion is true, the function returns the rectangle’s area; if it is false, it exits with an error. To show how to utilize assert in various situations, the function is called twice, once with positive inputs and once with negative inputs.

Python3




# Function to calculate the area of a rectangle
def calculate_rectangle_area(length, width):
    # Assertion to check that the length and width are positive
    assert length > 0 and width > 0, "Length and width"+ \
                "must be positive"
    # Calculation of the area
    area = length * width
    # Return statement
    return area
 
 
# Calling the function with positive inputs
area1 = calculate_rectangle_area(5, 6)
print("Area of rectangle with length 5 and width 6 is", area1)
 
# Calling the function with negative inputs
area2 = calculate_rectangle_area(-5, 6)
print("Area of rectangle with length -5 and width 6 is", area2)
 
 

Output:

AssertionError: Length and widthmust be positive

Assert with boolean Condition

In this example, the assert statement checks whether the boolean condition x < y is true. If the assertion fails, it raises an AssertionError. If the assertion passes, the program continues and prints the values of x and y.

Python3




# Initializing variables
x = 10
y = 20
 
# Asserting a boolean condition
assert x < y
 
# Printing the values of x and y
print("x =", x)
print("y =", y)
 
 

Output:

x = 10 y = 20

Assert Type of Variable in Python

In this example, the assert statements check whether the types of the variables a and b are str and int, respectively. If any of the assertions fail, it raises an AssertionError. If both assertions pass, the program continues and prints the values of a and b.

Python3




# Initializing variables
a = "hello"
b = 42
 
# Asserting the type of a variable
assert type(a) == str
assert type(b) == int
 
# Printing the values of a and b
print("a =", a)
print("b =", b)
 
 

Output:

a = hello b = 42

Asserting dictionary values

In this example, the assert statements check whether the values associated with the keys “apple”, “banana”, and “cherry” in the dictionary my_dict are 1, 2, and 3, respectively. If any of the assertions fail, it raises an AssertionError. If all assertions pass, the program continues and prints the contents of the dictionary.

Python3




# Initializing a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
 
# Asserting the contents of the dictionary
assert my_dict["apple"] == 1
assert my_dict["banana"] == 2
assert my_dict["cherry"] == 3
 
# Printing the dictionary
print("My dictionary contains the following key-value pairs:", my_dict)
 
 

Output:

My dictionary contains the following key-value pairs:  {'apple': 1, 'banana': 2, 'cherry': 3}

Practical Application

This has a much greater utility in the Testing and Quality Assurance roles in any development domain. Different types of assertions are used depending on the application. Below is a simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch.

Python3




# Python 3 code to demonstrate
# working of assert
# Application
 
# initializing list of foods temperatures
batch = [ 40, 26, 39, 30, 25, 21]
 
# initializing cut temperature
cut = 26
 
# using assert to check for temperature greater than cut
for i in batch:
    assert i >= 26, "Batch is Rejected"
    print (str(i) + " is O.K" )
 
 

Output:

40 is O.K 26 is O.K 39 is O.K 30 is O.K

Runtime Exception:

AssertionError: Batch is Rejected

Why Use Python Assert Statement?

In Python, the assert statement is a potent debugging tool that can assist in identifying mistakes and ensuring that your code is operating as intended. Here are several justifications for using assert:

  1. Debugging: Assumptions made by your code can be verified with the assert statement. You may rapidly find mistakes and debug your program by placing assert statements throughout your code.
  2. Documentation: The use of assert statements in your code might act as documentation. Assert statements make it simpler for others to understand and work with your code since they explicitly describe the assumptions that your code is making.
  3. Testing: In order to ensure that certain requirements are met, assert statements are frequently used in unit testing. You can make sure that your code is working properly and that any changes you make don’t damage current functionality by incorporating assert statements in your tests.
  4. Security: You can use assert to check that program inputs comply with requirements and validate them. By doing so, security flaws like buffer overflows and SQL injection attacks may be avoided.


Next Article
as Keyword - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • python-basics
Practice Tags :
  • python

Similar Reads

  • as Keyword - Python
    as keyword in Python plays a important role in simplifying code, making it more readable and avoiding potential naming conflicts. It is mainly used to create aliases for modules, exceptions and file operations. This powerful feature reduces verbosity, helps in naming clarity and can be essential whe
    3 min read
  • python class keyword
    In python class keyword is used to create a class, which acts as a blueprint for creating objects. A class contains attributes and methods that define the characteristics of the objects created from it. This allows us to model real-world entities as objects with their own properties and behaviors. S
    1 min read
  • Python False Keyword
    False is a boolean value in Python that represents something untrue or a "no" condition. It is one of the two Boolean constants (True and False) and is mostly used in conditions, loops and logical operations. In Python, False is treated as 0 in mathematical operations and as a falsy value in conditi
    2 min read
  • Python def Keyword
    Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In Python def
    6 min read
  • Python del keyword
    The del keyword in Python is used to delete objects like variables, lists, dictionary entries, or slices of a list. Since everything in Python is an object, del helps remove references to these objects and can free up memory del Keyword removes the reference to an object. If that object has no other
    2 min read
  • Python And Keyword
    The and keyword in Python is a logical operator used to combine two conditions. It returns True if both conditions are true, otherwise, it returns False. It is commonly used in if statements, loops and Boolean expressions. Let's understand with a simple example. [GFGTABS] Python x = 10 y = 5 if x
    2 min read
  • Python in Keyword
    The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary. Example: [GFGTABS] Python s = "Geeks for geeks" if "for" in s: print(
    3 min read
  • Python Keywords
    Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. List of Keywords in PythonTrueFalseNoneandornotisifelseelifforwhilebreakconti
    12 min read
  • is keyword in Python
    In programming, a keyword is a “reserved word” by the language that conveys special meaning to the interpreter. It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. Python language also reserves some of the keywords that convey special meaning. In Py
    2 min read
  • Python True Keyword
    True is a built-in Boolean value that represents truth or logical true value. It is one of the two Boolean constants (True and False) and is often used in conditions, loops and logical operations. Python treats True as 1 when used in arithmetic operations and as a truthy value in conditional stateme
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences