Python

Python Basics Guide | Getting Started Tutorial

Master Python installation, syntax, loops, conditionals, and functions with practical examples for cross-platform development success

By InventiveHQ Team

Python basics come down to six fundamentals you learn in order: install Python 3, use print() and input() for output and input, store data in variables, branch with if/elif/else, repeat with for and while loops, and package reusable logic into functions defined with def. Python uses indentation instead of curly braces to define code blocks, which forces the readable formatting the language is known for, and Python 3 is the only version you should learn — Python 2 reached end-of-life on January 1, 2020. Master those six building blocks and you can write scripts that read files, make decisions, and automate repetitive work; everything else — classes, web frameworks, data-science libraries — is built on top of them.

That's the summary an AI Overview will give you. What it can't show you is the order those pieces connect in when you actually sit down to run your first program, or how to decide between a for loop and a while loop under pressure. Below is an animated map of the beginner's path from a blank terminal to a running program, a side-by-side loop decision table, and the six-item checklist that separates "watched a tutorial" from "can actually write Python." This comprehensive guide covers installation, syntax, input/output, loops, conditionals, and functions — with the exact commands for each operating system.

The Python Beginner's Path, At A Glance

Every first Python program travels the same four stops: get the interpreter installed, write plain-text code in a .py file, run that file through Python, and read what it prints back. The diagram below animates that loop — the part beginners repeat dozens of times a day.

The four-stop loop of writing and running a Python program Install Python leads to Write code in a .py file, which leads to Run it with python3, which leads to Read the output, which loops back to editing the code. From blank terminal to running program 1. Install Get Python 3 python3 --version 2. Write Save hello.py plain-text code 3. Run Execute the file python3 hello.py 4. Read output See the result fix & repeat edit and run again — the loop you live in

Steps 2 through 4 are the loop you spend your whole career inside: edit code, run it, read the output, edit again. Getting comfortable with that fast feedback cycle matters more than memorizing syntax.

Understanding Python: The Language That Powers Modern Development

Python somewhat fills the need that Java programming was meant to solve—an object-oriented, cross-platform programming language. However, Python's syntax is significantly more readable and beginner-friendly than most other programming languages, making it an ideal choice for both newcomers and experienced developers.

Python Version Overview

  • Python (Original): No longer used in modern development
  • Python 2: Previously most common, but officially deprecated
  • Python 3: Current standard for all new development projects

For new projects, focus exclusively on Python 3, as Python 2 reached end-of-life in 2020. All examples in this guide use Python 3 syntax and best practices.

Installing Python: Platform-Specific Setup Guide

Getting Python installed correctly is crucial for development success. Here's how to install Python 3 on major operating systems.

Ubuntu Linux Installation

# Update package index and install Python 3
sudo apt-get update
sudo apt-get install python3

macOS Installation

Modern macOS (Monterey 12.3 and later) no longer ships any bundled Python at all — Apple removed the old Python 2.7. Install Python 3 with Homebrew for the cleanest development setup:

# Install Python 3 using Homebrew
brew install python3

Windows Installation

For Windows users, download the latest Python 3 installer from python.org or use Chocolatey package manager:

# Install using Chocolatey
choco install python

Python 3.6+ installations will typically be located at C:\python36 or in your user AppData folder when installed for current user only.

Installing Pip: Python Package Manager

Pip is Python's package manager, essential for installing external modules that extend Python's functionality. Modern Python 3 installations typically include pip automatically, but here's how to install it manually if needed:

# Download and install pip
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

Note: Modern Python 3 installations from Homebrew include pip3 automatically. Python 3.4+ from python.org also includes pip by default.

Python Syntax: Understanding Code Structure

Python's syntax differs significantly from languages like C or Java. Instead of using curly braces to define code blocks, Python uses indentation—making your code more readable and eliminating common syntax errors.

Advertisement

Indentation-Based Structure

Compare these equivalent code examples:

// C-style syntax (with braces)
if (a > b) { do_something(); }
# Python syntax (with indentation)
if a > b:
    do_something()

The indented line tells Python that do_something() belongs to the if statement's code block. This approach eliminates unbalanced brace errors and creates more readable code.

