🌟 The Petroleum Coding Guide

This guide explains every step in simple words. You’ll learn what each piece of code does and why it behaves that way.

How a Petroleum program runs

When you run a Petroleum file, the language looks for a function named main. If it exists, Petroleum calls it automatically. That’s why you don’t need to explicitly invoke main() yourself (after you've defined it, as you would for regular functions).

You can also call functions at the top level (outside of any function). Those lines run immediately as the file loads. This is handy for tiny scripts. For bigger programs, it’s cleaner to put your work inside main() so there’s one clear starting point.


# Style A: quick script — top-level call runs immediately when the file loads
def say_hello(person_name):
    print("Hello, " + person_name)

say_hello("Ava")   # runs right away


# Style B: structured app — Petroleum auto-calls main() first
def main():
    say_hello("Max")

Think of main() as the front door of your program. The computer walks through it first if it’s present.

Comments, printing, and indentation

Comments are notes to yourself. Petroleum ignores them. Use # at the start of a line or after code.

Printing can show multiple things at once by separating them with commas.

Indentation shows which lines belong together, like inside a function. Petroleum treats indentation like Python does.


def main():
    # This is a comment. It helps you and future you.
    name = "Ava"  # Comments can go after code too
    age = 25
    
    # Print multiple things at once
    print("Name:", name, "Age:", age)
    
    # Keep the window open so you can see the output
    input("Press Enter to exit...")

Variables: giving names to values

A variable is a name that remembers a value. Use clear names.


def main():
    player_name = "Ava"
    total_coins = 25
    print(player_name)
    print(total_coins)

Strings: text values with superpowers

Use single '...', double "...", or triple quotes for multi-line text.

F-strings let you put values right inside text with {...}.


def main():
    name = "Ava"
    age = 25
    
    # Regular strings
    greeting = "Hello"
    question = 'How are you?'
    
    # F-strings - variables go inside {}
    personal_greeting = f"Hello {name}! You are {age} years old."
    
    # Multi-line strings
    poem = """Roses are red,
Violets are blue,
Petroleum is awesome,
And so are you!"""
    
    # Multi-line f-strings work too!
    info = f"""Welcome {name}!
Your age: {age}
Next year: {age + 1}"""
    
    print(personal_greeting)
    print(info)

Numbers and math

Math works like you expect. // is whole-number division, ** is power.


def main():
    apples = 10
    friends = 3
    print(apples + friends)   # 13
    print(apples - friends)   # 7
    print(apples * friends)   # 30
    print(apples // friends)  # 3 (whole division)
    print(apples / friends)   # 3.333...
    print(apples % friends)   # 1 (remainder)
    print(apples ** 2)        # 100 (power)

Booleans: true or false decisions

A boolean is a value that's either True or False. Booleans help your program make decisions.

Comparison operators create boolean values by comparing things:

  • == means "is equal to"
  • != means "is not equal to"
  • < means "is less than"
  • > means "is greater than"
  • <= means "is less than or equal to"
  • >= means "is greater than or equal to"

def main():
    # Boolean values
    is_sunny = True
    is_raining = False
    
    # Comparisons create booleans
    age = 18
    can_vote = age >= 18        # True (18 is >= 18)
    is_teenager = age < 20      # True (18 is < 20)
    
    print("Can vote?", can_vote)
    print("Is teenager?", is_teenager)
    
    # Combine booleans with 'and', 'or', 'not'
    can_drive = age >= 16 and has_license
    can_enter = is_member or has_ticket
    is_closed = not is_open

Tip: Read and as "both must be true", or as "at least one must be true", and not as "the opposite".

Making decisions: if, elif, else

Use if to run code only when a condition is true. Add elif (else if) for more conditions, and else as a catch-all.

Think of it like a flowchart: the computer checks each condition from top to bottom and runs the first one that's true.


def main():
    score = 85
    
    # Simple if statement
    if score >= 60:
        print("You passed!")
    
    # If with else (two choices)
    if score >= 90:
        print("Excellent!")
    else:
        print("Keep practicing!")
    
    # Multiple choices with elif
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    elif score >= 70:
        grade = "C"
    elif score >= 60:
        grade = "D"
    else:
        grade = "F"
    
    print(f"Your grade: {grade}")

Important: Notice the colon : at the end of each if/elif/else line, and the indentation of the code inside. This is how Petroleum knows what belongs together.

Lists: collections of things

A list holds multiple values in order. Use square brackets [...] to create a list. You can add, remove, and access items.


def main():
    # Create a list
    fruits = ["apple", "banana", "cherry"]
    numbers = [1, 2, 3, 4, 5]
    empty_list = []
    
    # Access items by position (starts at 0!)
    first_fruit = fruits[0]   # "apple"
    second_fruit = fruits[1]  # "banana"
    last_fruit = fruits[-1]   # "cherry" (negative = from end)
    
    # Get the length
    count = len(fruits)  # 3
    
    # Print all fruits
    print("Fruits:", fruits)
    print("First:", first_fruit)
    print("Count:", count)

Remember: List positions start at 0, not 1. So the first item is at position 0, the second at position 1, and so on.

For loops: doing things repeatedly

A for loop goes through each item in a list (or range of numbers) one at a time. It's like saying "for each item, do this..."


def main():
    # Loop through a list
    fruits = ["apple", "banana", "cherry"]
    
    for fruit in fruits:
        print(f"I like {fruit}!")
    
    # Loop through numbers with range()
    # range(5) gives you: 0, 1, 2, 3, 4
    for i in range(5):
        print(f"Count: {i}")
    
    # range(start, end) - end is not included
    # range(1, 4) gives you: 1, 2, 3
    for num in range(1, 4):
        print(f"Number: {num}")
    
    # Calculate a sum
    total = 0
    for n in [10, 20, 30]:
        total = total + n
    print("Total:", total)  # 60

Tip: The variable after for (like fruit or i) takes on each value in turn. You can name it whatever makes sense!

While loops: keep going until...

A while loop keeps running as long as its condition is true. Use it when you don't know exactly how many times you'll need to repeat.

Be careful: Make sure the condition eventually becomes false, or your loop will run forever!


def main():
    # Countdown
    count = 5
    while count > 0:
        print(count)
        count = count - 1  # Important: change the condition!
    print("Blast off!")
    
    # Keep asking until valid input
    password = ""
    while password != "secret":
        password = input("Enter password: ")
    print("Access granted!")
    
    # Use 'break' to exit early
    while True:  # Runs forever...
        answer = input("Type 'quit' to exit: ")
        if answer == "quit":
            break  # ...unless we break out!
        print("You typed:", answer)

break exits the loop immediately. continue skips to the next iteration.

Dictionaries: labeled storage

A dictionary stores pairs of keys and values. Think of it like a real dictionary: you look up a word (key) to find its definition (value).

Use curly braces {...} with colons between keys and values.


def main():
    # Create a dictionary
    person = {
        "name": "Alice",
        "age": 25,
        "city": "Seattle"
    }
    
    # Access values by key
    print(person["name"])  # Alice
    print(person["age"])   # 25
    
    # Change a value
    person["age"] = 26
    
    # Add a new key-value pair
    person["hobby"] = "coding"
    
    # Print the whole dictionary
    print("Person:", person)

Keys are usually strings (in quotes). Values can be anything: strings, numbers, lists, even other dictionaries!

Getting input: talking with your users

Use input() to ask the user for information. The text you put inside becomes the prompt.

Pro tip: Add input("Press Enter to exit...") at the end of your main() so the window doesn’t close immediately.


def main():
    # Ask the user for their name
    name = input("What's your name? ")
    age = input("How old are you? ")
    
    # Use f-strings to create a personalized message
    message = f"Nice to meet you, {name}! At {age}, you're ready to code!"
    print(message)
    
    # Keep the window open
    input("Press Enter to exit...")

Functions: teaching the computer new tricks

def creates a function. A function can take inputs (parameters) and give back a value with return.

You can call functions:

  • At the top level — runs as the file loads (good for tiny scripts).
  • Inside main() — recommended for full programs.

def make_greeting(person_name):
    # F-strings make this much cleaner!
    message = f"Hello, {person_name}! Welcome to Petroleum!"
    return message

# Top-level call (runs on load):
greeting_message = make_greeting("Ava")
print(greeting_message)

# Structured app entry point:
def main():
    name = input("Enter your name: ")
    other_message = make_greeting(name)
    print(other_message)
    input("Press Enter to exit...")

Scope: a variable created inside a function (like message) lives only inside that function.

Pets: friendly background helpers 🐕

A pet runs a function in the background while your program continues. Start one with pet, get the result with await.


def slow_calculation(value):
    # Imagine this takes a long time
    result = value * value * value
    print(f"Calculated {value}^3 = {result}")
    return result

def main():
    print("Starting background calculations...")
    
    # Start two pets working at the same time
    helper_one = pet slow_calculation(5)
    helper_two = pet slow_calculation(10)
    
    print("Both pets are working! Let's wait for results...")
    
    # Get the results when they're done
    result_one = await helper_one
    result_two = await helper_two
    
    print("Results:", result_one, "and", result_two)
    input("Press Enter to exit...")

Use pets when tasks can happen at the same time (like downloading several pages).

Running your programs: the easy way

Use petroleum run to compile and run your program in one step.


# Save this as hello.pet
def main():
    name = input("What's your name? ")
    print(f"Hello {name}! Welcome to Petroleum!")
    input("Press Enter to exit...")

Then in your terminal:


petroleum run hello.pet

Or compile to an executable:


petroleum compile hello.pet
./hello.exe

petroleum run compiles and runs immediately (perfect for testing!). petroleum compile creates an executable file you can share.

Classes: creating your own types

Classes let you bundle data and behavior together. Use init to set up new objects, and self to access fields.


class Person:
    def init(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hi, I'm {self.name} and I'm {self.age}!"
    
    def have_birthday(self):
        self.age = self.age + 1
        print(f"Happy birthday! Now {self.age} years old.")

def main():
    alice = Person("Alice", 30)
    print(alice.greet())
    alice.have_birthday()

Enums: named constants

Enums define a set of named values. Great for status codes, directions, or anything with fixed options.


enum Status:
    PENDING = 0
    ACTIVE = 1
    COMPLETED = 2

enum Direction:
    NORTH
    SOUTH
    EAST
    WEST

def main():
    current = Status.ACTIVE
    print("Status:", current)
    
    heading = Direction.NORTH
    print("Heading:", heading)

Pattern matching: elegant conditionals

Use match/case for cleaner code when checking multiple values. Use _ as a catch-all.


def http_status(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not Found"
        case 500:
            return "Server Error"
        case _:
            return "Unknown"

def main():
    print(http_status(200))  # OK
    print(http_status(404))  # Not Found
    print(http_status(999))  # Unknown

Error handling: try/except/finally

Use try/except to catch errors gracefully. Add finally for cleanup that always runs.


def divide(a, b):
    if b == 0:
        raise "Cannot divide by zero!"
    return a / b

def main():
    try:
        result = divide(10, 0)
        print("Result:", result)
    except e:
        print("Error:", e)
    finally:
        print("Done!")

The finally block always runs, even if an error occurred.

Mini-project: Personal Greeting Generator

Combine functions, f-strings, user input, and multiple-argument printing to create a friendly greeting program.


def create_greeting(name, age, hobby):
    # Use f-strings to create a personalized message
    greeting = f"""🌟 Welcome to Petroleum, {name}!
    
At {age} years old, you're at a perfect age to learn programming!
I see you enjoy {hobby} - that's awesome!
    
Petroleum will help you build amazing things. Let's code together!"""
    return greeting

def main():
    # Get information from the user
    print("Let's create a personalized greeting for you!")
    name = input("What's your name? ")
    age = input("How old are you? ")
    hobby = input("What's your favorite hobby? ")
    
    # Create and show the greeting
    personal_message = create_greeting(name, age, hobby)
    print(personal_message)
    
    # Show some info using multiple argument printing
    print("Summary - Name:", name, "Age:", age, "Hobby:", hobby)
    
    input("Press Enter to exit...")

Save this as greeting.pet and run it with petroleum run greeting.pet

You’re ready to build!

Now you know what each piece does and why it works. Start small, have fun, and let your pets help you build amazing things.

Back to Home