CMPSC 100 Computational Expression
Comparing values
These operators return boolean values (True/False):
==
Equal to!=
Not equal to<
Less than>
Greater than<=
Less than or equal to>=
Greater than or equal toCombining boolean values
Used to combine or modify boolean values:
and
- Both conditions must be Trueor
- At least one condition must be Truenot
- Reverses the boolean valueMaking decisions in your code
Conditional statements allow programs to make decisions:
Real-world analogy: - “If it is raining, take an umbrella” - “If you’re hungry, eat something” - “If the temperature is below 32°F, water freezes”
Without conditionals, programs can only follow one path:
With conditionals, we can create responsive programs:
if
StatementBasic decision making
if
Statement SyntaxThe simplest conditional statement:
Key parts:
if
keyword starts the statement:
) ends the condition lineif
Statement ExamplesSimple examples:
More examples:
Review of comparison operators:
==
Equal to!=
Not equal to<
Less than>
Greater than<=
Less than or equal to>=
Greater than or equal toExamples:
else
StatementHandling the alternative
else
for Two ChoicesHandle both True and False cases:
Example:
elif
StatementMultiple conditions
When you need more than two choices:
Key points: - elif
is short for “else if” - You can have multiple elif
statements - Only the first True condition executes - else
is optional and runs if nothing else is True
elif
ExamplesGrade calculator:
Combining conditions
and
, or
, not
Combine multiple conditions:
and
- Both conditions must be Trueor
- At least one condition must be Truenot
- Reverses True/FalseAge and grade level:
Conditionals inside conditionals
Conditional statements inside other conditional statements:
When to use: - When you need to check a second condition only after the first is true - For more complex decision-making logic - To avoid overly complicated logical operators
Grade and extra credit:
Weather and activity suggestions:
is_sunny = input("Is it sunny? (y/n): ") == "y"
temperature = float(input("What's the temperature? "))
if is_sunny:
print("Great! It's sunny.")
if temperature >= 75:
print("Perfect for swimming!")
elif temperature >= 60:
print("Good for a picnic!")
else:
print("Sunny but chilly - wear a jacket!")
else:
print("It's not sunny today.")
if temperature >= 70:
print("Still nice for indoor activities!")
else:
print("Good day to stay inside!")
Avoiding pitfalls
Indentation errors:
Using assignment instead of comparison:
Forgetting the colon:
Comparing strings incorrectly:
Write clear conditions:
Use meaningful variable names: