OKPEDIA PYTHON EN

How to use if else in python

To insert a condition into a python program, use if else statement

if (condition):
statement 1
else:
statement 2

Statements 1 and 2 must start from a position further to the right of the if-else statement (indentation).

They can also be blocks with several sequential instructions.

How if else works

  • If the condition is true, the program executes instruction 1.
  • If the condition is not true, it is false, the program executes statement 2.

The else clause is optional. If the else clause is missing, the program executes statement 1 only if the condition is true. Otherwise, it exits the conditional statement and continues program execution.

Examples

Example 1

If the variable age is greater than equal to zero

if (age>=18):
price=20

the program assigns the value 20 to the variable price.

Example 2

If the variable age is greater than zero, the program assigns 20 to the variable price.

if (age>=18):
price=20
else:
price=10

Otherwise, the program assigns 15 to the variable price.

https://how.okpedia.org/en/python/how-to-use-if-else-in-python


Report an error or share a suggestion to enhance this page



FacebookTwitterLinkedinLinkedin