Python Conditional Statements

Python Conditional Statements

  • Conditional statements are used to execute code on based of some condition.
  • It is used for flow control of our code according to some condition.
  • It helps in decision making.

In Python programming any non-zero or non-null value is considered as TRUE vice-versa.

Note: Before reading this, read about Python Relational Operator here.

Python have following different types of conditional statements:

  • If Statement
  • If-else Statement
  • Nested if-else

If Statement

If statement will allow inner statement to be executed only when the condition will be true. If condition is False then it will not execute the statement.

Syntax:

if (Condition)

Statement(s)

[pastacode lang=”python” manual=”i%20%3D%2020%0A%0Aif%20i%20%25%202%20%3D%3D%200%3A%0A%C2%A0%20%C2%A0print(%22Number%20is%20even%22)%0Aelse%3A%0A%C2%A0%20%C2%A0print(%22Number%20is%20odd%22)” message=”” highlight=”” provider=”manual”/]

If-else Statement

The case that you want one thing to happen when a condition it true, and something else to happen when it is false. For that we have the if elsestatement.

[pastacode lang=”python” manual=”today%20%3D%20%22monday%22%0A%0Aif%20today%20%3D%3D%20%22monday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20monday%22)%0Aelif%20today%20%3D%3D%20%22tuesday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20tuesday%22)%0Aelif%20today%20%3D%3D%20%22wednesday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20wednesday%22)%0Aelif%20today%20%3D%3D%20%22thursday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20thursday%22)%0Aelif%20today%20%3D%3D%20%22friday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20friday%22)%0Aelif%20today%20%3D%3D%20%22saturday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20saturday%22)%0Aelif%20today%20%3D%3D%20%22sunday%22%3A%0A%C2%A0%20%C2%A0print(%22this%20is%20sunday%22)%0Aelse%3A%0A%C2%A0%20%C2%A0print(%22something%20else%22)” message=”” highlight=”” provider=”manual”/]

Nested if-else

It is used when you need condition inside a condition, you can use nested if-else.

[pastacode lang=”python” manual=”num%20%3D%20float(input(%22Enter%20a%20number%3A%20%22))%0Aif%20num%20%3E%3D%200%3A%0A%20%20%20%20if%20num%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20print(%22Zero%22)%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print(%22Positive%20number%22)%0Aelse%3A%0A%20%20%20%20print(%22Negative%20number%22)” message=”” highlight=”” provider=”manual”/]

 

Leave a Reply