Your First Program
Create a file named hello.py and add this single line:
print("Hello, World!")
Hello, World!
That is a complete, working Python program. No imports, no main function, no semicolons, no class boilerplate required.
Running Python Files
# Navigate to the folder containing hello.py
cd ~/projects/my-first-python
# Run the file
python3 hello.py # macOS / Linux
python hello.py # Windows (if Python 3 is the default)
py hello.py # Windows py launcher (most reliable)
# Run a one-liner without a file (-c flag)
python3 -c "print('Hello from command line')"
# In VS Code: open the file and press F5 (or Ctrl+F5 to run without debug)
The print() Function
print() accepts any number of arguments separated by commas. It converts each to a string and writes them to standard output.
# Basic print
print("Hello, World!") # Hello, World!
print(42) # 42
print(3.14) # 3.14
print(True) # True
# Multiple arguments - separated by space by default
print("Name:", "Alice", "Age:", 30) # Name: Alice Age: 30
# sep - change the separator
print("2024", "06", "15", sep="-") # 2024-06-15
print("a", "b", "c", sep=", ") # a, b, c
# end - change what is appended after (default is "\n")
print("Loading", end="")
print("...", end="")
print(" done")
# Loading... done (all on one line)
# Print empty line
print()
# f-string (the modern way to format output)
name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")
# Hello, Alice! You are 30 years old.
# print to stderr (useful for error messages)
import sys
print("Error: file not found", file=sys.stderr)
Hello, World! 42 3.14 True Name: Alice Age: 30 2024-06-15 a, b, c Loading... done Hello, Alice! You are 30 years old.
Comments
# Single-line comment - starts with #
# Everything after # on the same line is ignored
x = 5 # inline comment - after code on the same line
# Multi-line comments - use consecutive # lines
# This is line 1 of a longer explanation
# This is line 2
# This is line 3
# Docstrings - triple-quoted strings used to document functions/classes
def greet(name):
"""Return a greeting string for the given name."""
return f"Hello, {name}!"
# Docstrings are accessible at runtime via __doc__
print(greet.__doc__) # Return a greeting string for the given name.
# Triple-quoted strings can span multiple lines (used as multi-line docstrings)
def calculate_area(width, height):
"""
Calculate the area of a rectangle.
Args:
width: The width of the rectangle.
height: The height of the rectangle.
Returns:
The area as a float.
"""
return width * height
User Input with input()
input() pauses the program and waits for the user to type something. It always returns a string.
# input() always returns a string
name = input("What is your name? ")
print(f"Hello, {name}!")
# Convert to int or float for numeric input
age_str = input("How old are you? ")
age = int(age_str) # convert string to integer
print(f"In 10 years you will be {age + 10}.")
# Shorthand - convert in one line
height = float(input("Enter your height in meters: "))
print(f"Height: {height}m")
# Always validate user input in real programs
try:
count = int(input("Enter a number: "))
print(f"You entered: {count}")
except ValueError:
print("That was not a valid number.")
A common mistake is using input() for math without converting: x = input("Number: "); print(x + 1) raises a TypeError because you cannot add an integer to a string. Always convert with int() or float() when expecting numbers.
Using the REPL
$ python3
>>> # Expressions are evaluated and printed automatically
>>> 2 + 2
4
>>> "hello".upper()
'HELLO'
>>> # Assign variables - they persist in the session
>>> x = 10
>>> x * 3
30
>>> # _ holds the last result
>>> 5 * 5
25
>>> _ + 1
26
>>> # Multi-line code - use ... continuation
>>> for i in range(3):
... print(i)
...
0
1
2
>>> # Exit
>>> exit() # or Ctrl+D
Basic Program Structure
# 1. Imports (standard library first, then third-party, then local)
import os
import sys
# 2. Constants (UPPER_SNAKE_CASE by convention)
MAX_RETRIES = 3
DEFAULT_NAME = "World"
# 3. Functions and classes
def greet(name=DEFAULT_NAME):
"""Print a greeting."""
print(f"Hello, {name}!")
def main():
"""Entry point of the program."""
if len(sys.argv) > 1:
name = sys.argv[1] # command-line argument
else:
name = input("Enter your name: ")
greet(name)
# 4. Entry point guard - runs only when executed directly, not when imported
if __name__ == "__main__":
main()
$ python3 structured-program.py Alice Hello, Alice! $ python3 structured-program.py Enter your name: Bob Hello, Bob!