So far, your programs have followed a straight path - executing every line of code in order. But real programs need to make decisions! Should I send this email? Is the user old enough? Does this text contain a specific word? Conditional logic lets your program choose different paths based on the data it's working with.
In this lesson, you'll learn:
Python has two special values for representing truth: True
and False
. These are called boolean values (named after mathematician George Boole). Interestingly, True
and False
are special instances of 1 and 0!
Every condition in programming ultimately comes down to: "Is this true or false?"
# Boolean values
is_sunny = True
is_raining = False
print("Is sunny:", is_sunny)
print("Is raining:", is_raining)
print("Type of True:", type(True))
print("Type of False:", type(False))
True and False are special cases of 1 and 0:
# True and False are special cases of 1 and 0
print("True as number:", True + 0)
print("False as number:", False + 0)
print("True + True =", True + True)
print("True + False =", True + False)
Comparison operations create boolean values:
# Comparison operations create boolean values
age = 25
print("Age:", age)
print("Age > 18:", age > 18)
print("Age == 25:", age == 25)
print("Age < 20:", age < 20)
Create variables for a student's test score (85) and the passing grade (70). Use comparison operators to check if they passed.
In Python, many values can be treated as True or False even if they're not actually the boolean values True
and False
. This is called being "truthy" or "falsy".
You can use the bool()
function to see what any value counts as in a boolean context:
False
, 0
, ""
(empty string), empty collections# Testing what values are truthy or falsy
print("=== FALSY VALUES ===")
print("bool(False):", bool(False))
print("bool(0):", bool(0))
print("bool(''):", bool("")) # Empty string
print("bool(None):", bool(None))
Most values are truthy:
print("=== TRUTHY VALUES ===")
print("bool(True):", bool(True))
print("bool(1):", bool(1))
print("bool(-1):", bool(-1))
print("bool('hello'):", bool("hello"))
print("bool('0'):", bool("0")) # String "0" is truthy!
print("bool(' '):", bool(" ")) # Space is truthy!
Testing with real variables:
# Testing with variables
name = ""
message = "Hello"
score = 0
age = 25
print("=== VARIABLE TESTS ===")
print("Empty name (''):", bool(name))
print("Message ('Hello'):", bool(message))
print("Score (0):", bool(score))
print("Age (25):", bool(age))
Test different values to see if they're truthy or falsy. Check an empty string, a string with just a space, the number 0, and a negative number.
The if
statement is how you make your program choose different paths. Like function definitions, if
statements end with a colon :
and use indentation to show which code belongs to the condition.
Pattern: if condition:
followed by indented code block.
# Basic if statement
temperature = 75
if temperature > 70:
print("It's warm outside!")
print("Good weather for a walk.")
print("Weather check complete.")
You can have multiple separate if statements:
# if statement with different conditions
age = 17
if age >= 18:
print("You are eligible to vote.")
if age < 18:
print("You are not yet eligible to vote.")
If statements work with truthy/falsy values:
# Using truthy/falsy values
user_name = "Alice"
if user_name: # Non-empty string is truthy
print("Welcome,", user_name)
empty_name = ""
if empty_name: # Empty string is falsy
print("This won't print")
print("Program continues...")
Create a program that checks if a word is long (more than 10 characters). If it is, print that it's a long word.
Often you need to check multiple conditions or have a backup plan. Python provides elif
(else if) for additional conditions and else
for when none of the conditions are true.
Python checks conditions in order and stops at the first one that's true.
# if/elif/else chain
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Score:", score)
print("Grade:", grade)
Conditions can be based on any type of data:
# Text analysis with conditions
text = "Hello world"
length = len(text)
if length == 0:
print("The text is empty")
elif length < 5:
print("Short text:", text)
elif length < 15:
print("Medium text:", text)
else:
print("Long text:", text)
print("Text length:", length)
Create a temperature classifier. If temp >= 80: "Hot", if temp >= 60: "Warm", if temp >= 40: "Cool", otherwise: "Cold".
You can combine conditions using logical operators:
and
- Both conditions must be trueor
- At least one condition must be truenot
- Reverses the truth value# Using 'and' operator
age = 25
has_license = True
if age >= 16 and has_license:
print("Can drive legally")
else:
print("Cannot drive legally")
The 'or' operator checks if at least one condition is true:
# Using 'or' operator
day = "Saturday"
hour = 14
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
if hour < 9 or hour > 17:
print("Outside business hours")
The 'not' operator reverses the truth value:
# Using 'not' operator
is_raining = False
if not is_raining:
print("Good day for outdoor activities")
You can combine multiple operators:
# Combining multiple operators
text = "Python programming"
word_count = len(text.split())
if len(text) > 10 and word_count >= 2:
print("This is a substantial phrase")
elif len(text) > 5 or word_count > 1:
print("This is a short phrase")
else:
print("This is very short text")
Create a simple access control system. A user can access if they have a valid username (not empty) AND either they are an admin OR their age is 18 or over.
Combining functions with conditional logic creates powerful, flexible code. Functions can make different decisions based on their parameters.
# Function with conditional logic
def categorize_text(text):
length = len(text)
word_count = len(text.split())
if length == 0:
return "empty"
elif word_count == 1:
return "single word"
elif length < 20:
return "short phrase"
elif length < 50:
return "medium text"
else:
return "long text"
# Test the function
test_texts = ["", "Hello", "Python programming", "This is a longer sentence with more words"]
for text in test_texts:
category = categorize_text(text)
print("Text:", repr(text))
print("Category:", category)
print()
Here's another function example with different return values based on conditions:
# Function that returns different values based on conditions
def calculate_shipping(weight, is_express):
base_cost = 5.00
if weight <= 1:
weight_cost = 0
elif weight <= 5:
weight_cost = 2.00
else:
weight_cost = weight * 0.50
total = base_cost + weight_cost
if is_express:
total = total * 2
return total
# Test shipping calculation
standard_shipping = calculate_shipping(3, False)
express_shipping = calculate_shipping(3, True)
print("Standard shipping (3 lbs):", standard_shipping)
print("Express shipping (3 lbs):", express_shipping)
Create a function called get_letter_grade
that takes a numeric score and returns the appropriate letter grade (A, B, C, D, or F).
Let's create a comprehensive text analyzer that uses conditional logic to provide intelligent feedback about text quality and characteristics.
# Comprehensive Text Analyzer with Conditional Logic
def analyze_text_quality(text):
"""Analyze text and provide quality feedback."""
if not text or not text.strip():
return "Error: No text provided"
# Basic statistics
length = len(text)
words = text.split()
word_count = len(words)
sentence_count = text.count(".") + text.count("!") + text.count("?")
# Calculate averages (avoid division by zero)
if word_count > 0:
avg_word_length = sum(len(word.strip(",.!?")) for word in words) / word_count
else:
avg_word_length = 0
if sentence_count > 0:
avg_words_per_sentence = word_count / sentence_count
else:
avg_words_per_sentence = word_count # All words in one sentence
# Quality assessment
quality_score = 0
feedback = []
# Length assessment
if length < 10:
feedback.append("Very short text")
elif length < 50:
feedback.append("Short text")
quality_score += 1
elif length < 200:
feedback.append("Good length")
quality_score += 2
else:
feedback.append("Long text")
quality_score += 1
# Word length assessment
if avg_word_length < 3:
feedback.append("Words are quite short")
elif avg_word_length < 5:
feedback.append("Average word length")
quality_score += 1
else:
feedback.append("Good use of longer words")
quality_score += 2
# Sentence structure assessment
if sentence_count == 0:
feedback.append("No sentence punctuation found")
elif avg_words_per_sentence < 5:
feedback.append("Very short sentences")
elif avg_words_per_sentence < 15:
feedback.append("Good sentence length")
quality_score += 2
else:
feedback.append("Long sentences - consider breaking them up")
quality_score += 1
# Overall quality determination
if quality_score >= 5:
overall_quality = "Excellent"
elif quality_score >= 3:
overall_quality = "Good"
elif quality_score >= 1:
overall_quality = "Fair"
else:
overall_quality = "Needs improvement"
# Format the analysis report
report = "=== TEXT ANALYSIS ===\n"
report += "Text: " + text + "\n\n"
report += "STATISTICS:\n"
report += "Length: " + str(length) + " characters\n"
report += "Words: " + str(word_count) + "\n"
report += "Sentences: " + str(sentence_count) + "\n"
report += "Average word length: " + str(round(avg_word_length, 1)) + " characters\n"
report += "Average words per sentence: " + str(round(avg_words_per_sentence, 1)) + "\n\n"
report += "ASSESSMENT:\n"
for comment in feedback:
report += "- " + comment + "\n"
report += "\nOVERALL QUALITY: " + overall_quality + " (" + str(quality_score) + "/6 points)"
return report
# Test the analyzer with different types of text
test_texts = [
"",
"Hi",
"Python is great!",
"Python is a powerful programming language. It's easy to learn and versatile.",
"The quick brown fox jumps over the lazy dog in the meadow while the sun shines brightly overhead and birds sing melodiously in the distant trees."
]
for i, text in enumerate(test_texts, 1):
print("TEST", i)
print(analyze_text_quality(text))
print("\n" + "="*50 + "\n")
Create a function called check_password_strength
that evaluates password strength based on length and character types. Return "Strong", "Medium", or "Weak".
Congratulations! You now understand how to make decisions in your Python programs:
True
and False
are special cases of 1 and 0and
, or
, not
Conditional logic is what makes programs truly intelligent - they can adapt their behavior based on the data they receive. This is the foundation of creating responsive, interactive software!
Now that you can make decisions and create reusable functions, you're ready to dive deeper into working with text data using Python's powerful string methods!