Course
If Statement
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
If Statement
Python
if
statement is similar to that of other languages. The if
statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison.Syntax
if expression: statement(s)
If the boolean expression evaluates to
TRUE
, then the block of statement(s) inside the if statement is executed. If boolean expression evaluates to FALSE
, then the first set of code after the end of the if statement(s) is executed.Flow Diagram
Example
Let us consider an example of a customer entitiled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following flowchart shows the whole decision making process.
In Python, we first set a discount variable to 0 and accept the amount as input from user.
Then comes the conditional statement if amount > 1000. Put : symbol that starts conditional block wherein discount applicable is calculated. Obviously, discount or not, next statement by default prints amount-discount. If applied, it will be subtracted, if not it is 0.
discount = 0amount = 1200
# Check he amount valueif amount > 1000: discount = amount * 10 / 100
print("amount = ", amount - discount)
Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output
amount = 1080.0
Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output
amount = 800
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.