Python else statement
Created By: chatGPT
In Python, the else statement is used in conjunction with if statements to define an alternate block of code that executes when the condition of the if statement evaluates to False. This is particularly useful for handling various scenarios in your code.
Here's a simple example to illustrate the usage of the else statement:
age = 20
if age >= 18:
print('You are an adult.')
else:
print('You are not an adult.')
In this example, if the age variable is 18 or older, the program will print 'You are an adult.' If the age variable is younger than 18, it will print 'You are not an adult.' This shows how the else statement provides a fallback option for when the condition is not met.
temperature = 30
if temperature > 25:
print('It is warm outside.')
else:
print('It is cold outside.')
The else statement can also be used after if-elif statements for additional condition handling. This allows for more complex decision-making in your code. Here's an example using the if-elif-else structure:
score = 85
if score >= 90:
print('Grade: A')
elif score >= 80:
print('Grade: B')
else:
print('Grade: C')
In this case, the program determines the letter grade based on the score variable. If the score is 90 or above, it prints 'Grade: A'. If the score is 80 or above but less than 90, it prints 'Grade: B'. Otherwise, it defaults to 'Grade: C'. This showcases the flexibility of using else within different conditional structures.
number = 0
if number > 0:
print('Positive number')
elif number < 0:
print('Negative number')
else:
print('Zero')