PythonPlaza - Python & AI

Python

IntroductionVariablesIf-else
Strings Functions while-loop
For-LoopListSet
DictionaryTuple Try..Except
Class/ObjectInheritancePolymorphism
File Handling

Python if elif else statements:

The if elif else statements in Python are used for decision making, where a conditions are evaluated and based on the result of the condition, certain satements will be executed. Indentation is required in the if elif else statements.

The following logical statements are supported by Python.

x == y (It checks if the 2 variables x and y are equal)

x != y (It checks if the 2 variables x and y are not equal)

x < y (It checks if the variable x is less than y)

x <= y (It checks if the variable x is less than or equal to and y)

x > y (It checks if the variable x is greater than y)

x >= y (It checks if the variable x is greater than or equal to y)


if else Statement

if(Condition X):
Execute the statements if the Condition X is met.
else:
Execute the statements if the Condition X is not met.


if elif Statement

if(Condition X):
Execute the statements if the Condition X is met.
elif(Condition Y):
Execute the statements if the Condition Y is met.


if elif else Statement

if(Condition X):
Execute the statements if the Condition X is met.
elif(Condition Y):
Execute the statements if the Condition Y is met.
else:
Execute the statements if the Condition X and Y are not met.



Code Example 1:
#Check if the number > 0
x = 3
if (x > 0):
 print(f"{x} is a positive number")

#Output:
3 is a positive number.

Code Example 2:
#Check if the number > 0
y = -3
if (y < 0):
 print(f"{x} is a negative number")

#Output:
3 is a negative number.

Code Example 3:
#Is the number greater than 10 or not.
z = 5
if z > 10:
 print(f"{z} is greater than 10.")
else:
 print(f"{z} is less than 10.")

#Output:
5 is less than 10.

Code Example 4:
#Output Grade of a Student.
marks = input("Please enter the Marks:")

intMarks=int(marks)

if(intMarks >= 90):
 print("Student got A Grade")
elif(intMarks < 90 and intMarks >= 80):
 print("Student got B Grade")
elif(intMarks < 80 and intMarks >= 70):
 print("Student got C Grade")
elif(intMarks < 70 and intMarks >= 60):
 print("Student got D Grade")
else:
 print("Failed")
 
#Output:
Please enter the Marks:79
Student got C Grade

Code Example 5:
#An example of nested if statment. 
x = input("Enter a number between 1 and 20=")
intX=int(x)

if (intX > 10):
    print("The number entered is greater than 10.")

    if (intX > 15):
        print("The number entered is greater than 15.")
    elif(intX == 15):
        print("The number entered is equal to 15.")
    else:
        print("The number entered is less than 15.")
else:
    print("The number entered is less than 10.")

#Output:
Enter a number between 1 and 20=12
The number entered is greater than 10.
The number entered is less than 15.