Net-informations.com
SiteMap  | About    

Python Conditional Statements

Decision making is one of the most important concepts of computer programming . It require that the developer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Python programming language provides following types of decision making statements.

  1. if statements
  2. if....else statements
  3. if..elif..else statements
  4. nested if statements
  5. not operator in if statement
  6. and operator in if statement
  7. in operator in if statement

Python if statements

Python Decision Making

In Python, if statement evaluates the test expression inside parenthesis. If test expression is evaluated to true (nonzero) , statements inside the body of if is executed. If test expression is evaluated to false (0) , statements inside the body of if is skipped.

example

output

In this program we have two variables x and y. x is assigned as the value 20 and y is 10. In next line, the if statement evaluate the expression (x>y) is true or false. In this case the x > y is true because x=20 and y=10, then the control goes to the body of if block and print the message "X is bigger". If the condition is false then the control goes outside the if block.

Python if..else statements

The else statement is to specify a block of code to be executed, if the condition in the if statement is false. Thus, the else clause ensures that a sequence of statements is executed.

python if else statement

example

output

In the above code, the if stat evaluate the expression is true or false. In this case the x > y is false, then the control goes to the body of else block , so the program will execute the code inside else block.

if..elif..else statements

The elif is short for else if and is useful to avoid excessive indentation.

example

output

In the above case Python evaluates each expression one by one and if a true condition is found the statement(s) block under that expression will be executed. If no true condition is found the statement(s) block under else will be executed.

Nested if statements

In some situations you have to place an if statement inside another statement.

example

output

not operator in if statement

By using Not keyword we can change the meaning of the expressions, moreover we can invert an expression.

example

output

You can write same code using "!=" operator.

example

output

and operator in if statement

The equivalent of "& & " is "and" in Python.

example

output

in operator in if statement

example

output









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.