When I first started writing code, everything felt like a simple sequence: run line one, then run line two, then exit. But real software doesn't run in a straight line. It has to make decisions.
Did the user input a username and/or password? Is the username correct? Should a user be allowed to sign in? Does a phone number match the format you expect? And many more.
Answering these questions comes down to two foundational ideas in Python: operators and conditionals. Once you understand how they work together, your scripts stop being static lists of commands and start behaving like real applications.
Here is what I learned while wrapping my head around them, along with code from a command-line contact book project I built to put these concepts to work.
You can also check my previous articles on Python. Python will Save You Time. Here is Why and How and Python Basics: Where It All Starts
What Are Operators?
Think of operators as the verbs of Python. They take pieces of data (called operands) and do something with them, usually spitting out a brand new value.
Python has several categories of operators, but three show up constantly when you're controlling program flow: arithmetic, comparison, and logical operators.
1. Arithmetic Operators
You probably know these from math class: addition (+), subtraction (-), multiplication (*), and division (/).
In Python, though, arithmetic operators aren't just for math. They can also manipulate text. For example, multiplying a string repeats it:
print("=" * 40)
# Outputs: ========================================
This is a neat trick for printing clean visual borders in terminal menus without typing forty equals signs by hand.
2. Comparison Operators
These operators compare two values and always return a Boolean: either True or False.
-
==checks if two values are equal -
!=checks if two values are not equal -
<,>,<=,>=handle standard less-than and greater-than checks
A classic mistake here is confusing = with ==. A single equals sign assigns a value to a variable (age = 25). A double equals sign asks a question (age == 25). Python will throw a syntax error if you mix these up in an if statement, but it still trips up almost everyone in the beginning.
3. Logical Operators
Logical operators let you combine multiple conditions:
-
andreturnsTrueonly if both conditions are true. -
orreturnsTrueif at least one condition is true. -
notreverses the Boolean value (turningTruetoFalse, and vice versa).
Python reads these almost like plain English, which makes long conditions much easier to decipher.
Directing Traffic with Conditionals
Conditionals are where operators get useful. They tell Python: "Only run this block of code if a specific condition evaluates to True."
The basic structure uses if, elif (short for else-if), and else:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Keep practicing!")
Python evaluates these from top to bottom. As soon as one condition evaluates to True, Python executes that indented block and skips the rest of the chain completely.
How I Used Them in a Project: The Contact Book
Theory is fine, but seeing these ideas handle messy real-world input is where things click.
Recently, I built a command-line contact book that stores names and Kenyan phone numbers in a dictionary. The entire program relies on operators and conditionals to route user choices and validate data.
Here is the core logic:
import re
contacts = {}
while True:
print("=" * 40)
print("1. Add Contact\n2. Search Contact\n3. Delete Contact\n4. Print All\n5. Quit")
choice = str(input("Enter your choice (1-5): ")).strip()
if choice == '1':
name = input("Enter contact name: ").strip().lower()
# Checking for empty strings using "not"
if not name:
print("Name cannot be empty. Please enter a valid name.")
continue
# Using the "in" membership operator
if name in contacts:
print(f"Contact {name} already exists. Do you want to update their number? (y/n): ")
update = input().strip().lower()
if update == 'n':
continue
phone = input("Enter phone number: ").strip()
# Validation checks
if not phone.isdigit():
print("Invalid phone number. Please enter digits only.")
continue
else:
if phone.startswith('+254'):
phone = '0' + phone[4:]
if re.match(r"^(07|01)\d{8}$", phone):
contacts[name] = phone
print(f"Added {name}: {phone} successfully.\n")
else:
print("Invalid phone number format. Must start with 07 or 01 and have 10 digits.\n")
elif choice == '2':
name = input("Enter contact name: ").strip().lower()
if name in contacts:
print(f"{name}: {contacts[name]}")
else:
print("Contact not found.")
elif choice == '3':
name = input("Enter contact name: ").strip().lower()
if name in contacts:
del contacts[name]
print(f"Contact {name} deleted successfully.")
else:
print("Contact not found.")
elif choice == '4':
# Checking truthiness of the contacts dictionary
if contacts:
print("All Contacts:")
print("=" * 40)
for name, phone in contacts.items():
print(f"{name}: {phone}")
print(f"Total contacts: {len(contacts)}\n")
else:
print("No contacts to display.")
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice, please select 1-5.\n")
Let's break down three specific ways operators and conditionals keep this program from breaking.
1. Truthiness and the not Operator
Look at how empty inputs are handled:
if not name:
print("Name cannot be empty.")
continue
In Python, empty structures, like an empty string "", an empty list [], or an empty dictionary {} are considered "falsy." That means Python treats them as False in a conditional context.
If the user hits Enter without typing a name, name is "". Python sees that as False. The not operator flips that False to True, triggering the warning and restarting the loop.
I used the same concept when printing the directory:
if contacts:
# Print the directory
else:
print("No contacts to display.")
Instead of writing if len(contacts) > 0:, we can test the dictionary directly. If it has items, it is truthy. If it's empty, it evaluates to False.
2. The in Membership Operator
Before adding, updating, or deleting a name, the program needs to know if that person already exists:
if name in contacts:
del contacts[name]
in is a membership operator. It checks whether a specific key exists inside a collection. Using in keeps your code readable and saves you from writing manual search loops just to see if a record is there.
3. Cleaning and Validating Inputs
Real data is unpredictable. Users add extra spaces, enter letters where numbers belong, or use international prefixes instead of local ones.
The nested conditionals inside option 1 act like a filter:
-
if not phone.isdigit():catches accidental letters or symbols right away. -
if phone.startswith('+254'):checks for the Kenyan country code and normalizes it to a local zero (phone = '0' + phone[4:]). - An inner regular expression check ensures the number begins with
07or01and contains exactly ten digits.
If any check fails, execution stops early with a clear error message instead of corrupting the dictionary with bad data.
Three Common Mistakes to Avoid
Forgetting that input() Returns a String
When asking users for numbers, beginners often write:
age = input("Enter your age: ")
if age >= 18:
print("Allowed")
This crashes with a TypeError. Even if the user types 20, Python stores it as "20" (text). You cannot compare text to an integer. You must explicitly convert it using int(input(...)) or keep both sides of your comparison as strings, like I did with choice == '1'.
Accidental Assignment
Writing if choice = '1': instead of if choice == '1': will stop your script immediately. Assignment gives a variable a value; comparison evaluates a relationship.
Over-Nesting Conditionals
It's tempting to put if statements inside if statements five levels deep. If you catch yourself indenting four or five times, consider using and to combine conditions, or use guard clauses (like continue or return) to kick out invalid data early.
Practical Takeaways
-
Use string operators for formatting:
"=" * 40keeps your CLI output clean without clutter. -
Lean on truthiness: You don't need
if len(my_list) == 0:. A simpleif not my_list:is cleaner and more idiomatic Python. - Validate early: Check for bad inputs first and exit early. It keeps your main logic clean and easier to maintain.
- Remember that
=assigns, while==compares.
Operators and conditionals are the decision-makers in your scripts. Once you get comfortable combining them, you can handle unexpected input, manage state, and build programs that work reliably. Give a simple CLI tool like this a try—building one teaches you more about logic flow than reading syntax ever will.
Top comments (0)