Python Full Tutorial -- Part 3: Operators & Input/Output

By Suraj Ahir 2025-12-09 11 min read

← Part 2Python Tutorial · Part 3 of 12Part 4 →
Python Full Tutorial -- Part 3: Operators & Input/Output

Programs that only produce fixed output are not useful tools -- they are demonstrations. Real programs ask questions, process answers, and produce results tailored to the input. That requires operators for comparison and arithmetic, and the input/output functions that connect your code to the outside world.

The moment I added an input() call to a Python script and it waited for my input, then did something with it, something clicked. This was no longer just code I was reading -- it was a tool responding to me. That shift from passive to interactive is what this part covers.

Arithmetic Operators

All arithmetic operations
x, y = 17, 5

print(x + y)    # 22
print(x - y)    # 12
print(x * y)    # 85
print(x / y)    # 3.4  -- always float
print(x // y)   # 3    -- floor division (integer)
print(x % y)    # 2    -- modulo (remainder)
print(x ** y)   # 1419857 -- exponentiation

# Compound assignment
count = 0
count += 1      # count = count + 1
count *= 2
count //= 3
count **= 2

Comparison Operators

Comparing values -- return True or False
x, y = 10, 20

print(x == y)   # False
print(x != y)   # True
print(x < y)    # True
print(x > y)    # False
print(x <= y)   # True
print(x >= y)   # False

# Chained comparisons
age = 25
if 18 <= age <= 65:
    print("Working age adult")

# String comparison (lexicographic order)
print("apple" < "banana")    # True
print("Python" == "python")  # False (case sensitive)

Logical Operators: and, or, not

Combining conditions
age = 25
has_id = True
is_member = False

# and: all must be True
if age >= 18 and has_id:
    print("Entry allowed")

# or: at least one must be True
if is_member or age >= 18:
    print("Eligible")

# not: invert
if not is_member:
    print("Not a member")

# Short-circuit evaluation
x = None
result = x or "default"     # "default" because x is None
name = "Suraj"
display = name or "Anonymous"  # "Suraj"

Membership and Identity Operators

in, not in, is, is not
skills = ["Python", "Docker", "Linux"]

print("Python" in skills)         # True
print("Kubernetes" not in skills) # True
print("World" in "Hello, World!") # True

# Identity: is checks if same object in memory
x = [1, 2, 3]
y = x              # Same list object
z = [1, 2, 3]      # Different object, same values

print(x is y)  # True
print(x is z)  # False
print(x == z)  # True (same values)

# Always use is for None checks
value = None
if value is None:
    print("Value is None")

Reading User Input with input()

input() always returns a string
name = input("Enter your name: ")
print(f"Hello, {name}!")

# ALWAYS convert to the right type
age = int(input("Enter your age: "))
price = float(input("Enter price: "))

print(f"In 10 years you will be {age + 10}")
print(f"Total with 18% tax: Rs.{price * 1.18:.2f}")

# Safe input with validation loop
while True:
    raw = input("Enter a positive integer: ")
    if raw.isdigit() and int(raw) > 0:
        number = int(raw)
        break
    print("Invalid. Please try again.")
print(f"You entered: {number}")

Advanced print() Options

print() parameters
print("A", "B", "C")              # A B C
print("A", "B", "C", sep="-")     # A-B-C
print("Loading...", end="")        # No newline
print(" Done!")                     # Continues same line

# Unpack a list into print
items = ["Python", "Docker", "Linux"]
print(*items, sep="\n")   # Each on its own line

String Formatting Compared

Three ways to format strings
name = "Suraj"
score = 98.567

# Method 1: f-strings (MODERN -- use this)
print(f"Name: {name}, Score: {score:.2f}")
print(f"Price: Rs.{1234567.89:,.2f}")   # 1,234,567.89
print(f"Percent: {0.856:.1%}")          # 85.6%
print(f"Padded: {name:<20}|")          # left-align in 20 chars
print(f"Padded: {name:>20}|")          # right-align
print(f"Center: {name:^20}|")           # center

# Method 2: .format() (older, still works)
print("Name: {}, Score: {:.2f}".format(name, score))

# Method 3: % (oldest -- avoid in new code)
print("Name: %s" % name)

Practical Example: BMI Calculator

Interactive program combining operators and I/O
print("=== BMI Calculator ===")

weight = float(input("Weight in kg: "))
height = float(input("Height in metres: "))

bmi = weight / (height ** 2)
print(f"\nYour BMI: {bmi:.1f}")

if bmi < 18.5:
    category = "Underweight"
elif bmi < 25.0:
    category = "Normal weight"
elif bmi < 30.0:
    category = "Overweight"
else:
    category = "Obese"

print(f"Category: {category}")

Frequently Asked Questions

What is the modulo operator used for?

17 % 5 returns 2 (the remainder). Check even numbers: n % 2 == 0. Cycle through values: index % length. Work with time: total_seconds % 60 gives remaining seconds after extracting full minutes.

What is the difference between == and is?

== checks value equality (same content). is checks identity (exact same object in memory). Use == for comparing values. Use is only for None: if value is None: -- never write if value == None:

How does input() work and why does it always return a string?

input() pauses the program, shows the prompt, waits for the user to type and press Enter, then returns whatever they typed as a string. Always convert: int(input()) for integers, float(input()) for decimals.

What is short-circuit evaluation?

Python stops evaluating and expressions when it finds False (result cannot be True). Stops or expressions when it finds True. Enables: result = value or default -- if value is falsy, default is used.

Which string formatting method should I use?

Always f-strings for new code (Python 3.6+). They are the most readable, fastest, and most powerful. Use .format() only when you need reusable templates. Avoid % formatting in new code entirely.

In Part 4, we cover if/elif/else -- the decision-making logic that lets programs respond differently to different situations.

Key takeaways

Continue reading
Part 4 — Functions and Scope
How to write code worth reusing.
Suraj Ahir — author of SRJahir Tech

Written by

Suraj Ahir

Cloud & DevOps engineer running four live production services on my own AWS infrastructure. I write everything on this site myself — no ghostwriters, no AI filler.

← Part 2Python Tutorial · Part 3 of 12Part 4 →
← Back to Blog
Disclaimer: This content is for educational purposes only. SRJahir Tech does not guarantee any specific outcome.