Tutorialslot.com

youtube facebook twitter gmail pinterest

If Statement in Python

->if
->if else

If statement:
For taking any decision "if" statement helps to check the conditions of the program and changes the behaviour of the given program. If the given condition is true then it will be exectuted otherwise the program moves to the next statement.Python do not have any braces{} in the flow of program.

Syntax:
if CONDITION:
  STATEMENTS

Example:
food = 'spam'

if food == 'spam':
  print('Ummmm, my favorite!')
  print('I feel like saying it 100 times...')
  print(100 * (food + '! '))


If else statement:
If the condition given in "if" part is true then it will be executed otherwise the statements in "else" part will be executed.

Syntax:
if CONDITION:
  STATEMENTS_1   # executed if condition evaluates to True
else:
  STATEMENTS_2   # executed if condition evaluates to False

Example:
n=9
if n>5:
  print ("Answer")
  print ("True")
else:
  print "(Answer")
 print ("False")

Chained conditionals:
When situation occurs to take many decisions or many possibilities then it can be handled with the help of chained conditionals.

Syntax:
if CONDITION_1:
  STATEMENT_1
elif CONDITION_2:
  STATEMENT_2
else:
  STATEMENT_3

Example:
x = int(input("Please enter integer value : "))
if x < 0:
  print('Given Integer Is Negative Number')
elif x == 0:
  print('Given Integer Is Zero')
elif x == 1:
  print('Given Integer Is One')
else:
 print('Given Integer Is Postive Number')

Output:
Please enter integer value : 42
Given Integer Is Postive Number

There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.

Nested statements:
If one condition is defined inside another conditional statement then they are called as nested conditionals.

Syntax:

if CONDITION_1:
  statement(s)
if CONDITION_2:
   statement(s)
elif CONDITION_3:
   statement(s)
else:
   statement(s)
elif CONDITION_4:
 statement(s)
else:
  statement(s)

Example:

var = 100
if var < 200:
  print "Expression value is less than 200"
 if var == 150:
   print "Which is 150"
  elif var == 100:
   print "Which is 100"
  elif var == 50:
   print "Which is 50"
elif var < 50:
  print "Expression value is less than 50"
else:
  print "Could not find true expression"
print "Good bye!"
Output:
Expression value is less than 200
Which is 100
Good bye!



Advertisement Powered By Google Adsense






IF YOU LIKE THIS TUTORIALS PLEASE SHARE

Share on whatsapp

POPULAR TAGS

python python tutorial learn python learning python python code learning java python language python documentation python tutor python basics python download python online python for dummies how to learn python