Indentation Best Practices

  • Use 4 spaces per indentation level (Python standard)
  • Be consistent throughout your project
  • Avoid mixing tabs and spaces to prevent errors
  • Configure your editor to show whitespace characters

Input and Output Operations

Understanding how to get data into and out of your Python programs is fundamental. Here are the most common input and output methods.

Console Input

# Prompt user for input
name = input("What is your name? ")
print(f"Hello, {name}!")

File Input/Output

# Reading from a file
with open('myfile.txt', 'r') as file:
    content = file.read()
    print(content)

# Writing to a file
with open('output.txt', 'w') as file:
    file.write("Hello, World!")

# Appending to a file
with open('log.txt', 'a') as file:
    file.write("New log entry\n")

Best Practice: Always use the with statement when working with files. It automatically handles file closing, preventing resource leaks and file locks.

Conditional Logic: If, Elif, and Else

Conditional statements allow your programs to make decisions based on different conditions. Python uses if, elif (else if), and else statements. For a complete, example-driven walkthrough — including elif chains, one-line ternary expressions, and the most common mistakes — see our guide to Python if, elif, and else statements.

# Basic conditional logic
x = 10

if x > 15:
    print("Greater than 15")
else:
    print("15 or less")

Elif vs Multiple If Statements

Understanding the difference between elif and multiple if statements is crucial:

# Multiple if statements — each is checked independently
x = 10
if x > 5:
    print("Greater than 5")    # Executes
if x > 8:
    print("Greater than 8")    # Also executes

# An if/elif chain — only the FIRST matching branch runs
if x > 5:
    print("Greater than 5")    # Executes, then the rest are skipped
elif x > 8:
    print("Greater than 8")    # Skipped, even though it is also true

Loops: Automating Repetitive Tasks

Loops allow you to execute the same code multiple times without retyping it. Python provides two main types of loops: for loops and while loops.

For Loops

# Iterating through a file
with open('myfile.txt', 'r') as file:
    for line in file:
        print(line.strip())

# Iterating through a range
for i in range(5):
    print(f"Count: {i}")

# Iterating through a list
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(f"I like {fruit}")

While Loops

# Basic while loop — count from 0 to 9
x = 0
while x < 10:
    print(x)
    x += 1

For vs While: Which Loop Should You Use?

The single most common beginner question about loops is which one to reach for. The rule is about whether you know the count in advance.

SituationUseWhy
Iterating a list, string, or range(n)forYou know exactly what you are looping over; the loop can't run forever
Processing every line in a fileforThe file is a finite, iterable sequence
Repeating until a condition changes (retry, game loop, "keep asking until valid")whileThe number of repeats is unknown until it happens
Doing something a fixed number of timesfor i in range(n)Cleaner and safer than a manual counter
Reading input until the user types "quit"whileYou can't know how many entries they'll make
Which should I default to?forMost real loops iterate a known collection; a for loop cannot accidentally become infinite

The practical danger sign: if you write a while loop, ask "what line makes the condition eventually false?" If you can't point to it, you have an infinite loop. A for loop over a fixed collection removes that risk entirely, which is why it's the safer default.

Functions: Organizing and Reusing Code

Functions allow you to group code into reusable blocks, making your programs cleaner, more maintainable, and less error-prone. In Python, define functions at the top of your files since Python is an interpreted language.

Basic Function Definition

# Simple function with no parameters
def greet():
    print("Hello!")
    print("Welcome to Python")
    print("Happy coding!")

# Call the function
greet()

Functions with Parameters

# Function with parameters
def personalized_greeting(name, language="English"):
    if language == "Spanish":
        print(f"¡Hola, {name}!")
    else:
        print(f"Hello, {name}!")

# Call with different parameters
personalized_greeting("Alice")
personalized_greeting("Carlos", "Spanish")

Return Values

# Function that returns a value
def calculate_area(length, width):
    area = length * width
    return area

# Use the returned value
room_area = calculate_area(12, 10)
print(f"Room area: {room_area} square feet")

The return vs print() trap: these are not interchangeable, and confusing them is the number-one beginner bug. print() shows a value to a human; return hands a value back to your code so it can be reused. A function that only prints its answer gives you back None when you try to store its result. If total = add(2, 3) leaves total as None, it's because add printed the sum instead of returning it.

