Ch 1.4 Your First Python Program
With your Python development environment set up, let's write your first piece of code. Starting from the traditional "Hello, World!", you will learn about input and output as well as the basic structure of a Python program.
1. Hello World
print("Hello, World!")
It runs in just one line. Save the file as hello.py and run it from the terminal.
python3 hello.py
# Hello, World!
Comparing with Java or C shows just how concise Python is.
# Python — 1 line
print("Hello, World!")
# Java — requires 5 lines
# public class Hello {
# public static void main(String[] args) {
# System.out.println("Hello, World!");
# }
# }
2. Python Code Structure
Indentation Is Syntax
In Python, indentation is not just a style choice — it is part of the syntax. Code will not run without consistent indentation.
# Correct indentation (4 spaces recommended)
if True:
print("This is inside the if block")
print("Same indentation = same block")
print("This is outside the if block")
# Incorrect indentation — causes IndentationError
# if True:
# print("Error!") # IndentationError: expected an indented block
No Semicolons Required
Python does not require a semicolon (;) at the end of a line. A newline signals the end of a statement.
# Normal code
x = 10
y = 20
z = x + y
# Semicolons are allowed but not recommended
a = 1; b = 2; c = 3 # Occasionally used to write multiple statements on one line
Comments
# Single-line comment: use the # symbol
x = 10 # Inline comments are also possible
"""
Multi-line comment or documentation string (docstring).
Technically a string, but commonly used for documentation purposes.
"""
def add(a, b):
"""Adds two numbers and returns the result.""" # docstring
return a + b
3. Multiple Ways to Output
The print() function supports a variety of parameters.
# Basic output
print("Hello, Python!")
# Output multiple values (default separator: space)
print("apple", "banana", "strawberry")
# apple banana strawberry
# sep — change the separator
print("2024", "01", "15", sep="-")
# 2024-01-15
print("Name", "Age", "Job", sep=" | ")
# Name | Age | Job
# end — change the end character (default: '\n')
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")
# Loading...
# file — change the output destination
import sys
print("Error message", file=sys.stderr)
# flush — flush the buffer immediately (useful for progress displays)
import time
for i in range(5):
print(f"\rProgress: {i * 20}%", end="", flush=True)
time.sleep(0.3)
print("\rDone! ")
4. Getting User Input
Use the input() function to receive a string from the user.
# Basic input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# input() always returns a string (str)
age_str = input("Enter your age: ")
print(type(age_str)) # <class 'str'>
# Convert to a number when needed
age = int(age_str)
print(f"Next year you will be {age + 1}.")
# Handle in one line
height = float(input("Enter your height (cm): "))
print(f"Height: {height:.1f}cm")
5. Simple Calculator Example
A complete program that takes two numbers from the user and performs basic arithmetic.
def calculator():
"""Simple four-function calculator"""
print("=== Python Calculator ===")
# Get input
try:
num1 = float(input("First number: "))
num2 = float(input("Second number: "))
except ValueError:
print("Error: Please enter a valid number.")
return
# Choose operation
print("\nSelect operation:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
choice = input("Choice (1-4): ")
# Calculate result
if choice == "1":
result = num1 + num2
operator = "+"
elif choice == "2":
result = num1 - num2
operator = "-"
elif choice == "3":
result = num1 * num2
operator = "*"
elif choice == "4":
if num2 == 0:
print("Error: Cannot divide by zero.")
return
result = num1 / num2
operator = "/"
else:
print("Invalid choice.")
return
# Display result
print(f"\n{num1} {operator} {num2} = {result}")
calculator()
6. The if __name__ == "__main__": Pattern
A Python file can be run directly or imported by another file. This pattern distinguishes between the two cases.
# calculator.py
def add(a: float, b: float) -> float:
"""Adds two numbers."""
return a + b
def multiply(a: float, b: float) -> float:
"""Multiplies two numbers."""
return a * b
def main():
"""Main execution function"""
print(f"3 + 4 = {add(3, 4)}")
print(f"3 * 4 = {multiply(3, 4)}")
if __name__ == "__main__":
# main() is called only when this file is run directly
# It does NOT run when imported with: import calculator
main()
# When importing from another file, main() does not run automatically
import calculator
result = calculator.add(10, 20) # Only functions are available
print(result) # 30
Output:
# When run directly
python3 calculator.py
# 3 + 4 = 7
# 3 * 4 = 12
# When imported
# main() does not run; only functions are available for use
Print debugging is quick but not suitable for production code. In professional work, use the logging module.
import logging
# Logging configuration
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
def process_data(data: list) -> list:
logger.debug(f"Input data: {data}")
result = [x * 2 for x in data]
logger.info(f"Processing complete: {len(result)} items")
return result
data = [1, 2, 3, 4, 5]
output = process_data(data)
# 2024-01-15 10:30:00 [DEBUG] Input data: [1, 2, 3, 4, 5]
# 2024-01-15 10:30:00 [INFO] Processing complete: 5 items
Use the pprint module to display complex data structures in a readable format.
from pprint import pprint, pformat
data = {
"users": [
{"id": 1, "name": "Alice", "roles": ["admin", "user"]},
{"id": 2, "name": "Bob", "roles": ["user"]},
],
"total": 2,
}
# Regular print — outputs on one line, hard to read
print(data)
# pprint — displays with indentation for readability
pprint(data)
# {'total': 2,
# 'users': [{'id': 1, 'name': 'Alice', 'roles': ['admin', 'user']},
# {'id': 2, 'name': 'Bob', 'roles': ['user']}]}
# Convert to a formatted string
formatted = pformat(data, indent=2)
print(formatted)
You have learned basic input and output with print() and input(). The next chapter covers virtual environments and package management to help you structure a professional Python project.