10xdev Book: Programming from Zero to Pro with Python

Chapter 3: Python 3.14 Programming Basics: Syntax, I/O, and Your First Steps

Chapter 3: Python 3.14 Programming Basics: Syntax, I/O, and Your First Steps

Chapter Introduction

Welcome to where the rubber meets the road! With your modern Python 3.14 environment set up, it’s time to learn the fundamental rules – the syntax – that let you communicate with the Python interpreter. We’ll cover how to write basic commands, get information in from the user (Input), display information out (Output), and store data temporarily.


What is “Syntax”?

Think of it like grammar in English. Syntax rules define how you must structure your code so Python understands it. If you mess up the syntax (like forgetting a colon), Python will raise a SyntaxError and stop. Don’t worry, Python 3.14 is actually much better at telling you exactly what went wrong, which is a huge help for beginners!


1. Comments: Your Notes in Code

A comment is text in your code file that Python completely ignores. It’s purely for humans – to explain why you wrote something, leave reminders, or temporarily disable code. Comments start with a hash symbol (#).

# This is a single-line comment. Python ignores it.
print("Hello!") # This part runs, but the comment after it is ignored.
# Use comments to make your code understandable!

Good habit: Comment your code, especially the tricky parts. Your future self will thank you.


2. Your First Command: print() (Output)

The most basic thing you’ll do is display information on the screen. We use the built-in function print() for this. A function is a named block of code that performs a specific task. You “call” it using its name followed by parentheses ().

print("Welcome to Python 3.14!")
print(10 + 5) # You can print the result of calculations too

Whatever you put inside the parentheses is called an argument.


3. Getting User Input: input() (Input)

Most programs need to interact with the user. The input() function pauses your program, displays an optional message (called a prompt), and waits for the user to type something and press Enter.

Crucial point: input() always returns the user’s input as text (a string), even if they type numbers!

user_name = input("Please enter your name: ")
print(f"Hello, {user_name}!") # Using an f-string (more on this soon!)

age_text = input("Enter your age: ")
print(f"You told me your age is: {age_text}")
# print(age_text + 5) # This would CRASH! You can't add text and a number.

4. Storing Data: Variables

Programs need to remember information. We use variables as named containers (or labels) to store values in the computer’s memory.

To create a variable, you use the assignment operator (=).

message = "This is stored in a variable." # Storing text (string)
count = 10                               # Storing a whole number (integer)
price = 19.99                            # Storing a decimal number (float)
is_valid = True                          # Storing a truth value (boolean)

# Now you can use the variable name instead of the value
print(message)
print(count * 2)

Variable Naming Rules (Quick Recap):

  • Start with a letter or underscore (_).
  • Can contain letters, numbers, underscores.
  • Case-sensitive (age is different from Age).
  • Use snake_case (lowercase with underscores) by convention (e.g., user_input, total_cost).

5. Basic Math: Operators

Python acts like a calculator using operators:

Operation Symbol Example Result
Addition + 5 + 3 8
Subtraction - 5 - 3 2
Multiplication * 5 * 3 15
Division / 5 / 3 1.666…
Integer Division // 5 // 3 1
Modulo (Remainder) % 5 % 3 2
Exponentiation ** 5 ** 3 125

6. Converting Types (Type Casting)

Remember how input() gives you text? To do math, you must convert that text to a number type using type casting functions:

  • int(value): Converts to an integer (whole number). Crashes if the text isn’t a whole number.
  • float(value): Converts to a float (decimal number). Crashes if the text isn’t a number.
  • str(value): Converts to a string (text).
age_text = input("Enter your age again: ")

try: # Let's handle potential errors (more in Chapter 9)
    age_number = int(age_text)
    print(f"Next year, you will be {age_number + 1}.")
except ValueError:
    print("That wasn't a valid whole number!")

price_text = input("Enter a price: ")
try:
    price_number = float(price_text)
    print(f"The price plus 10% tax is: {price_number * 1.10:.2f}") # .2f formats to 2 decimals
except ValueError:
    print("That wasn't a valid number!")

7. Formatting Output: F-Strings are King 👑

How do you mix variables smoothly into your printed text? The best way in modern Python is using f-strings. Just put an f before the opening quote and place your variable names inside curly braces {}.

item = "Laptop"
cost = 1200.50

# The f-string way (clean and readable)
print(f"The {item} costs ${cost:.2f}.")

# Older ways (avoid these if you can):
# print("The " + item + " costs $" + str(cost) + ".") # Clumsy concatenation
# print("The {} costs ${:.2f}.".format(item, cost))   # .format() method

F-strings are concise, readable, and powerful – stick with them!


Bonus: The Awesome Python 3.14+ REPL

If you just type python (or python3) in your terminal, you enter the REPL (Read-Eval-Print Loop). It’s like a live Python playground. Starting with Python 3.14, the REPL got major upgrades:

  • Syntax Highlighting: Your code gets colored as you type!
  • Autocomplete: Start typing and press Tab – it suggests completions!

It makes experimenting much more pleasant. Try it out!


🎯 Mini-Project: Trip Cost Calculator (Updated)

Let’s apply these basics to build a simple calculator.

# --- Trip Cost Calculator ---

print("--- Welcome to the Trip Cost Calculator ---")

# 1. Get Inputs (as text)
destination = input("Where are you traveling to? ")
days_str = input(f"How many days will you be in {destination}? ")
hotel_cost_str = input("What's the estimated hotel cost per day? $")
flight_cost_str = input("What's the round-trip flight cost? $")
food_cost_str = input("Estimated food cost per day? $")

try:
    # 2. Convert text inputs to numbers (float for costs, int for days)
    days = int(days_str)
    hotel_cost_per_day = float(hotel_cost_str)
    flight_cost = float(flight_cost_str)
    food_cost_per_day = float(food_cost_str)

    # 3. Calculate total costs
    total_hotel_cost = hotel_cost_per_day * days
    total_food_cost = food_cost_per_day * days
    total_trip_cost = total_hotel_cost + flight_cost + total_food_cost

    # 4. Display Summary using f-strings and formatting
    print("\n--- Your Trip Cost Estimate ---")
    print(f"Destination: {destination}")
    print(f"Duration: {days} days")
    print("-" * 30) # A separator line
    print(f"Flight Cost:      ${flight_cost:>10.2f}") # Right-align price in 10 spaces
    print(f"Total Hotel Cost: ${total_hotel_cost:>10.2f}")
    print(f"Total Food Cost:  ${total_food_cost:>10.2f}")
    print("-" * 30)
    print(f"TOTAL ESTIMATE:   ${total_trip_cost:>10.2f}")

except ValueError:
    print("\nError: Please enter valid numbers for days and costs.")

Chapter Summary

You’ve learned the essential building blocks of Python 3.14:

  • Writing code following Python’s syntax.
  • Using comments (#) for explanations.
  • Displaying output with print().
  • Getting input with input() (and remembering it’s always text!).
  • Storing data in variables (=).
  • Performing basic math operations.
  • Converting between data types (type casting: int(), float(), str()).
  • Creating clean output with f-strings.
  • The interactive REPL is your friend for quick tests.

Storing single pieces of data is essential, but often you need to work with different kinds of data (text vs. numbers vs. true/false). Next, let’s dive deeper into Python’s core data types and how they behave.