DEV Community

Cover image for Python Basics for Beginners: Variables and Operators (Part 1)
Nelly Mogere
Nelly Mogere

Posted on

Python Basics for Beginners: Variables and Operators (Part 1)

Part 1 of a 3-part series. Real code from my Python learning journey, written for beginners.

You Can Write Real Programs in Your First Week

Here is the truth about learning Python: you do not need to finish a long course before you build something. In my first week I wrote a bus ticket booking script, a transaction limiter, and the start of a mini bank. Every one of those programs used the same few fundamentals. This article teaches you those fundamentals with the exact code I wrote, so you can run it, break it, and learn from it.

This is Part 1 of a short 3-part series:

READING TIP

Try each snippet yourself before moving on. Typing code builds memory. Copying does not.

1. Your First Python Program

Every journey starts with a single print():

print("hello world")
print("this is my first python program")
Enter fullscreen mode Exit fullscreen mode

print() displays whatever you put between the parentheses. The text inside quotes is a string. Python reads your file top to bottom, so the second line runs right after the first.

IMPORTANT

A string must open and close with the same quote. "hello" is valid, but "hello' (mixing quotes) raises an error. And print always needs parentheses.

Hello world

2. Variables and input(): Make Your Program Talk Back

A program that prints the same text forever is boring. The fun starts when the program asks the user for information. My bus ticket script taught me this:

passenger_name = input("Enter passenger name: ")
route = input("Enter route: ")
age = int(input("Enter passenger age: "))
fare = int(input("Enter fare (ksh): "))

booking_fee = 10
total = fare + booking_fee

print()
print("=" * 40)
print("            TICKET")
print("=" * 40)
print(f"Passenger   : {passenger_name}")
print(f"Route       : {route}")
print(f"Age         : {age} years")
print(f"Fare        : Ksh{fare}")
print(f"Booking Fee : Ksh{booking_fee}")
print("-" * 40)
print(f"TOTAL       :  Ksh{total}")
print("=" * 40)
print("             THANK YOU FOR BOOKING   ")
print("=" * 40)
Enter fullscreen mode Exit fullscreen mode

Three ideas make this whole script work:

  1. input() returns text. Names like passenger_name stay strings. Ages and fares get wrapped in int() because you need numbers to do math.
  2. Variables hold values. booking_fee = 10 stores a number, then total = fare + booking_fee combines it with the user's fare.
  3. f-strings drop variables into text. f"TOTAL: Ksh {total}" inserts the value of total directly. The "=" * 40 trick repeats a character 40 times for clean divider lines.

GOLDEN RULE

You cannot do math with a string. total = "5" + 5 raises a TypeError. Always convert input() with int() or float() before arithmetic. This one rule prevents dozens of crashes.

bus ticket

Mini-challenge: add a luggage fee

MINI-CHALLENGE

Add a luggage fee of Ksh 50 to the ticket total. Hint: only two lines change. Create the variable, then use it in the total.

How to try it: solve it on your own first, then compare with the solution below.

Solution (no peeking before you try):

booking_fee = 10
luggage_fee = 50
total = fare + booking_fee + luggage_fee
Enter fullscreen mode Exit fullscreen mode

3. Python Operators

Operators are the verbs of your program: math, comparisons, and logic.

Arithmetic and Assignment Operators

You already used +. Python also has shortcuts called assignment operators. += means "add to the current value":

balance = 10000

amount = float(input("Deposit Amount: "))
balance += amount  # same as: balance = balance + amount

print(f"Deposited Ksh {amount:,.1f}   New balance: Ksh {balance:,.1f}")
Enter fullscreen mode Exit fullscreen mode

Instead of writing balance = balance + amount, you use the shortcut. Same result, less typing, and it reads like English: "balance plus equals amount".

GOOD TO KNOW

{amount:,.1f} shows the number with commas and one decimal place. You type 5000, Python prints 5,000.0. Money looks professional with almost no effort.

Comparison Operators: True or False

Every comparison returns True or False. These are the questions your program asks:

age = 20
score = 75

print(age == 20)    # True  (equal to?)
print(age == 25)    # False
print(age != 18)    # True  (not equal to?)
print(score > 70)   # True
print(score < 50)   # False
print(score >= 75)  # True
print(score <= 74)  # False
Enter fullscreen mode Exit fullscreen mode

age == 20 is True because age is 20; age == 25 is False. Each line is simply a yes/no question Python answers for you. Note the double equals ==: it asks a question, it does not assign.

Fun discovery: strings compare too. "A" < "B" is True because A comes before B, and Python is case-sensitive, so "Alice" == "alice" is False. Small detail, big bug later.

COMMON BUG

== compares, = assigns. Writing if score = 75 instead of if score == 75 is one of the most common beginner mistakes.

Logical Operators: Combine Conditions

and, or, and not combine multiple conditions into one decision. Here is a real transaction limiter I built with and:

account_type = input("Enter your account type (basic/premium): ")
amount = int(input("Enter Amount to send (Ksh): "))

if account_type == "basic" and amount <= 70000:
    print("Transaction approved")
elif account_type == "basic" and amount > 70000:
    print("Limit exceeded for basic account (max Ksh 70000)")
elif account_type == "premium" and amount <= 300000:
    print("Transaction approved")
elif account_type == "premium" and amount > 300000:
    print("Limit exceeded for premium account (max Ksh 300000)")
else:
    print("Unknown account type")
Enter fullscreen mode Exit fullscreen mode

Trace one scenario: user picks "basic" and sends 85000. The first check fails (85000 is not <= 70000), so Python moves to the elif: is it basic AND over 70000? Both true, so it prints the limit message. The chain tries each combination until one matches. This is real business logic, the kind banks use every day.

WHY IT MATTERS

and checks two conditions at once, and both must be true. The else catches everything the chain missed, here an unknown account type.

account type

Part 1 Recap

You should now be comfortable with:

  • Printing with print() and reading input with input()
  • Storing values in variables and converting them with int() and float()
  • Formatting output with f-strings and the :,.1f money format
  • Using arithmetic (+), assignment (+=), comparison (==, >, <=), and logical (and) operators

COMING NEXT

Making your code decide and repeat. Part 2 takes these operators inside if/else statements and loops.

Continue to Part 2

Continue to Part 2: Python Loops and Control Flow for Beginners

Bookmark this part and leave a comment with what you built. Happy coding.

Top comments (0)