Sunday, January 2, 2022

How to check a condition with Assert statement in a Python Program

The Assert statement to check whether a condition is true or not in Python Program
Assert:
The 'assert' statement in Python is used to check whether a specified condition is fulfilled or not.
If the condition is False, it will throw an Assertion Error.
Syntax:
assert condition, error message

Example1:
x = int(input('Please enter a number>0: '))
assert x > 0, "Try again! Invalid Input"
print('The number you entered is: ', x)

In the above example, the Python interpreter checks if x>0 is True or not. If it is True, then the next statements will execute, else it will display the AssertionError along with the message we mentioned "Try again! Invalid Input".
# ------------------------------------------------------------------------------------------------------------------------ #
Input : when you entered 0 or -number as input, the output is as follows.
Output:
Traceback (most recent call last):
  File "C:\Userstpreddy\PycharmProjects\pythonProject\PyLab1\Temp1.py", line 6, in <module>
    assert x > 0, "Try again! Invalid Input"
AssertionError: Try again! Invalid Input
# ------------------------------------------------------------------------------------------------------------------------ #
The AssertionError shown in the above output is called an exception. An exception is an error that occurs during the runtime.
To avoid such type of exceptions, we can handle exceptions using the 'try...except' statement.
In the except block, we can write the statements that are executed in case of exception, as shown in the below example:

Example2:
x = int(input('Please enter a number>0: '))
try:
    assert x > 0
    NumValid = True
    print('The number you entered is: ', x)
except AssertionError:
    print("Try again! Invalid Input\n")

# ------------------------------------------------------------------------------------------------------------------------ #
Input : 
Plese enter a number >0: -5

Output:
Traceback (most recent call last):
  File "C:\Users\tpreddy\PycharmProjects\pythonProject\PyLab1\Temp1.py", line 6, in <module>
    assert x > 0, "Try again! Invalid Input"
AssertionError: Try again! Invalid Input

Process finished with exit code 1
# ------------------------------------------------------------------------------------------------------------------------ #

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog