Conditional
statements:
Before anything we have to know what is conditional statements.
Conditional statements are those statements that need
condition to be executed. If you don’t know how to make conditions I recommend
you to have a look on my operators’ topic. In short words we can say when we
compare two values with each other that makes a condition that can have two
possible result true and false and the condition statements are using this
condition to perform for us the commands.
If () statement:
in this statement after the “if” prentices
which we will write our condition there and next we have colon that relates our
condition to our statements or commands that we write.
keyword we have
keyword we have
If(condition):
commands
If the condition was true the commands that we write will be
executed but if the condition was false compiler will ignore the commands of
that conditional statement. Like
If (1==1):
print (‘the result is true and I am printing this massage’)
In the above example we can see that our condition is true
and the massage will be printed but if the condition value was false compiler
will ignore the massage like:
If (1==0):
print (‘the result is true and I am printing this massage’)
This will not give us the massage.
elif () statement:
this conditional statement is related with if () statement
that means we can not use this without if () statement we can only use this
statement after if statement as many as we want. the name of elif is a shortcut
for else if we use this keyword when we want to check for multiple conditions,
the structure of this statement is just like if () statement the deference is
just in its keyword we write our condition between prentices and relate it to
our commands by colon the examples are in below:
if (1<0): print (‘one is smaller than zero?’)
elif
(1>0): print (‘one is bigger than zero’)
elif
(1==0): print (‘one is equal with zero’)
I think you know the answer right. If you are confused so it will print the second massage.
else statement (default statment):
this statement is related to if () statement too we cannot
use it alone it comes after if () statements or at the end of elif ()
statements. We use this statement to do something at the end that means if all
conditions were false so this statement will be executed this statement don’t
need any conditions like:
if (1<0): print (‘one is smaller than zero?’)
elif
(1>0): print (‘one is bigger than zero’)
else:
print (‘nothing was true’)
else statement can be used without elif () statement like:
if (1<0): print (‘one is smaller than zero?’)
else:
print (‘nothing was true’)
Nested if:
and at the end I want to mention another important thing
about if () statement which is nested if, the meaning of nested if is when we
use an if () statement in the body of another if () statement like:
if (1==1):
if
(2>1):
print(‘nested
if’)
flow chart of if , elif and else statements:
No comments