Python is the most popular programming language in the world — ranked number one on the TIOBE Index (March 2026), used by 58% of developers according to the 2025 Stack Overflow Developer Survey (a 7-percentage-point jump from the year before), and the most-used language on GitHub since 2024. It reads like English, runs everywhere, and powers everything from simple automation scripts to multi-billion-dollar AI systems. If you have never written a single line of code in your life, this is the place to start. By the end of this guide, you will understand variables, data types, operators, conditionals, loops, functions, and basic data structures — and you will have written real, working code at every step along the way.
Programming can feel intimidating at first. The blinking cursor on a blank screen, the unfamiliar syntax, the fear that you will break something. Every developer who ever lived felt that exact hesitation at the start. The secret they all discovered is the same: you learn to code by writing code. Not by reading about it, not by watching someone else do it, but by typing it in yourself, running it, breaking it, and fixing it. This guide is designed to get your hands on the keyboard immediately. Every concept is followed by a code example you should type out and run yourself.
Abelson and Sussman argued that code is written primarily for human readers, with machine execution being almost incidental to that purpose.
Why Python? And How to Get Started
Python was created by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands, with development beginning over Christmas 1989 and the first public release arriving on February 20, 1991. Its name has nothing to do with the snake — van Rossum named it after Monty Python's Flying Circus, the British comedy series he was watching while writing it. That sense of humor is baked into Python's culture: the official documentation uses spam and eggs as example variable names instead of the traditional foo and bar. For a fuller account of the language's trajectory from a Christmas hobby project to global dominance, see how Python became popular.
Python's core design philosophy prizes readability above almost everything else. Where other languages use curly braces and semicolons to structure code, Python uses whitespace and indentation. This means Python code often looks remarkably close to plain English, which is exactly why it has become the go-to language for beginners, data scientists, web developers, cybersecurity professionals, and automation engineers alike. The guiding principles are codified in The Zen of Python — type import this in any Python interpreter to read all 19 of them. The opening line: "Beautiful is better than ugly."
As of March 2026, Python holds the number one position on the TIOBE Index with a 21.25% share, leading second-place C by nearly 10 percentage points. In July 2025, it briefly reached 26.98% — the highest rating any language had achieved in the index's 25-year history. The 2025 Stack Overflow Developer Survey found that 58% of developers use Python — a 7-percentage-point surge from the prior year, the largest single-year jump in the survey's history, driven largely by the explosion in AI and machine learning work. On GitHub, Python overtook JavaScript in 2024 to become the most-used language after a decade of JavaScript dominance, while Jupyter Notebook usage spiked 92% in the same period. Its ecosystem now includes over 760,000 packages on PyPI (the Python Package Index), and the count grows daily. Whether you want to build websites with Django, analyze data with Pandas, train machine learning models with PyTorch, or automate tedious tasks on your computer, Python has a library ready and waiting for you.
Download Python from python.org. During installation on Windows, check the box that says "Add Python to PATH" — this is critical. On macOS and Linux, Python is often pre-installed but may be an older version; install a fresh copy from python.org to be safe. Open a terminal (or Command Prompt on Windows) and type python --version (or python3 --version on macOS/Linux) to confirm it is working. You can write code in any text editor, but VS Code with the Python extension is an excellent free choice for beginners.
Type import this in any Python interpreter and press Enter. You will see all 19 guiding principles of the language, written by Tim Peters in 2004 and formalized as PEP 20. Favorites include "Readability counts," "Explicit is better than implicit," and "There should be one — and preferably only one — obvious way to do it." These aren't rules enforced by the interpreter; they're the philosophy that shapes how Python programmers think about writing good code.
Let us start with the classic first program. Open a terminal, type python (or python3 on macOS/Linux) to enter the interactive interpreter, and type the following:
print("Hello, World!")
When you press Enter, Python will display Hello, World! on the screen. Congratulations — you just wrote your first program. The print() function is one of Python's built-in tools. It takes whatever you put inside the parentheses and displays it as output. Simple, powerful, and something you will use in virtually every Python program you ever write.
"Talk is cheap. Show me the code."
How to Install Python and Write Your First Program
Follow these steps to get Python running on your machine and execute your first line of code. The whole process takes about five minutes.
- Download Python. Go to python.org and download the latest stable version for your operating system. As of early 2026, that is Python 3.14.3 (released February 3, 2026). Python 3.13 is also a fully supported long-term release. Any version 3.10 or later works fine for everything in this guide.
- Run the installer. On Windows, check the box labeled "Add Python to PATH" before clicking Install Now — skipping this step is the single most common beginner mistake. On macOS and Linux, a system Python is often pre-installed, but it may be an older version. Install a fresh copy from python.org to avoid conflicts.
- Verify the installation. Open a terminal (macOS/Linux) or Command Prompt (Windows) and type:
You should see something likepython --versionPython 3.14.3printed back. On macOS or Linux, ifpythonpoints to Python 2, trypython3 --versioninstead — that is the correct command on many Unix-based systems. - Open the Python interpreter. In the same terminal, type
python(orpython3on macOS/Linux) and press Enter. The prompt changes to>>>, indicating the interactive interpreter is ready. - Write your first program. At the
>>>prompt, type the following and press Enter:
Python displaysprint("Hello, World!")Hello, World!. You have written and executed your first program.
For writing longer scripts, use a proper code editor rather than the interactive interpreter. VS Code with the official Python extension is free, has excellent autocomplete, and runs scripts with a single button press. For a full comparison of editors, see our guide to choosing the right IDE for learning Python.
Variables, Data Types, and Operators
A variable is a name that points to a piece of data stored in your computer's memory. Think of it as a labeled container. In Python, you create a variable by simply choosing a name, using the equals sign, and assigning a value. There is no need to declare the type of data ahead of time — Python figures it out automatically through a mechanism called dynamic typing.
# Creating variables
name = "Kandi"
age = 30
height = 5.7
is_student = True
# Displaying them
print(name)
print(age)
print(height)
print(is_student)
In this example, name is a string (text wrapped in quotes), age is an integer (a whole number), height is a float (a decimal number), and is_student is a boolean (either True or False). These four data types form the foundation of nearly everything you will do in Python. You can check the type of any variable using the built-in type() function:
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
Python also gives you a full set of operators for doing math and combining values. Arithmetic operators work exactly the way you would expect from a calculator, with a few extras like floor division and the modulo operator that returns the remainder after division.
# Arithmetic operators
a = 15
b = 4
print(a + b) # 19 (addition)
print(a - b) # 11 (subtraction)
print(a * b) # 60 (multiplication)
print(a / b) # 3.75 (division)
print(a // b) # 3 (floor division, rounds down)
print(a % b) # 3 (modulo, the remainder)
print(a ** b) # 50625 (exponentiation, 15 to the power of 4)
You can also combine strings together using the + operator, and you can mix strings and variables elegantly using f-strings. F-strings were introduced in Python 3.6 via PEP 498 (authored by Eric V. Smith) and are now the standard way to format text output in Python. Prefix any string with f and embed any expression inside curly braces:
# String concatenation and f-strings
first_name = "Python"
last_name = "Learner"
# The old way
greeting = "Hello, " + first_name + " " + last_name + "!"
print(greeting)
# The modern way (f-strings)
greeting = f"Hello, {first_name} {last_name}!"
print(greeting)
# F-strings can contain expressions
price = 19.99
quantity = 3
print(f"Total cost: ${price * quantity:.2f}")
Variable names in Python should be lowercase with underscores separating words (called snake_case). Names like user_age and total_price are considered Pythonic. Avoid starting names with numbers, and never use Python's reserved keywords like print, list, or type as variable names.
Making Decisions with Conditionals
Programs need to make decisions. Should the user be granted access? Is the password correct? Is the temperature above freezing? Python handles decision-making with if, elif (short for "else if"), and else statements. The structure relies on indentation — the code that belongs inside a conditional block must be indented by four spaces (or one tab).
# Basic conditional
temperature = 72
if temperature > 85:
print("It's hot outside! Stay hydrated.")
elif temperature > 65:
print("The weather is nice today.")
elif temperature > 45:
print("It's a bit chilly. Grab a jacket.")
else:
print("It's cold! Bundle up.")
You can also combine conditions using the logical operators and, or, and not. These let you build more complex decision logic in a way that reads almost like natural language:
# Combining conditions
age = 25
has_license = True
has_insurance = True
if age >= 16 and has_license and has_insurance:
print("You are cleared to drive.")
else:
print("You cannot drive yet.")
# Using 'or' and 'not'
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("No alarm needed. Sleep in!")
if not is_weekend:
print("It's a weekday.")
Python also supports comparison operators that return boolean values: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to). Notice that a single = is for assignment while a double == is for comparison — mixing these up is one of the most common beginner mistakes.
Fowler observed that making a computer understand code is easy; the real skill is writing code that other people can understand.
Repeating Actions with Loops
Loops are how you tell Python to repeat an action multiple times. There are two main types: for loops and while loops. A for loop iterates over a sequence of items (like a list, a string, or a range of numbers), executing the indented block of code once for each item. A while loop keeps running as long as a condition remains true. For a thorough treatment of every loop pattern in the language, see the Python loops guide on this site.
# For loop with range
for i in range(5):
print(f"Iteration number: {i}")
# Output: 0, 1, 2, 3, 4
# For loop over a list
languages = ["Python", "JavaScript", "Rust", "Go"]
for language in languages:
print(f"I want to learn {language}")
# For loop over a string
for letter in "Python":
print(letter)
The range() function is your best friend for generating sequences of numbers. Calling range(5) produces the numbers 0 through 4. You can also specify a start, stop, and step: range(2, 20, 3) generates 2, 5, 8, 11, 14, 17.
# While loop
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Don't forget this, or the loop runs forever!
# Practical example: simple countdown
import time
countdown = 5
while countdown > 0:
print(f"Launching in {countdown}...")
countdown -= 1
time.sleep(1)
print("Liftoff!")
A while loop that never has its condition become False will run forever (an infinite loop). Always make sure your loop has a clear exit condition. If you accidentally create one, press Ctrl + C in the terminal to stop it.
Python also provides break and continue keywords for finer control inside loops. break exits the loop entirely, while continue skips the rest of the current iteration and jumps to the next one:
# Using break and continue
for number in range(1, 20):
if number == 13:
print("Skipping unlucky 13!")
continue
if number > 15:
print("Stopping at 15.")
break
print(f"Number: {number}")
The function below is supposed to print every even number from 2 to 10. It runs without crashing, but the output is wrong. Can you find the problem?
def print_evens():
for i in range(1, 11):
if i % 2 = 0:
print(i)
print_evens()Organizing Code with Functions
As your programs grow, you will quickly discover that copying and pasting the same code in multiple places creates a mess. Functions solve this problem by letting you wrap a block of code in a reusable package, give it a name, and call it whenever you need it. You define a function with the def keyword:
# Defining and calling a function
def greet(name):
"""Display a personalized greeting."""
print(f"Welcome to Python, {name}!")
greet("Kandi")
greet("Reader")
greet("World")
Functions can accept multiple parameters, return values, and even have default values for parameters that the caller may or may not provide:
# Function with return value and default parameter
def calculate_tip(bill_amount, tip_percent=18):
"""Calculate the tip and total for a restaurant bill."""
tip = bill_amount * (tip_percent / 100)
total = bill_amount + tip
return tip, total
# Using the function
my_tip, my_total = calculate_tip(85.50)
print(f"Tip: ${my_tip:.2f}")
print(f"Total: ${my_total:.2f}")
# Overriding the default
my_tip, my_total = calculate_tip(85.50, 25)
print(f"Generous total: ${my_total:.2f}")
Notice the triple-quoted string right below the def line. That is called a docstring, and it documents what your function does. It is a Python best practice to include docstrings in every function you write. You can view a function's docstring at any time by calling help(calculate_tip) in the interpreter.
Kernighan and Plauger warned that debugging is harder than writing code, so writing maximally clever code leaves you unable to debug it.
Working with Lists and Dictionaries
So far, each variable has held a single value. But what if you need to store a collection of items? Python gives you powerful built-in data structures for this. The two most important ones for beginners are lists and dictionaries.
A list is an ordered, changeable collection of items enclosed in square brackets. Lists can hold any data type, and you can mix types within the same list (though it is usually cleaner to keep them consistent):
# Creating and manipulating lists
fruits = ["apple", "banana", "cherry", "date"]
# Accessing items by index (starts at 0)
print(fruits[0]) # apple
print(fruits[-1]) # date (last item)
# Adding and removing items
fruits.append("elderberry")
fruits.insert(1, "blueberry")
fruits.remove("cherry")
print(fruits)
# Slicing a list
print(fruits[1:3]) # ['blueberry', 'banana']
# List comprehension (a Pythonic shortcut)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(f"Even numbers: {evens}")
# Useful list operations
print(f"Length: {len(fruits)}")
print(f"Sorted: {sorted(fruits)}")
A dictionary is an ordered collection of key-value pairs, enclosed in curly braces. Dictionaries are guaranteed to preserve insertion order as of Python 3.7 — first as a CPython implementation detail in 3.6, then officially guaranteed by the language spec in 3.7. Dictionaries are extraordinarily useful for representing structured data where each piece of information has a label:
# Creating and using dictionaries
student = {
"name": "Kandi",
"major": "Cybersecurity",
"gpa": 3.85,
"courses": ["Python 101", "Network Security", "Ethical Hacking"]
}
# Accessing values by key
print(student["name"])
print(student["courses"])
# Adding and updating entries
student["graduation_year"] = 2026
student["gpa"] = 3.90
# Looping through a dictionary
for key, value in student.items():
print(f"{key}: {value}")
# Checking if a key exists
if "major" in student:
print(f"Major found: {student['major']}")
Use the .get() method instead of square brackets when you are not sure a key exists: student.get("phone", "Not on file") returns the default value instead of crashing your program with a KeyError.
Putting It All Together: A Mini Project
The best way to cement what you have learned is to build something. Here is a small but complete program that combines variables, input, conditionals, loops, functions, lists, and dictionaries into a working password strength checker:
def check_password_strength(password):
"""Analyze a password and return a strength rating."""
score = 0
feedback = []
# Check length
if len(password) >= 12:
score += 2
elif len(password) >= 8:
score += 1
else:
feedback.append("Use at least 8 characters")
# Check for uppercase letters
if any(char.isupper() for char in password):
score += 1
else:
feedback.append("Add uppercase letters")
# Check for lowercase letters
if any(char.islower() for char in password):
score += 1
else:
feedback.append("Add lowercase letters")
# Check for digits
if any(char.isdigit() for char in password):
score += 1
else:
feedback.append("Add numbers")
# Check for special characters
special_chars = "!@#$%^&*()_+-=[]{}|;:',.<>?/~`"
if any(char in special_chars for char in password):
score += 1
else:
feedback.append("Add special characters")
# Determine rating
ratings = {0: "Very Weak", 1: "Weak", 2: "Weak",
3: "Fair", 4: "Strong", 5: "Strong",
6: "Very Strong"}
rating = ratings.get(score, "Very Strong")
return rating, score, feedback
# Main program loop
print("=== Password Strength Checker ===\n")
while True:
user_input = input("Enter a password to check (or 'quit' to exit): ")
if user_input.lower() == "quit":
print("Goodbye!")
break
rating, score, tips = check_password_strength(user_input)
print(f"\nRating: {rating} ({score}/6)")
if tips:
print("Suggestions for improvement:")
for tip in tips:
print(f" - {tip}")
else:
print("Excellent! Your password meets all criteria.")
print()
This small project uses almost every concept covered in this tutorial. The function receives a string, analyzes it with conditionals and loops, stores results in a list and a dictionary, and returns multiple values. The main program uses a while loop with break to let the user check multiple passwords before exiting. Take the time to type it out line by line, run it, and experiment with changes.
If cybersecurity is where you want to take your Python skills, the logic patterns in this project — iterating over character data, scoring against criteria, building feedback lists — are exactly the same patterns used in real-world threat analysis and security tooling. Python's role in offensive and defensive security is substantial, and everything you have learned in this guide is directly transferable.
Ritchie held that learning a programming language requires actually writing programs in it — there is no substitute.
Key Takeaways and Next Steps
- Python reads like English: Its clean syntax and indentation-based structure make it the most accessible language for beginners. You learned to print output, store data in variables, and use f-strings for formatting.
- Control flow is straightforward: Conditionals (
if/elif/else) let your programs make decisions, and loops (forandwhile) let them repeat actions efficiently. - Functions keep your code organized: By wrapping reusable logic in functions with clear names and docstrings, you write code that is easier to read, test, and maintain.
- Lists and dictionaries are essential: These two data structures will appear in virtually every Python program you write. Master them early, and everything else becomes easier.
- Build projects to learn: Reading tutorials gives you knowledge, but building real programs gives you skill. Start small, break things, fix them, and gradually increase complexity.
From here, your next steps should include learning about file handling (reading and writing files with open()), error handling with try/except blocks, working with modules and packages from the Python standard library, and exploring object-oriented programming with classes. Each of these topics builds naturally on the foundation you have built today. Picking a specific domain will sharpen your skills faster than any tutorial — build a small web app with Flask, explore data with Pandas, or automate a task you actually do every day. The official Python Tutorial at docs.python.org is free, authoritative, and an excellent next read. The most important thing is to keep writing code every single day, even if it is just a few lines. Consistency beats intensity in programming, just as it does in everything else worth learning.
Einstein attributed his success less to raw intelligence than to his willingness to keep working on difficult problems longer than others would.
Python is not just a language — it is a gateway. It opens doors to web development, data science, artificial intelligence, cybersecurity, automation, and dozens of other fields. Whatever drew you to programming in the first place, Python has the tools to take you there. The journey of a thousand programs begins with a single print(). You have already taken that step. Keep going.
Frequently Asked Questions
fruits[0]. A dictionary is a collection of key-value pairs accessed by a named key, such as student["name"]. As of Python 3.7, dictionaries preserve insertion order. Use a list when order matters and items do not have labels; use a dictionary when each piece of data has a meaningful name.python command for legacy compatibility, even though Python 2 is end-of-life. Use python3 to explicitly invoke Python 3 on these systems. After installing a fresh copy from python.org, you can verify with python3 --version. On Windows, a fresh python.org installer maps python directly to Python 3.open()), error handling with try/except blocks, working with modules and the Python standard library, and object-oriented programming with classes. From there, picking a domain — web development with Flask or Django, data analysis with Pandas, or automation with the os and pathlib modules — will sharpen your skills faster than any additional tutorial.IndentationError and refuses to run the code. This is deliberate. By forcing structure through whitespace, Python guarantees that code looks the same regardless of who wrote it, which makes it dramatically easier to read and understand. A practical rule: never mix tabs and spaces. Configure your editor to insert 4 spaces when you press Tab, and you will never hit this problem.print() displays a value on the screen for a human to read — it produces output, but that value cannot be used elsewhere in your program. return sends a value back from a function so that other parts of your program can use it. For example, if a function calculates a total and uses print(total), only the screen sees that number. If it uses return total, the calling code receives the number and can store it in a variable, pass it to another function, or use it in a calculation. A good rule of thumb: use return inside functions when you need the result, and use print() when you want to show something to the user.# symbol starts a comment. Python ignores everything on a line after a #, so comments are notes for humans — not instructions for the interpreter. They explain why the code does what it does, flag areas that need attention, or temporarily disable a line during testing. For example: score = score + 1 # award one point. Comments are not optional decoration; they are part of writing code that other people (and your future self) can understand. The only rule is to keep them accurate — an outdated comment that contradicts the code is worse than no comment at all.