Conditional statements allow you to execute different code blocks based on whether a condition is true or false. The basic syntax for an if/else statement in Python is:
if condition: # Code to execute if the condition is true else: # Code to execute if the condition is false
Here’s an example that uses an if/else statement to determine whether a number is even or odd:
# Ask the user for a number number = int(input("Enter a number: ")) # Check if the number is even or odd if number % 2 == 0: print("The number is even.") else: print("The number is odd.")
In this example, the if
statement checks whether the number entered by the user is divisible by 2 (i.e., even). If it is, the program prints a message saying so. If it isn’t, the program prints a message saying the number is odd.
You can also use nested if statements to check multiple conditions. Here’s an example that checks whether a number is positive, negative, or zero:
# Ask the user for a number number = float(input("Enter a number: ")) # Check if the number is positive, negative, or zero if number > 0: print("The number is positive.") elif number < 0: print("The number is negative.") else: print("The number is zero.")
In this example, the if
statement checks whether the number entered by the user is greater than zero. If it is, the program prints a message saying the number is positive. If it isn’t, the program moves on to the next elif
statement, which checks whether the number is less than zero. If it is, the program prints a message saying the number is negative. If the number is not greater than zero or less than zero, the program moves on to the else
statement, which prints a message saying the number is zero.
Conditional statements are useful in many different contexts in Python, such as user input validation, error handling, and program flow control.
Checking multiple conditions with and
and or
:
You can use the and
and or
operators to check multiple conditions in a single if statement. Here’s an example:
# Ask the user for their age and whether they have a driver's license age = int(input("How old are you? ")) has_license = input("Do you have a driver's license? (y/n) ") == "y" # Check if the person is eligible to drive if age >= 16 and has_license: print("You are eligible to drive.") else: print("You are not eligible to drive.")
In this example, the if
statement checks whether the user is at least 16 years old and has a driver’s license. If both conditions are true, the program prints a message saying the person is eligible to drive. If either condition is false, the program prints a message saying the person is not eligible to drive.
You can also use the or
operator to check whether at least one condition is true.
Using the ternary operator:
The ternary operator is a compact way of writing an if/else statement in a single line of code. Here’s an example:
# Ask the user for a number number = int(input("Enter a number: ")) # Use the ternary operator to check if the number is positive or negative result = "positive" if number > 0 else "negative" # Print the result print("The number is", result)
In this example, the ternary operator checks whether the number entered by the user is greater than zero. If it is, the result
variable is set to "positive"
. If it isn’t, the result
variable is set to "negative"
. The program then prints a message saying whether the number is positive or negative.
The ternary operator can be a useful way to write more concise code, but it can also make your code harder to read if used excessively.
These examples demonstrate some of the more advanced features of conditional statements in Python. As you continue to learn Python, you’ll discover many more techniques and libraries for working with conditions and logical expressions.
Checking for membership using in
:
The in
operator can be used to check if an item is a member of a list, tuple, or other iterable object. Here’s an example:
# Ask the user for their favorite color color = input("What is your favorite color? ") # Check if the color is in a list of primary colors if color.lower() in ["red", "blue", "yellow"]: print("Your favorite color is a primary color!") else: print("Your favorite color is not a primary color.")
In this example, the if
statement checks if the user’s favorite color is "red"
, "blue"
, or "yellow"
. If it is, the program prints a message saying that the color is a primary color. If it isn’t, the program prints a message saying that the color is not a primary color.
Using elif
to check multiple conditions:
The elif
keyword can be used to check multiple conditions in a single if statement. Here’s an example:
# Ask the user for their grade on a test grade = int(input("What was your grade on the test? ")) # Check the grade and give feedback if grade >= 90: print("Great job! You got an A!") elif grade >= 80: print("Good job! You got a B.") elif grade >= 70: print("Not bad. You got a C.") elif grade >= 60: print("You got a D. You need to study harder.") else: print("You got an F. You failed the test.")
In this example, the program checks the user’s grade on a test and prints a message depending on the grade. If the grade is at least 90, the program prints a message saying the user got an A. If the grade is between 80 and 89, the program prints a message saying the user got a B. If the grade is between 70 and 79, the program prints a message saying the user got a C. If the grade is between 60 and 69, the program prints a message saying the user got a D. If the grade is below 60, the program prints a message saying the user failed the test.
These are just a few more examples of how you can use conditional statements in Python to make your programs more powerful and flexible. As you continue to learn Python, you’ll discover many more ways to use conditionals to create complex logic and solve a wide variety of programming problems.
Using the ternary operator for compact if-else statements:
Python provides a shorthand notation for if-else statements, known as the ternary operator. Here’s an example:
# Check if a number is even or odd num = int(input("Enter a number: ")) result = "even" if num % 2 == 0 else "odd" print(f"The number {num} is {result}.")
In this example, the program checks if the user’s input is even or odd using the modulus operator %
. If the remainder is zero, then the number is even and the variable result
is set to "even"
. Otherwise, the number is odd and result
is set to "odd"
. The ternary operator is used to set result
in a single line of code.
Chaining multiple conditions with and
and or
:
You can use the logical operators and
and or
to combine multiple conditions in a single if statement. Here’s an example:
# Ask the user for their age and citizenship age = int(input("How old are you? ")) citizenship = input("Are you a citizen of the United States (y/n)? ") # Check if the user is eligible to vote if age >= 18 and citizenship.lower() == "y": print("You are eligible to vote!") else: print("You are not eligible to vote.")
In this example, the program checks if the user is at least 18 years old and a citizen of the United States using the and
operator. If both conditions are true, the program prints a message saying the user is eligible to vote. If either condition is false, the program prints a message saying the user is not eligible to vote.
Using not
to negate a condition:
The not
keyword can be used to negate a condition. Here’s an example:
# Ask the user for their favorite food food = input("What is your favorite food? ") # Check if the user dislikes pizza if not food.lower() == "pizza": print("I see you have good taste!") else: print("Really? I thought everyone loved pizza.")
In this example, the program checks if the user’s favorite food is not pizza using the not
operator. If the user does not like pizza, the program prints a message saying they have good taste. If the user’s favorite food is pizza, the program prints a message expressing surprise that anyone could dislike pizza.
These are just a few more examples of how you can use conditional statements in Python to make your programs more powerful and flexible. As you continue to learn Python, you’ll discover many more ways to use conditionals to create complex logic and solve a wide variety of programming problems.
Nested if-else statements:
You can nest if-else statements to check for multiple conditions in sequence. Here’s an example:
# Check if a number is positive, negative, or zero num = int(input("Enter a number: ")) if num > 0: print("The number is positive.") elif num < 0: print("The number is negative.") else: print("The number is zero.")
In this example, the program checks if the user’s input is positive, negative, or zero using a series of nested if-else statements. If the number is greater than zero, the program prints a message saying it’s positive. If it’s less than zero, the program prints a message saying it’s negative. If it’s equal to zero, the program prints a message saying it’s zero.
Using the in
keyword to check for membership:
You can use the in
keyword to check if a value is a member of a sequence or collection. Here’s an example:
# Check if a letter is a vowel or a consonant letter = input("Enter a letter: ") if letter in "aeiou": print("The letter is a vowel.") else: print("The letter is a consonant.")
In this example, the program checks if the user’s input is a vowel or a consonant by checking if the letter is a member of the string “aeiou” using the in
keyword. If the letter is in the string, the program prints a message saying it’s a vowel. Otherwise, the program prints a message saying it’s a consonant.
Using the pass
keyword as a placeholder:
Sometimes you may want to create an if statement that doesn’t do anything yet. You can use the pass
keyword as a placeholder in these situations. Here’s an example:
# Check if a number is even or odd num = int(input("Enter a number: ")) if num % 2 == 0: print("The number is even.") else: pass
In this example, the program checks if the user’s input is even or odd using the modulus operator %
. If the remainder is zero, then the number is even and the program prints a message saying so. Otherwise, the program doesn’t do anything yet, but the pass
keyword indicates that there will be additional logic added to the else statement later.
These are just a few more examples of how you can use conditional statements in Python to create complex logic and solve a wide variety of programming problems. As you continue to learn Python, you’ll discover many more ways to use conditionals to make your programs more powerful and flexible.
Using multiple conditions with logical operators:
You can use logical operators like and
, or
, and not
to combine multiple conditions in an if statement. Here’s an example:
# Check if a number is between 0 and 100 num = int(input("Enter a number: ")) if num >= 0 and num <= 100: print("The number is between 0 and 100.") else: print("The number is not between 0 and 100.")
In this example, the program checks if the user’s input is between 0 and 100 using the logical and
operator to combine two conditions. If both conditions are true, the program prints a message saying the number is between 0 and 100. Otherwise, the program prints a message saying the number is not between 0 and 100.
Using if-elif-else chains:
You can use if-elif-else chains to check for multiple conditions in a more concise and organized way. Here’s an example:
# Check if a number is positive, negative, or zero using if-elif-else chain num = int(input("Enter a number: ")) if num > 0: print("The number is positive.") elif num < 0: print("The number is negative.") else: print("The number is zero.")
In this example, the program checks if the user’s input is positive, negative, or zero using an if-elif-else chain. The program evaluates each condition in order, stopping as soon as it finds a condition that’s true. If none of the conditions are true, the program executes the code in the else block.
Ternary operator:
Python has a shorthand syntax for writing simple if-else statements called the ternary operator. Here’s an example:
# Determine if a number is even or odd using ternary operator num = int(input("Enter a number: ")) result = "even" if num % 2 == 0 else "odd" print(f"The number is {result}.")
In this example, the program checks if the user’s input is even or odd using the modulus operator %
and the ternary operator. The ternary operator evaluates the expression num % 2 == 0
and returns the string “even” if it’s true, or the string “odd” if it’s false. The program then uses an f-string to print a message saying whether the number is even or odd.
These are just a few more examples of how you can use conditional statements in Python to create complex logic and solve a wide variety of programming problems. As you continue to learn Python, you’ll discover many more ways to use conditionals to make your programs more powerful and flexible.