Have You Actually Learned The Basics? A Self-Check

You've read the material — but reading is not the same as being able to write Python unaided. Use this checklist. If you can do all six from a blank file without looking anything up, you have the fundamentals.

  • Run a program. Save a .py file and run it with python3 yourfile.py, then confirm the output in the terminal.
  • Take input and format output. Read a name with input() and print a greeting using an f-string (f"Hello, {name}").
  • Branch on a condition. Write an if/elif/else chain that responds differently to at least three input ranges.
  • Loop both ways. Write a for loop over a list and a while loop that stops when a condition changes — and explain why each fits its job.
  • Write a function that returns. Define a function with def, give it a parameter and a default, and return a value you then store in a variable.
  • Handle a file safely. Read and write a text file using the with open(...) block, and know why with beats calling .close() yourself.

Anything you can't do yet points you straight at the section above to re-read.

Next Steps: Building Your Python Skills

This guide has covered Python fundamentals: installation, syntax, input/output operations, conditional logic, loops, and functions. These building blocks form the foundation for all Python programming.

Key Takeaways: Python's indentation-based syntax creates readable code, functions promote code reusability, and proper file handling prevents resource issues. Master these fundamentals before advancing to object-oriented programming and external libraries.

Continue practicing with small projects, explore Python's extensive standard library, and gradually introduce external packages using pip. Python's versatility makes it excellent for web development, data analysis, automation, and artificial intelligence applications.

Frequently Asked Questions

What are the basics I need to learn first in Python?

Learn these six fundamentals in order: (1) installing Python 3 and confirming it runs, (2) the print/input functions for output and input, (3) variables and basic data types, (4) if/elif/else conditionals, (5) for and while loops, and (6) defining functions with def. Everything else in Python — classes, libraries, web frameworks — is built on top of these. You do not need object-oriented programming, decorators, or async to write useful scripts.

Should I learn Python 2 or Python 3?

Learn Python 3 exclusively. Python 2 reached official end-of-life on January 1, 2020, receives no security patches, and is missing modern syntax like f-strings. Every new project, tutorial, and library targets Python 3. If you ever see print "hello" without parentheses, you are looking at Python 2 code that will not run on a modern interpreter.

How do I check if Python is already installed?

Open a terminal and run python3 --version (on Windows, try python --version or py --version). If it prints something like Python 3.12.4, Python is installed and ready. If you get "command not found," you need to install it. Do not rely on the bare python command on macOS or Linux — it historically pointed at Python 2 or may not exist at all.

Why does Python use indentation instead of braces?

Python uses indentation to define code blocks because it forces readable, consistently formatted code — the visual structure and the logical structure are always the same. Other languages let you write a correctly-braced block that is indented misleadingly; Python makes that impossible. The rule is four spaces per level (PEP 8), and you must never mix tabs and spaces in the same block or you get an IndentationError.

What is the difference between a for loop and a while loop?

Use a for loop when you know what you are iterating over — a list, a range of numbers, the lines in a file. Use a while loop when you repeat until a condition changes and you do not know the count in advance, such as retrying until a connection succeeds. A for loop over a fixed collection cannot run forever; a while loop can, so always make sure its condition eventually becomes false.

What is pip and do I need it?

pip is Python's package installer — it downloads and installs third-party libraries from the Python Package Index (PyPI) so you do not have to write everything from scratch. It ships with Python 3.4 and newer, so you almost never install it manually. Run pip install requests (or pip3 install requests) to add a library, and use a virtual environment so each project keeps its own dependencies.

What is the difference between print() and return in a function?

print() displays a value on the screen for a human to read; return hands a value back to the code that called the function so the program can use it. A function that only prints cannot be reused in a calculation — total = add(2, 3) needs add to return the sum, not print it. Beginners frequently confuse these and wonder why their variable is None; that happens when a function prints instead of returning.

How long does it take to learn Python basics?

Most beginners can work through installation, syntax, conditionals, loops, and functions in one to two weeks of consistent practice — a few hours per day. Reaching the point where you can build small useful scripts unaided typically takes four to eight weeks. The fundamentals on this page are the "learn once" core; the rest of Python is looking up specific libraries as you need them.

Advertisement