• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Python AssertionError Exception and Assert Message | Example

Aniruddha Chaudhari/12729/0
CodePython

Have you heard about ‘assert’ in Python? Or you may have got ‘AssertionError’ while executing any project code.

In this Python tutorial, you will learn Python assert a statement with examples and how to use it in your code. You will also learn to write Python assert message and unit test cases using it.

Let’s start with the basic first.

Python interview questions and answers

Table of Contents

  • What is Assert Statement in Python?
  • Python Assert Statement Example
  • Python Assert Message for Exception
  • How to disable Assert Statement Globally?
  • Use of Assert to Write Unit Test Cases in Python

What is Assert Statement in Python?

The assert statement is used in Python to verify the condition.

  • If the condition is False, it terminates the program by throwing an exception.
  • If the condition is True, it does not make any changes to the execution of your program.

It has a very simple syntax.

assert <condition>

You can use any condition statement which returns either True or False.

Condition in the Python code is executed first. Based on the result of condition, assert statement either don’t make any changes (just like nothing happened) or terminates the program.

Python Assert Statement Example

Let’s understand this concept with simple examples…

When the condition is True…

>>> assert True
>>>
>>>

If you run above the line of code on your Python console, nothing happens as the condition is True.

When the condition is False…

>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>>

Try running the above statement on your Python console. For any False condition, it throws an AseertionError error.

You can capture AssertionError error as a part of exception handling in Python.

Python Assert Message for Exception

To distinguish multiple assert failure messages, you can also customize the message.

Customizing the message to display for the False condition:

>>> assert False, "Assertion failed!"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Assertion failed!
>>>

Many times this assert statement is very useful when you don’t want to execute your program for invalid conditions or parameter values.

Another Example:

Let’s take a real and practical programming example. You are asking the users to enter their birthday month, so the accepted values are 1 to 12.

Here you don’t want your program to continue running for an invalid (erroneous) month.

When the user provides a valid month number:

>>> month=int(input('birthday month: '))
birthday month: 11
>>> assert month in range(1,13)
>>>

When the user provides an invalid month number:

>>> month=int(input('birthday month: '))
birthday month: 14
>>> assert month in range(1,13)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>>

In the above code, we have used:

  • taking user input from the keyboard
  • range() function in Python

You can also disable assert statement globally.

How to disable Assert Statement Globally?

Assert statements can be used for debugging code and for the unit testing.

If your script already have assert statement and you don’t want to execute it, you can use -O command-line switch while starting Python.

Use the following command to open Python console.

python -O

This will disable the debugging mode of the Python.

Now, even if you provide False condition to the assert, it will not throw an error.

>python -O
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59)
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> assert False
>>>
>>>

This way it will disable assert statements globally.

Use of Assert to Write Unit Test Cases in Python

The keyword assert is used for writing the unit test cases. When you call the actual function from the test case, it returns certain values.

To test if the actual function is working as expected, we usually compare the return value with the expected value.

Something like this…

assert <return_value_of_function> == <expected_return_value>

If the return value of the function does not match with the expected return value, the test case throws an exception. This means the test case has failed.

If the return value of the function is the same as the expected value, the test case passes without throwing any exception.

One test case can have multiple assert statements.

Great! With this Python assert tutorial, you have learned some of the interesting concepts in Python. If you have any doubts about Python AssertionError and Python assert message, let’s discuss in the comment section below

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard