Python Hello World

Write and run your first Python program, master print(), take user input, and understand the basics of program structure.

Beginner 7 min read 8 examples

Your First Program

Create a file named hello.py and add this single line:

Python
print("Hello, World!")
Output
Hello, World!

That is a complete, working Python program. No imports, no main function, no semicolons, no class boilerplate required.

Running Python Files

Shell
# 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)

print() accepts any number of arguments separated by commas. It converts each to a string and writes them to standard output.

Python
# 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)
Output
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

Python
# 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.

Python
# 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.")
input() always returns a string

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

Python 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

Python
# 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()
Terminal
$ python3 structured-program.py Alice
Hello, Alice!

$ python3 structured-program.py
Enter your name: Bob
Hello, Bob!

Frequently Asked Questions

print() is Python's built-in function to output text to standard output (the terminal). Unlike JavaScript's console.log(), it is not namespace-qualified because it is a top-level built-in. It can print any object - Python automatically calls str() on non-string arguments. It also supports multiple arguments separated by commas and keyword arguments like sep, end, and file.

When Python runs a file directly, it sets the special variable __name__ to the string "__main__". When the same file is imported as a module, __name__ is set to the module's filename instead. The if __name__ == "__main__": guard lets you write code that only runs when the file is the entry point - not when it is imported. This is the standard way to write executable Python scripts that can also be imported as libraries.

Open Command Prompt or PowerShell, navigate to the folder containing your file, and run python hello.py or py hello.py. If Python is not recognized, it was not added to PATH during installation - reinstall and check "Add Python to PATH". In VS Code, press F5 to run the current file, or use the green play button at the top right with the Python extension installed.

By default, print() adds a newline (\n) after the output. end="" replaces that newline with an empty string, so the next print() continues on the same line. end=" " adds a space instead. This is useful for building output incrementally, printing progress dots, or formatting tabular data.