If, elif and else
If and else use to apply logical mathematical conditions. This will return true or false after statement execution.
Below are some conditions:
a < b : a is less than b.
a > b : a is greater than b
a == b : a is equal to b
a >= b : a is greater than equal to b
a <= b : a is less than equal to b
a != b : a does not equal to b
There are different if else statements in Java:
- if statement
- elif statement
- else statements
If Statement:
The if statement decides either to run or not the block of code.
Syntax:
if <condition> :
// bock of code
Example:
a = 2
b = 5
if a < b :
print("a is less than b");
OUTPUT:
a is less than b
elif Statement:
Code execution will always check if condition first. if if condition returns false, it will go and look for elif condition if defined:
Syntax:
if <condition_1> :
// Bock of code
elif <condition_2>
// Block of Code
Example:
a = 5
b = 5
if a < b :
print("a is less than b");
elif a ==b:
print("a is equals to b")
OUTPUT:
a is equals to b
else Statement:
The code will execute else block statement, only if and elif conditions are false.
Syntax:
if <condition_1> :
// Bock of code
elif <condition_2>
// Block of Code
else
// Block of Code
Example:
a = 15
b = 5
if a < b :
print("a is less than b");
elif a ==b:
print("a is equals to b");
else:
print("a is greater than b");
OUTPUT:
a is greater than b
Loop
Loop execute block of code repeatedly till the condition is true. Python provides two kinds of loop statements:
- While Loop
- For Loop
While Loop:
While loop repeats till the given Boolean condition is true.
As shown in the below diagram, the statement will run till the condition check is true.
Syntax:
while condition:
// block of code
Example:
Here the while loop will run till the condition is true for i which is less than the length of languages list.
len() function will return or give length of the List.
i = 0;
languages = ["HTML", "CSS", "Java"]
while i < len(languages):
print(languages[i])
i = i + 1;
OUTPUT:
HTML
CSS
Java
NOTE: Always increment the index to access the next value. e.g. → i=i+1
For Loop:
For loop is quite different from while and do while loop. The list, tuple and set value can be access sequentially after running loop without knowing the index. For loop in Python mostly used to iterate list, tuple, set etc.
Syntax:
<list_item_name> in <list_name>:
// block of code
Example:
languages = ["HTML", "CSS", "Java"]
for language in languages:
print(language)
OUTPUT:
HTML
CSS
Java
Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.