Editor settings

General settings

Save settings

Learn to program with Python

Combine if statement with else #

In Python, else is a keyword that is used with an if statement to specify a block of code to be executed when the condition of the if statement evaluates to False.

Here's how to write your code using else with if statement:

if condition:
    # block of code to be executed if the condition is True
else:
    # block of code to be executed if the condition is False

For example:

age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")

In this example, we check if the age variable is greater than or equal to 18. If it is, we print "You are an adult." If it's not, we print "You are not an adult.".


Exercise #

Change the code within the function is_longer_than_5_characters to use the else keyword:

  • If text is longer than 5 characters, it prints out only "That is longer than 5 characters.".
  • If text is not longer than 5 characters, it prints out only "That is not longer than 5 characters.".

Tests #

  • is_longer_than_5_characters("1234") should print the message "That is not longer than 5 characters."
  • is_longer_than_5_characters("12345") should print the message "That is not longer than 5 characters."
  • is_longer_than_5_characters("123456") should print the message "That is longer than 5 characters."
Output will be displayed here