Python if Statement

Advertisements
Advertisements

In python programming, you can run a specific block of code with the help of conditions. Usually, these types of block start with if statement.

The if statement in python can change the direction of the program with these conditions. Suppose condition is true, then block \hspace{3px}A will be executed and if condition is false, then nothing happens. The program continues with the rest of the statements. See the figure below

Python If Block
Python If Block

In the figure above, if the condition x > 10 is true, the python executes the block \hspace{3px} A statements. If the condition is false, nothing happens.

Example – if block

In this example, we will check if a customer has enough cash to buy a product whose price and tax if given. If the customer has enough cash, then he can buy the product, otherwise, purchase cannot be made.

# Customer declare the amount of cash
cash_available = 5000
# Price of the item is 3000 and tax amount is 100.
price = 3000
tax = 100
# Now we check if cash is less than total of price and tax, so that we can # decide the purchase
if cash <= price + tax:
    total_amount = price + tax
    print("Purchase Successful", total_amount)
print("Transaction Completed")

In the program above, observe how if statement ends with a semi-colon. Also, watch each line start with an indentation and not with a curly \hspace{3px} brace. The semi-colon is a way to tell the program that a new block is starting after the if statement. Statements inside a single block must have the same indentation rules.

Advertisements

Output – if Block

The output of the above program is as follows.

Purchase Successful 3100
Transaction Completed

Bestseller

Python Programming: Using Problem Solving Approach

Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.

Advertisements
Advertisements
Advertisements