How to Use Python: Your First Steps

How to Use Python: Your First Steps

by Leodanis Pozo Ramos Publication date Oct 13, 2025 Reading time estimate 1h 11m basics python

If you’re starting fresh with programming and wondering how to use Python, this tutorial will give you the foundation you need to get started with Python step by step. You’ll learn how to install Python, run your first program, and understand the language’s clear syntax.

You’ll also explore variables, loops, functions, classes, and error handling while discovering tools, coding style, and libraries that help you write effective Python code from day one.

By the end of this tutorial, you’ll understand that:

  • You can install Python on Windows, macOS, and Linux using binaries, package managers, or distributions like Anaconda.
  • You can use the Python REPL to experiment interactively before writing full scripts, modules, and projects.
  • Built-in data types like strings, lists, dictionaries, and sets provide powerful ways to structure information.
  • You can handle errors with syntax checks, exceptions, and debugging practices to keep your code running smoothly.
  • Tools like editors, integrated development environments (IDEs), and AI assistants can boost your productivity when writing Python code.

You’ll go through your first steps with clear examples so that you can start coding in Python confidently and build on solid ground.

Take the Quiz: Test your knowledge with our interactive “How to Use Python: Your First Steps” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Use Python: Your First Steps

Review the basics of Python with this quiz. Practice syntax, keywords, variables, errors, and tools every beginner should know.

Why Should You Use Python?

The Python Logo. The Python logo is a trademark of the Python Software Foundation.

Python is a high-level, interpreted, interactive, and object-oriented programming language that’s a great choice as a first language because its code reads like English. It’s flexible, powerful, and allows you to do many things, both big and small.

With Python, you can write basic programs and scripts, as well as create complex and large-scale enterprise solutions. Here’s a sampling of its uses:

You’ll find Python across many high-traffic websites. For example, Reddit is written in Python. Dropbox’s earliest prototypes were in Python, and it remains central there. YouTube uses Python among its back-end languages. Meanwhile, Instagram runs on Django, and Pinterest has historically used Python with a modified Django stack.

Python offers many features that make it attractive as your first programming language:

  • Readable, beginner-friendly syntax: Python’s design favors code readability, so you spend more time learning programming ideas and less time fighting syntax.
  • Accessible: People of all ages, from school children to retirees, have learned Python, and so can you.
  • Batteries included: The standard library ships with modules for file processing, networking, mathematics, date and time processing, testing, and more.
  • Large community and abundant resources: There’s a vast ecosystem of tutorials, videos, forums, and local meetups for every topic and skill level.
  • Proven in the real world: From startups to enterprises and research labs, Python powers production systems, data pipelines, and AI tooling across industries.
  • Versatile and scalable: It can be used for quick scripts and automation, as well as web applications, data analysis, machine learning, and even game development.
  • Free and cross-platform: Python runs on Windows, macOS, and Linux, and it’s free for both personal and commercial use.
  • Open source: Python source code is publicly available under the Python Software Foundation License Version 2, which grants broad rights to use, modify, and distribute, including in proprietary software. Additionally, anyone can contribute to its development.

Compared to other programming languages, Python offers several key features:

  • Interpreted: It’s portable and quicker to experiment with than compiled languages.
  • Multiparadigm: It lets you write code in different styles, including object-oriented, imperative, and functional.
  • Dynamically typed: It checks variable types at runtime, so you don’t need to declare them explicitly.
  • Strongly typed: It won’t let unsafe operations on incompatible types go unnoticed.

There’s a lot more to learn about Python. But by now, you should have a better idea of why Python is so popular and why you should consider learning to program with it.

How Do You Install and Run Python?

Before you can learn how to use Python, you need to install it. Python works on Linux, macOS, Windows, and several other platforms. You can download and install the latest version from the official download page. You also have the option to install and use different Python versions for different projects.

To check what Python version has been installed globally on your operating system, open the terminal or command line and run the following:

Windows PowerShell
PS> py -V
Shell
$ python3 -V

This command prints the version of your system’s default Python installation. Note that on macOS and Linux, you’ll typically run the interpreter with python3. On many systems, python now also points to Python 3, but this isn’t always guaranteed, especially on Linux. If python isn’t found or starts the wrong version, then use python3 instead.

Install Python From Binaries

Regardless of your operating system, you can download an appropriate version of Python from the official site. Go there and select the appropriate 32-bit or 64-bit version for your operating system and processor.

Selecting and downloading a Python binary from the language’s official site is often a good choice. However, there are some OS-specific alternatives:

  • macOS: You have the option of installing Python from Homebrew.
  • Linux: You can install several Python versions using your distribution’s package manager.
  • Windows: You can install Python from the Microsoft Store on Windows 10 and later versions. Before doing so, make sure the publisher is the Python Software Foundation (PSF). After installation, Python, pip, and IDLE will be available.

You can also use the Anaconda distribution to install Python with a rich set of packages and libraries, or you can use Miniconda to install only the packages you need.

Once you’ve installed Python on your system using your preferred method, you can start using the Python interpreter in interactive mode.

Run the Python Interpreter

You can do a quick test to ensure Python is installed correctly. Open your terminal or command line and run the python3 command. This will start a Python interactive session, also known as the REPL. Your command prompt should look similar to this:

Shell
$ python3
Python 3.13.7 (main, Aug 22 2025, 19:20:01) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

While you’re in this interactive session, you can run your first line of code:

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

When you press Enter, Python prints Hello, World! to the screen. That’s it! You’ve just written your first Python program in an interactive session!

You can use exit() or quit() to leave a Python interactive session and return to the system shell. If you’re using Python 3.13 or later, then you can also use the exit and quit commands (no parentheses) to leave the REPL.

Alternatively, you can use the following key combinations to finish a session:

  • Ctrl+D on macOS and Linux
  • Ctrl+Z and Enter on Windows

Keep your terminal or command line open. You still have more to do and learn! You’ll start with the basics of Python syntax.

How to Use Python: What’s the Basic Syntax?

The Python syntax is clear, concise, and focused on readability. Readability is arguably one of the most appealing features of the language itself. It makes Python ideal for those learning to program. In this section, you’ll learn about several key components of Python syntax:

In the following sections, you’ll learn the essentials of Python’s syntax. With this knowledge, you’ll understand the basics of how to use Python to write real programs.

Comments

Comments are pieces of text that live in your code but are ignored by the Python interpreter as it executes the code. You can use comments to quickly document certain parts of your code so that other developers can understand what the code does or why it’s written a certain way.

To write a comment in Python, just add a hash mark (#) before your comment text:

Python Syntax
# This is a comment on its own line

The Python interpreter ignores the text after the hash mark up to the end of the line.

You can also add inline comments to your code. In other words, you can combine a Python expression or statement with a comment in a single line, given that the comment is at the end of the line:

Python Syntax
greeting = "Hello, World!"  # This is an inline comment

You should use inline comments sparingly to clear up pieces of code that aren’t obvious on their own.

In practice, your comments should be short and to the point. PEP 8 advises keeping comments at 72 characters or less. If your comment is approaching or exceeding that length, then you might want to spread it out over multiple lines:

Python Syntax
# This is a long comment that requires
# two lines to be complete.

If you need more room for a comment, then you can use multiple lines with a hash mark on each. This way, you can keep your comments under 72 characters.

Variables

In Python, variables are names attached to a particular object. They hold a reference, or pointer, to the memory address at which an object is stored. Once you assign an object to a variable, you can access the object using that variable name.

To use a Python variable in your code, you need to define it in advance. Here’s the syntax:

Python Syntax
variable_name = variable_value

You should use a naming scheme that makes your variables intuitive and readable. The variable name should provide some indication as to what the values assigned to it are.

Sometimes programmers use short variable names, such as x and y. These are perfectly suitable names in the context of math, algebra, and so on. In other contexts, you should avoid single-character names and use something more descriptive. That way, other developers can make an educated guess of what your variables hold. Think of others and your future self when writing your programs. Your future self will thank you.

Here are some examples of valid and invalid variable names in Python:

Python
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers
[1, 2, 3, 4, 5]

>>> first_num = 1
>>> first_num
1

>>> π = 3.141592653589793
>>> π
3.141592653589793

>>> 1rst_num = 1
  File "<python-input-6>", line 1
    1rst_num = 1
    ^
SyntaxError: invalid decimal literal

Your variable names can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (_). In summary, variable names should be alphanumeric, but note that even though variable names can contain digits, their first character can’t be a digit.

Python offers full Unicode support, so you can also use Unicode characters in your variable names, such as the π variable shown above. However, while Python permits Unicode characters in identifiers, most style guides (including PEP 8) recommend sticking to ASCII letters, digits, and underscores for variable names. This helps avoid confusion, tooling issues, and potential security pitfalls.

Keywords

Like any other programming language, Python has a set of special words that are part of its syntax. These words are known as keywords. To get the complete list of keywords available in your current Python installation, you can run the following code in an interactive session:

Python
>>> help("keywords")

Here is a list of the Python keywords. Enter any keyword to get more help.

False               class               from                or
None                continue            global              pass
True                def                 if                  raise
and                 del                 import              return
as                  elif                in                  try
assert              else                is                  while
async               except              lambda              with
await               finally             nonlocal            yield
break               for                 not

Each of these keywords plays a role in Python syntax. They have specific meanings and purposes in the language, so you shouldn’t use them for anything but those specific purposes. For example, you shouldn’t use them as variable names in your code. In fact, Python will prevent this by raising a syntax error if you try.

Python also has what’s known as soft keywords. These are keywords that retain their meaning only in specific contexts. Unlike normal keywords, you can use soft keywords as identifiers if needed.

Here’s how you can access the whole list of Python keywords and soft keywords:

Python
>>> import keyword

>>> keyword.kwlist
[
    'False',
    'None',
    'True',
    'and',
    ...
    'yield'
]

>>> keyword.softkwlist
['_', 'case', 'match', 'type']

The keyword module provides objects and functions that allow you to work with Python keywords. For example, keyword.kwlist and keyword.softkwlist hold lists of all the current keywords and soft keywords in Python.

Built-in Data Types

Python has a handful of built-in data types, such as numbers (integers, floats, and complex numbers), Booleans, strings, bytes, lists, tuples, dictionaries, and sets.

You can manipulate the built-in data types using different tools. Here are some of them:

In the following sections, you’ll learn how to use Python’s built-in data types, including numbers, Booleans, strings, bytes, lists, tuples, dictionaries, and sets, with quick practical examples.

Numbers

Python provides integers, floating-point numbers, and complex numbers. Integers and floating-point numbers are the most commonly used numeric types in day-to-day programming, while complex numbers have specific use cases in math and science.

Here’s a summary of their more relevant features:

Number Description Examples Data Type
Integer Whole numbers 1, 2, 42, 476, -99999 int
Floating-point Numbers with decimal points 1.0, 2.2, 42.09, 476.1, -99999.9 float
Complex Numbers with a real part and an imaginary part complex(1, 2), complex(-1, 7), complex("1+2j") complex

Integer numbers have unlimited precision. The precision information for floating-point numbers is available in sys.float_info. Complex numbers have a real and an imaginary part, which are both floating-point numbers.

When you combine math operators with numbers, you form expressions that Python can evaluate. Arithmetic operators represent common operations such as addition, subtraction, multiplication, division, and so on:

Python
>>> # Addition
>>> 5 + 3
8

>>> # Subtraction
>>> 5 - 3
2

>>> # Multiplication
>>> 5 * 3
15

>>> # True division
>>> 5 / 3
1.6666666666666667

>>> # Floor division
>>> 5 // 3
1

>>> # Modulus (returns the remainder from division)
>>> 5 % 3
2

>>> # Power
>>> 5 ** 3
125

These operators work with two operands. The operands can be numbers or variables that point to numbers.

Besides operators, Python provides built-in functions that allow you to manipulate numbers. These functions are always available to you. In other words, you don’t have to do anything to use them in your programs.

Consider the float() function. Given an integer number or a string representing a number, float() returns a floating-point number:

Python
>>> # Integer numbers
>>> float(9)
9.0
>>> float(-99999)
-99999.0

>>> # Strings representing numbers
>>> float("2")
2.0
>>> float("-200")
-200.0
>>> float("2.25")
2.25

>>> # Complex numbers
>>> float(complex(1, 2))
Traceback (most recent call last):
    ...
TypeError: float() argument must be a string or a real number, not 'complex'

With float(), you can convert integer numbers and strings representing numbers into floating-point numbers, but you can’t convert a complex number into a floating-point number.

Similarly, int() returns an integer when you call it with a floating-point number or a string as an argument. This function doesn’t round a float input up to the nearest integer. Instead, it truncates the input, throwing out anything after the decimal point, and returns the resulting integer. For example, an input of 10.6 returns 10 instead of 11. Likewise, 3.25 returns 3:

Python
>>> # Floating-point numbers
>>> int(10.6)
10
>>> int(3.25)
3

>>> # Strings representing numbers
>>> int("2")
2
>>> int("2.3")
Traceback (most recent call last):
    ...
ValueError: invalid literal for int() with base 10: '2.3'

>>> # Complex numbers
>>> int(complex(1, 2))
Traceback (most recent call last):
    ...
TypeError: int() argument must be a string, a bytes-like object
⮑ or a real number, not 'complex'

Note that you can pass a string representing an integer to int(), but you can’t pass a string representing a floating-point number. Complex numbers don’t work either.

Besides these built-in functions, there are a few methods associated with each numeric type. You can access them through attribute references using dot notation:

Python
>>> 10.0.is_integer()
True
>>> 10.2.is_integer()
False

>>> (10).bit_length()
4
>>> 10.bit_length()
  File "<python-input-3>", line 1
    10.bit_length()
      ^
SyntaxError: invalid decimal literal

In the case of integer numbers, to access their methods through a literal, you need to use a pair of parentheses. Otherwise, you get a SyntaxError.

Booleans

In Python, Booleans are implemented as a subclass of integers with only two possible values: True or False. Note that these values must start with a capital letter.

You use Boolean values to express the truth value of an expression or object. Booleans are handy when you’re writing predicate functions or using comparison operators, such as greater than (>), less than (<), equal to (==), and so on:

Python
>>> 2 < 5
True
>>> 4 > 10
False
>>> 4 <= 3
False
>>> 3 >= 3
True
>>> 5 == 6
False
>>> 6 != 9
True

Comparison expressions like these evaluate to the Boolean values True or False. Feel free to play with them in your Python interactive session.

Python provides a built-in function called bool() that’s closely related to Boolean values. Here’s how it works:

Python
>>> bool(0)
False
>>> bool(1)
True

>>> bool("")
False
>>> bool("a")
True

>>> bool([])
False
>>> bool([1, 2, 3])
True

The bool() function takes an object as an argument and returns True or False according to the object’s truth value. To evaluate the truth value of an object, the function uses Python’s truth testing rules:

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. Here are most of the built-in objects considered false:

  • constants defined to be false: None and False
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0) (Source)

Strings

Strings are pieces of text or sequences of characters that you can define using single, double, or triple quotes:

Python
>>> # Use single quotes
>>> 'Hello there!'
'Hello there!'

>>> # Use double quotes
>>> "Welcome to Real Python!"
'Welcome to Real Python!'

>>> # Use triple quotes
>>> """Thanks for joining us!"""
'Thanks for joining us!'

>>> # Escape characters
>>> 'can\'t'
"can't"
>>> "can't"
"can't"

You can use different types of quotes to create string objects in Python. You can also use a backslash (\) to escape characters with special meaning, such as the quotes themselves.

You can use the plus operator (+) to concatenate multiple strings in a new string:

Python
>>> "Happy" + " " + "pythoning!"
'Happy pythoning!'

When used with strings, the plus operator (+) concatenates them into a single string. Note that you need to include a space (" ") between words to have proper spacing in your resulting string. If you need to concatenate several strings, then you should consider using the .join() method, which is more efficient.

Python comes with many useful built-in functions and methods for string manipulation. For example, if you pass a string as an argument to len(), then you’ll get the string’s length, or the number of characters it contains:

Python
>>> len("Happy pythoning!")
16

When you call len() using a string as an argument, you get the total number of characters, including any whitespace, in the input string.

The str data type provides a rich set of methods that are useful for manipulating and processing strings. For example, str.join() takes an iterable of strings and combines them into a new string. The string on which you call the method plays the role of a separator:

Python
>>> " ".join(["Happy", "pythoning!"])
'Happy pythoning!'

The .upper() method returns a copy of the underlying string with all the letters converted to uppercase:

Python
>>> "Happy pythoning!".upper()
'HAPPY PYTHONING!'

The .lower() method returns a copy of the underlying string with all the letters converted to lowercase:

Python
>>> "HAPPY PYTHONING!".lower()
'happy pythoning!'

The .format() method performs a string formatting operation. This method provides a lot of flexibility for string formatting and interpolation:

Python
>>> name = "John Doe"
>>> age = 25
>>> "My name is {0} and I'm {1} years old".format(name, age)
"My name is John Doe and I'm 25 years old"

You can also use an f-string to format your strings without using .format():

Python
>>> name = "John Doe"
>>> age = 25
>>> f"My name is {name} and I'm {age} years old"
"My name is John Doe and I'm 25 years old"

Python’s f-strings are an improved string formatting syntax. They’re string literals with an f at the beginning, outside the quotes. Expressions that appear in embedded curly braces ({}) are replaced with their values in the formatted string.

Strings are sequences of characters. As with other sequences, you can retrieve individual characters from a string using their index. An index is a zero-based integer associated with the position of a value in a sequence:

Python
>>> welcome = "Welcome to Real Python!"
>>> welcome[0]
'W'
>>> welcome[11]
'R'
>>> welcome[-1]
'!'

This syntax runs an indexing operation that retrieves the character at the position indicated by the target index. Note that a negative index retrieves the element in reverse order, with -1 being the index of the last character in the string.

You can also retrieve a part of a string by slicing it:

Python
>>> welcome[0:7]
'Welcome'

>>> welcome[11:22]
'Real Python'

Slicing operations follow the syntax [start:end:step]. Here, start is the index of the first value to include in the slice, and end is the index of the last value, which isn’t included in the returned slice.

Finally, step is an optional integer representing the number of values to jump over while extracting the values from the original string. A step of 2, for example, will return every other element between start and stop.

Bytes and Bytearrays

Bytes represent immutable sequences of raw 8-bit values or integers in the range 0 to 255. They’re useful for working with binary data such as files, network protocols, and encoded text. While str stores Unicode text, bytes objects store the encoded form of that text or arbitrary binary payloads.

You can create bytes objects in a few different ways:

Python
>>> # Literal syntax (ASCII only)
>>> b"Hello"
b'Hello'

>>> # From an iterable of integers (0 to 255)
>>> bytes([72, 101, 108, 108, 111])
b'Hello'

>>> # By encoding a string
>>> "café".encode("utf-8")
b'caf\xc3\xa9'

To turn a bytes object back into a string, decode it using the matching encoding:

Python
>>> data = b"caf\xc3\xa9"
>>> data.decode("utf-8")
'café'

Like other sequences, bytes support len(), indexing, and slicing. Note that indexing returns an integer representing the byte value, rather than a one-byte bytes object:

Python
>>> packet = b"ABCDEF"
>>> len(packet)
6
>>> packet[0]
65
>>> packet[1:4]
b'BCD'

Python’s bytes is an immutable data type. If you need a mutable sequence of bytes, then use the bytearray data type, which is a mutable array of bytes:

Python
>>> buffer = bytearray(b"ABC")
>>> buffer[0] = 97
>>> buffer
bytearray(b"aBC")
>>> bytes(buffer)
b'aBC'

Bytes also provide handy methods for binary representations and conversions:

Python
>>> b"Hello".hex()
'48656c6c6f'

>>> bytes.fromhex("48656c6c6f")
b'Hello'

The .hex() method converts a bytes object into a hexadecimal string representation, while the .fromhex() method does the opposite conversion.

Lists

Lists are usually called arrays in nearly every other programming language. In Python, lists are mutable sequences that group various objects together. To create a list, you use a sequence of comma-separated objects in square brackets ([]), as shown below:

Python
>>> # Define an empty list
>>> empty = []
>>> empty
[]

>>> # Define a list of numbers
>>> numbers = [1, 2, 3, 100]
>>> numbers
[1, 2, 3, 100]

>>> # Modify the list in place
>>> numbers[3] = 200
>>> numbers
[1, 2, 3, 200]

>>> # Define a list of strings
>>> ["batman", "superman", "spiderman"]
['batman', 'superman', 'spiderman']

>>> # Define a list of objects with different data types
>>> ["Hello World", [4, 5, 6], False]
['Hello World', [4, 5, 6], False]

They can be empty, as you saw in the first example. Because lists are mutable sequences, you can modify them in place using index notation and an assignment operation. Lists can also contain objects of different data types, including other lists.

Lists are sequences like strings, so you can access their individual items using zero-based integer indices:

Python
>>> numbers = [1, 2, 3, 4]
>>> numbers[0]
1
>>> numbers[1]
2

>>> superheroes = ["batman", "superman", "spiderman"]
>>> superheroes[-1]
"spiderman"
>>> superheroes[-2]
"superman"

Indexing operations also work with Python lists, so you can retrieve any item in a list by using its positional index. Negative indices retrieve items in reverse order, starting from the last item at index -1.

You can also slice lists:

Python
>>> numbers = [1, 2, 3, 4]
>>> new_list = numbers[0:3]
>>> new_list
[1, 2, 3]

If you nest a list, a string, or any other sequence within a list, then you can access the inner items using multiple indices in a row:

Python
>>> mixed_types = ["Hello World", [4, 5, 6], False]
>>> mixed_types[0][6]
'W'

>>> mixed_types[1][2]
6

In these examples, the first index gets the item from the container list, mixed_types, and the second index retrieves an item from the nested sequence.

You can also concatenate lists using the plus (+) operator:

Python
>>> fruits = ["apples", "grapes", "oranges"]
>>> veggies = ["corn", "kale", "spinach"]

>>> fruits + veggies
['apples', 'grapes', 'oranges', 'corn', 'kale', 'spinach']

This list concatenation returns a new list object containing all the items from the original lists.

You can also use len() with lists. Given a list as an argument, len() returns the list’s length, or the number of objects it contains:

Python
>>> numbers = [1, 2, 3, 4]
>>> len(numbers)
4

Lists provide a rich set of methods that allow you to manipulate them. Below are some of the most commonly used methods.

The .append() method takes an object as an argument and adds it to the end of the underlying list:

Python
>>> fruits = ["apples", "grapes", "oranges"]
>>> fruits.append("blueberries")
>>> fruits
['apples', 'grapes', 'oranges', 'blueberries']

The .sort() method sorts the underlying list in place:

Python
>>> fruits.sort()
>>> fruits
['apples', 'blueberries', 'grapes', 'oranges']

The .pop() method takes an integer index as an argument, then removes and returns the item at that index in the underlying list:

Python
>>> numbers = [1, 2, 3, 4]
>>> numbers.pop(2)
3
>>> numbers
[1, 2, 4]

Lists are widely used and versatile data structures in Python. They’re so popular that developers sometimes tend to overuse them, which can make the code inefficient. Check out the resources provided in this section to make sure you use lists effectively.

Tuples

Tuples are similar to lists, but they’re immutable sequences. This means that you can’t change their content after creation:

Python
>>> employee = ("Jane", "Doe", 31, "Software Developer")

>>> employee[0] = "John"
Traceback (most recent call last):
    ...
TypeError: 'tuple' object does not support item assignment

If you try to change a tuple in place, then you get a TypeError exception, which indicates that tuples don’t support in-place modifications.

Note that to create a tuple object, you only need a series of comma-separated values. You don’t need to include parentheses. However, using the parentheses to delimit a tuple makes your code more readable and explicit.

An edge case would be when you need to create a single-element tuple. In this situation, you need to add a comma after the value. Otherwise, you won’t be creating a tuple:

Python
>>> type((1))
<class 'int'>

>>> type((1,))
<class 'tuple'>

In this example, you use the built-in type() function to demonstrate that the parentheses don’t define the tuple—the comma does.

Just like lists, you can also do indexing and slicing with tuples:

Python
>>> employee = ("Jane", "Doe", 31, "Software Developer")
>>> employee[0]
'Jane'
>>> employee[1:3]
('Doe', 31)

You can use indices to retrieve specific items in the tuples. Note that you can also retrieve slices from a tuple with a slicing operation.

You can also concatenate two tuples using the plus operator:

Python
>>> first_tuple = (1, 2)
>>> second_tuple = (3, 4)
>>> third_tuple = first_tuple + second_tuple
>>> third_tuple
(1, 2, 3, 4)

A concatenation operation with two tuples creates a new tuple containing all the items from both input tuples.

Like with lists and strings, you can use certain built-in functions to manipulate tuples. For example, len() returns the length of the tuple:

Python
>>> numbers = (1, 2, 3)
>>> len(numbers)
3

With a tuple as an argument, list() returns a list with all the items in the input tuple:

Python
>>> numbers = (1, 2, 3)
>>> list(numbers)
[1, 2, 3]

Because tuples are immutable sequences, many of the methods that are available for lists don’t exist on tuples. Tuples have only two methods:

  1. .count()
  2. .index()

The .count() method takes a value as an argument and returns the number of times that value appears in the underlying tuple. If the value isn’t in the tuple, then .count() returns 0. Here’s a quick example:

Python
>>> letters = ("a", "b", "b", "c", "a")
>>> letters.count("a")
2
>>> letters.count("c")
1
>>> letters.count("d")
0

The .index() method takes a value as an argument and returns the index of the first instance of that value in the tuple at hand. If the value isn’t in the tuple, then .index() raises a ValueError exception:

Python
>>> letters = ("a", "b", "b", "c", "a")
>>> letters.index("a")
0

>>> letters.index("c")
3

>>> letters.index("d")
Traceback (most recent call last):
    ...
ValueError: tuple.index(x): x not in tuple

Tuples are very useful data structures. They’re memory-efficient, immutable, and have a lot of potential for managing data that shouldn’t be modified by the user. They can also be used as dictionary keys, provided that they don’t contain any mutable elements.

Dictionaries

Python dictionaries are associative arrays containing a collection of key-value pairs, where each key must be a hashable object that maps to an arbitrary value.

There are several ways to create a dictionary in Python. The most common one is to use a literal. However, you can also use the dict() constructor:

Python
>>> john = {"name": "John Doe", "age": 25, "job": "Python Developer"}
>>> john
{'name': 'John Doe', 'age': 25, 'job': 'Python Developer'}

>>> jane = dict(name="Jane Doe", age=24, job="Web Developer")
>>> jane
{'name': 'Jane Doe', 'age': 24, 'job': 'Web Developer'}

The first approach involves using a pair of curly braces, in which you add a comma-separated series of key-value pairs, using a colon (:) to separate the keys from the values. The second approach uses dict(), which can take keyword arguments and turn them into a dictionary. In this case, the keywords work as the keys and the arguments as the values.

You can retrieve the value associated with a given key using the following syntax:

Python
>>> john["name"]
'John Doe'

>>> john["age"]
25

This is quite similar to an indexing operation, but this time, you use a descriptive key instead of an index.

You can also retrieve the keys, values, and key-value pairs in a dictionary using the .keys(), .values(), and .items() methods, respectively:

Python
>>> # Retrieve all the keys
>>> john.keys()
dict_keys(['name', 'age', 'job'])

>>> # Retrieve all the values
>>> john.values()
dict_values(['John Doe', 25, 'Python Developer'])

>>> # Retrieve all the key-value pairs
>>> john.items()
dict_items([('name', 'John Doe'), ('age', 25), ('job', 'Python Developer')])

These three methods are fundamental tools when it comes to manipulating dictionaries in Python, especially when you’re iterating through them.

Sets

Python also provides a built-in set data type. Sets are unordered and mutable collections of unique and hashable objects.

You can create sets in several ways. Here are a few examples:

Python
>>> {"John", "Jane", "Linda"}
{'John', 'Linda', 'Jane'}

>>> set(["David", "Mark", "Marie"])
{'Mark', 'David', 'Marie'}

>>> empty = set()
>>> empty
set()

In the first example, you use a set literal consisting of curly braces and a series of comma-separated objects.

When you use set(), you need to provide an iterable with the objects you want to include in the set. Finally, if you want to create an empty set, then you need to use set() without arguments. Using an empty pair of curly braces creates an empty dictionary instead of a set.

One of the most common use cases for sets is removing duplicate items from an iterable:

Python
>>> set([1, 2, 2, 3, 4, 5, 3])
{1, 2, 3, 4, 5}

Because sets are collections of unique objects, when you create a set using set() with an iterable as an argument, the class constructor removes any duplicate objects and keeps only one instance of each in the resulting set.

You can use some built-in functions with sets like you’ve done with other built-in data types. For example, if you pass a set as an argument to len(), then you get the number of items in the set:

Python
>>> employees = {"John", "Jane", "Linda"}
>>> len(employees)
3

You can also use operators to manage sets in Python. In this case, most operators represent typical set operations like union (|), intersection (&), difference (-), and so on:

Python
>>> primes = {2, 3, 5, 7}
>>> evens = {2, 4, 6, 8}

>>> # Union
>>> primes | evens
{2, 3, 4, 5, 6, 7, 8}

>>> # Intersection
>>> primes & evens
{2}

>>> # Difference
>>> primes - evens
{3, 5, 7}

Sets provide a variety of methods, including those that perform set operations like in the example above. They also provide methods to modify or update the underlying set. For example, set.add() takes an object and adds it to the set:

Python
>>> primes = {2, 3, 5, 7}

>>> primes.add(11)
>>> primes
{2, 3, 5, 7, 11}

The .remove() method takes an object and removes it from the set:

Python
>>> primes = {2, 3, 5, 7, 11}

>>> primes.remove(11)
>>> primes
{2, 3, 5, 7}

Python sets are useful data structures and a valuable addition to any Python developer’s toolkit.

Conditionals

Sometimes, you need to run a given code block depending on whether certain conditions are met. In this situation, conditional statements are your allies. They’re control flow statements that manage the execution of a code block based on the truth value of a condition.

You can create a conditional statement in Python with the if, elif, and else keywords. Here’s the general syntax:

Python Syntax
if condition_0:
    # Run if condition_0 is true
    <block>
elif condition_1:
    # Run if condition_1 is true
    <block>
elif condition_2:
    # Run if condition_2 is true
    <block>
...
else:
    # Run if all expressions are false
    <block>

The code block under if only runs if the condition is true. The elif and else clauses are optional. The first elif clause evaluates condition_1 only if condition_0 is false. If condition_0 is false and condition_1 is true, then only the code block associated with condition_1 will run, and so on.

The else clause will run only if all the previous conditions are false, providing a default code block. You can have as many elif clauses as you need, including none at all, but you can only have one else clause.

Here are some examples of how this works:

Python
>>> age = 21
>>> if age >= 18:
...     print("You're a legal adult")
...
You're a legal adult

>>> age = 16
>>> if age >= 18:
...     print("You're a legal adult")
... else:
...     print("You're NOT an adult")
...
You're NOT an adult

>>> age = 18
>>> if age > 18:
...     print("You're over 18 years old")
... elif age == 18:
...     print("You're exactly 18 years old")
...
You're exactly 18 years old

In the first example, age is equal to 21, so the condition is true and Python prints You're a legal adult. In the second example, the expression age >= 18 is false, and Python runs the code block of the else clause, printing You're NOT an adult on your screen.

In the final example, age > 18 is false, so execution jumps to the elif clause. The condition in this clause is true, so Python runs the associated code block and prints You're exactly 18 years old.

Loops

Sometimes, you need to traverse an iterable of data or repeat a piece of code several times. In this scenario, you can use a loop. Python provides two types of loops:

  1. for loops
  2. while loops

Python’s for loops are designed to iterate over the items in a collection, such as lists, tuples, strings, and dictionaries. In contrast, while loops are useful when you need to execute a block of code repeatedly as long as a given condition remains true.

Here’s the general syntax for creating a for loop:

Python Syntax
for loop_var in iterable:
    # Repeat this code block until iterable is exhausted
    # Do something with loop_var...
    if break_condition:
        break  # Leave the loop
    if continue_condition:
        continue  # Resume the loop without running the remaining code
    # Remaining code...
else:
    # Run this code block if no break statement is run

This type of loop normally performs as many iterations as items in the target iterable. You commonly use each iteration to perform a given operation on or with the value of loop_var. The else clause is optional and runs when the loop finishes. The break and continue statements are also optional.

Here’s a quick example of a for loop that allows you to iterate over a tuple of numbers:

Python
>>> for i in (1, 2, 3, 4, 5):
...     print(i)
... else:
...     print("The loop wasn't interrupted")
...
1
2
3
4
5
The loop wasn't interrupted

When the loop processes the last number in the tuple, the flow of execution jumps to the else clause and prints The loop wasn't interrupted on your screen. That’s because your loop wasn’t interrupted by a break statement.

You commonly use an else clause in loops that include at least one break statement in their code block. Otherwise, there’s no need for it.

If the loop finds a break_condition, then the break statement interrupts the loop’s execution and jumps to the next statement below the loop, without consuming the rest of the items in iterable:

Python
>>> for i in (1, 2, 3, 4, 5):
...     if i == 3:
...         print("Number found:", i)
...         break
... else:
...     print("Number not found")
...
Number found: 3

When i == 3 is true, the loop prints Number found: 3 on your screen and then hits the break statement. This interrupts the loop, and the execution jumps to the line below the loop without running the else clause. If you change the condition to i == 6 or any other number that’s not in the tuple, then the loop doesn’t hit the break statement and prints Number not found.

If the continue_condition is true, then the continue statement resumes the loop without running the remaining statements in the loop’s code block:

Python
>>> for i in (1, 2, 3, 4, 5):
...     if i == 3:
...         continue
...     print(i)
...
1
2
4
5

This time, the continue statement restarts the loop when i == 3. That’s why you don’t see the number 3 in the output.

Both break and continue should be wrapped in a conditional. Otherwise, the loop will always break when it hits break, and continue when it hits continue.

You typically use a while loop when you don’t know beforehand how many iterations you need to complete a given operation. Here’s the general syntax for a while loop in Python:

Python Syntax
while condition:
    # Repeat this code block as long as the condition is true
    # Do something...
    if break_condition:
        break  # Leave the loop
    if continue_condition:
        continue  # Resume the loop without running the remaining code
    # Remaining code...
else:
    # Run this code block if no break statement is run

This loop works similarly to a for loop, but it’ll keep iterating until condition becomes false. A common problem with this type of loop comes when you provide a condition that never evaluates to False. In such cases, you’ll have a potentially infinite loop.

Here’s an example of how the while loop works:

Python
>>> count = 1
>>> while count < 5:
...     print(count)
...     count += 1
... else:
...     print("The loop wasn't interrupted")
...
1
2
3
4
The loop wasn't interrupted

Again, the else clause is optional, and you’ll commonly use it with a break statement in the loop’s code block. The break and continue statements work the same way in a for loop.

There are situations where you need an infinite loop. For example, GUI applications run in an infinite loop that manages the user’s events. This loop needs a break statement to terminate the loop when, for example, the user exits the application. Otherwise, the application would continue running independently. You often create this type of intentionally infinite loop using the while True: pattern.

Functions

In Python, a function is a named code block that performs actions and optionally computes the result, which can be returned to the calling code.

You can use the following syntax to define a function:

Python Syntax
def function_name(arg1, arg2, ..., argN):
    # Do something with arg1, arg2, ..., argN here...
    return return_value

The def keyword starts the function header. Then you need the function’s name and a list of arguments in parentheses. Note that the list of arguments is optional, but the parentheses are syntactically required.

Next, you can define the function’s code block, which will begin one level of indentation to the right. The return statement is also optional and is the statement you use if you need to send a return_value back to the caller code.

To use a function, you need to call it with the appropriate arguments if needed. A function call consists of the function’s name, followed by the function’s arguments in parentheses:

Python Syntax
function_name(arg1, arg2, ..., argN)

You can have functions that don’t require arguments when called, but parentheses are always needed. If you forget them, then you won’t be calling the function but referencing it as a function object.

Classes

Classes let you bundle data (attributes) and behavior (methods) into reusable blueprints for objects. They’re a core part of object-oriented programming in Python and help you model concepts from your problem domain.

Here’s a quick example of how to create a class and instantiate it:

Python
>>> class Dog:
...     def __init__(self, name, age):
...         self.name = name
...         self.age = age
...
...     def bark(self):
...         return "Woof! Woof!"
...

>>> fido = Dog("Fido", 3)
>>> fido.name, fido.age
('Fido', 3)
>>> fido.bark()
"Woof! Woof!"

The class keyword allows you to define the class. Then, you have the .__init__(), which runs when you create a new object and initializes its attributes.

Once you’ve defined a class, you can create instances using the class constructor with appropriate arguments. Finally, you can access the attributes and methods on the instance.

Imports

Imports allow you to reuse code by bringing modules and packages into your main program. They’re a critical tool for programs where you split the code into multiple .py files.

Here are some quick examples of common syntax constructs that you’ll use to import modules and objects in your Python code:

Python
>>> import math
>>> math.sqrt(16)
4.0

>>> from math import sqrt
>>> sqrt(25)
5.0

>>> from math import pi as PI
>>> PI
3.141592653589793

In these examples, you import math and use dot notation to call sqrt(). Then, you import the sqrt() function directly into your current session and call it again. Finally, you import pi as PI, which is an alias.

How Do You Handle Errors in Python?

Errors can frustrate programmers at every level of experience, and identifying and handling them is a core skill. In Python, there are two types of code-based errors—syntax errors and exceptions—and you may also face semantic errors.

Syntax Errors

Syntax errors occur when the syntax of your code isn’t valid in Python. They automatically stop the execution of your programs. For example, the if statement below is missing a colon at the end of its header, and Python quickly points out the error:

Python
>>> if x < 9
  File "<python-input-0>", line 1
    if x < 9
            ^
SyntaxError: expected ':'

The missing colon at the end of the if statement is invalid Python syntax. Python’s parser catches the problem and immediately raises a SyntaxError exception. The ^ character indicates where the parser found the problem.

Exceptions

Exceptions are raised by syntactically correct code at runtime to signal a problem during program execution. For example, consider the following math expression:

Python
>>> 12 / 0
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    12 / 0
    ~~~^~~
ZeroDivisionError: division by zero

The expression 12 / 0 is syntactically correct from the Python parser’s perspective. However, it raises a ZeroDivisionError exception when the interpreter tries to evaluate the expression.

Python provides several convenient built-in exceptions that allow you to catch and handle errors in your code.

Semantic Errors

Semantic errors happen as a result of one or more problems in the logic of a program. These errors can be difficult to find, debug, and fix because no error message is generated. The code runs but generates unexpected, incorrect output or no output at all.

A classic example of a semantic error is an unintentional infinite loop, which most programmers experience at least once in their coding lifetime.

How Do You Get Help in Python?

If you’re stuck, start by asking the interpreter for help. It’s built in and always available. Perhaps you need to know how a specific function, method, class, or object works. In this situation, you can open an interactive session and call the built-in help() function. That’ll take you directly to Python’s interactive help system:

Python
>>> help()
Welcome to Python 3.13's help utility! If this is your first time using
Python, you should definitely check out the tutorial at
https://docs.python.org/3.13/tutorial/.

...

To quit this help utility and return to the interpreter,
enter "q", "quit" or "exit".

help>

Once there, you can enter the name of a Python object to get helpful information about it:

Python Interactive Help System
help> len

Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

When you type the name len at the help> prompt and press Enter, you get help content related to that built-in function. To leave the content and get back to the help> prompt, you can press Q. To leave the help utility, type quit and press Enter.

You can also use help() with the name of an object as an argument to get information about that object:

Python
>>> help(dir)

Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the
    attributes of the given object, and of attributes reachable from it.
    ...

The built-in dir() function allows you to inspect the methods and attributes that are available in a particular object.

What Are Good Tools for Coding in Python?

There are several tools you can use to write and run Python code. You’ll often combine them as your projects grow. The Python interactive interpreter—also known as the REPL (Read-Eval-Print Loop)—is perfect for experimenting and learning how to use Python.

To write code that you can reuse and share, you typically put it into Python scripts and modules, which you usually edit in a code editor or an integrated development environment (IDE).

In addition to these traditional tools, modern AI coding assistants can help you scaffold Python projects, write code and tests, debug, suggest improvements, and more. Think of them as a productivity booster that pairs nicely with the terminal, editors, and IDEs. The sections below introduce each option and how they fit together.

REPLs

Although you can write complex code in an interactive session, you typically use the REPL for one-line expressions and statements or for short compound statements to get quick feedback from your code. Open your Python interpreter and type the following:

Python
>>> 24 + 10
34

The interpreter evaluates 24 + 10 and outputs the sum 34. Now, try one more:

Python
>>> import this

Take a moment to read the output of this import. It states some important principles in Python, which will help you write better and more Pythonic code.

So far, you’ve used the standard Python REPL, which ships with the official CPython distribution. However, this isn’t the only REPL out there. Third-party REPLs provide many useful features, such as syntax highlighting, code completion, and history. Here are some popular options:

  • IPython provides a rich toolkit to help you code in Python interactively.
  • bpython is an interface to the Python interpreter for Linux, BSD, and macOS.
  • ptpython is a Python REPL that also works on Linux, BSD, macOS, and Windows.

Keep in mind that once you close the REPL session, your code is gone. In other words, the code typed into a REPL isn’t saved, so you can’t reuse it. As a developer, you want code that you can reuse to save precious keystrokes. In this situation, code editors and IDEs come in handy.

Code Editors

Code editors are often good for learning purposes. Why? Because when you’re learning something new, you want to peel off as many layers of complexity as possible. Adding a complex IDE into the mix can make the task of learning Python more difficult.

A Python program, in its simplest form, consists of lines of text (code) saved in a file with a .py or .pyw extension. You can write Python code in something as basic as Notepad on Windows, but there are much better options available that make coding and learning easier.

At its core, a code editor should provide several features to help programmers create programs. In most cases, you can customize the code editor to suit your needs and style. So, what should you look for in a code editor? The answer to this question might depend on your personal needs, but in general, you should look for at least the following features:

Here’s a non-exhaustive list of some modern code editors that you can use:

  • Visual Studio Code is a full‑featured code editor for Linux, macOS, and Windows.
  • Sublime Text is a fast, cross‑platform editor with a rich plugin ecosystem.
  • Neovim is a modern Vim with an extensible Lua‑based plugin system.
  • Zed is a high‑performance, collaborative editor available on macOS and Linux.
  • Cursor is an AI‑assisted editor built on the VS Code ecosystem, available on macOS, Windows, and Linux.
  • Notepad++ is a popular, lightweight editor for Windows.
  • GNU Emacs is an extensible, cross‑platform editor.

There are many different options, both free and commercial, when it comes to code editors. Do your research and don’t be afraid to experiment! Keep in mind that your code editor should help you adhere to Python coding standards, best practices, and idioms.

IDEs

An integrated development environment (IDE) is a program dedicated to software development. IDEs commonly integrate features such as code editing, debugging, version control, test running, and environment management. Here are solid, up‑to‑date options that work great with Python:

If you’re into data science, then you may use JupyterLab, which isn’t a traditional IDE but is widely used for data analysis and teaching.

This list isn’t exhaustive. If you’re new, start with Thonny. For larger projects and web work, PyCharm is a strong choice. Explore and experiment before you make your final choice.

AI Coding Assistants

AI coding assistants can augment your workflow by generating code, explaining error messages, writing tests and documentation, and suggesting refactors. All of this comes from natural language prompts. Most popular and powerful AI coding assistants like GitHub Copilot Chat, Claude Code, Codex CLI, Gemini CLI, and JetBrains AI Assistant, are available as editor plugins or extensions, web apps, and command-line tools.

When you’re using these AI assistants, keep these best practices in mind:

  • Be specific in your prompts: Include your Python version and library names and versions when they matter.
  • Verify everything: Run the code, read the documentation, and add tests.
  • Protect secrets: Don’t share user credentials, private keys, or sensitive data in prompts.
  • Treat it like a junior teammate: You’re still the engineer responsible for code correctness and style.

AI assistants are tools to speed up your development process. They’re not replacements for understanding. Use them for learning, coding, and automating routine tasks, but always validate their output and keep building your understanding of Python and the libraries you use.

PEP 8 is the official style guide for Python code. Although it’s not required for writing working Python code, studying PEP 8 and applying it consistently in your Python code will make your programs more readable and maintainable.

Luckily, you don’t need to memorize PEP 8 to give your Python code a Pythonic style. Most code editors and IDEs that support Python internally implement automatic checks to flag PEP 8 violations. These checks help you consistently improve your code style and reinforce PEP 8’s recommendations.

You can also take advantage of code linters like Flake8, Pylint, and pycodestyle. You can even use code formatters, such as Black, isort, and Ruff, to consistently format your code. Some of these tools are conveniently integrated into most modern Python code editors and IDEs.

To learn more about improving the quality of your code using PEP 8 and other style best practices, check out How to Write Beautiful Python Code With PEP 8 and Python Code Quality: Best Practices and Tools.

How Can You Get Extra Features in Python?

So far, you’ve learned a few basic Python concepts and features. When you start to dive deeper into the language, you may find that you need a certain feature and decide to code it by yourself. If that’s the case, then consider that you might be reinventing the wheel.

Python’s been in use for over three decades now. It has an incredibly large community of developers, and it’s likely that someone else has run into the same problem as you. With a little research, you may be able to find a code snippet, library, framework, or other solution that can save you a lot of time and effort.

The first place to look is the Python standard library. If you don’t find anything there, then you can also look at the Python Package Index (PyPI). Finally, you can check out some other third-party libraries.

The Standard Library

One of the great things about Python is the plethora of available modules, packages, and libraries built into the Python core and made available by third-party developers. These modules, packages, and libraries can be very useful in your day-to-day work as a Python developer.

Here are some of the most commonly used built-in modules:

Module Description
asyncio Asynchronous I/O with event loops, tasks, and coroutines
collections Specialized container data types
csv CSV reading and writing
itertools Iterator utilities
json JSON encoding and decoding
math Mathematical operations
pathlib Object-oriented file system paths
random Pseudo-random numbers
re Regular expressions
subprocess Subprocess management and external commands
tkinter Desktop GUI applications
unittest Unit testing

For example, here you import math to use pi, find the square root of a number with sqrt(), and raise a number to a power with the pow() function:

Python
>>> import math

>>> math.pi
3.141592653589793

>>> math.sqrt(121)
11.0

>>> math.pow(7, 2)
49.0

Once you import math, you can use any function or object defined in that module. If you want a complete list of the functions and objects that live in math, then you can run something like dir(math) in an interactive session.

You can also import specific functions directly from math or any other module:

Python
>>> from math import sqrt
>>> sqrt(121)
11.0

This kind of import statement brings the name sqrt() into your current namespace, so you can use it directly without needing to reference the containing module.

If you’re using modules such as math or random, then make sure not to use those same names for your custom modules, functions, or objects. Otherwise, you might run into name conflicts, which can cause unexpected behavior.

The Python Package Index (PyPI)

The Python Package Index, also known as PyPI (pronounced “pie pea eye”), is a massive repository of Python packages that includes frameworks, tools, packages, and libraries. You can install any PyPI package using pip, uv, or another package installer.

New coders frequently hit a wall when they’re following an example and get a ModuleNotFoundError exception when they run the code. This error means that the code lives in a module, but that module isn’t installed in the current Python environment, leading to a broken dependency.

For example, say you’re trying to run an application that uses pandas, but you don’t have this library installed in your Python environment. In this situation, you can open your terminal and use pip as shown below:

Shell
$ python -m pip install pandas

This command downloads pandas and its dependencies from PyPI and installs them in your current Python environment. Once the installation is finished, you can run your application again. If there are no other broken dependencies, the code will work.

How Can You Take Your Python Skills to the Next Level?

Real Python Logo

Here at Real Python, you’ll find all kinds of resources to help you get started with the language and learn Python:

  • 📘 Tutorials help you learn Python through a detailed, in-depth approach.

  • 📺 Video Courses provide in-depth content with a progressive learning approach.

  • 🧭 Learning Paths guide you through foundational and advanced Python topics from the ground up.

  • 🧑‍🏫 Live Courses for Beginners connect you with expert instructors for hands-on Python learning in real time.

  • 📖 References help you quickly look up Python and programming-related concepts.

  • 🧠 Quizzes let you test your understanding and measure your learning progress.

  • 🎧 The Real Python Podcast covers a wide range of topics, including Python best practices, career tips, and related software-development themes.

  • ⏰ Office Hours give you the opportunity to meet fellow Pythonistas, discuss your learning, ask questions, and explore Python concepts.

  • 📚 Books help you take your Python skills to the next level and support our online resources.

  • 👥 Community allows you to connect with the Real Python team and other Pythonistas who are actively looking to improve their skills.

Most of these learning resources are free. Others cost a modest fee that supports the site and helps maintain high-quality content.

If you’re just beginning with Python, then check out the book Python Basics: A Practical Introduction to Python 3 and its companion Learning Path. They’ll help you make the leap from beginner to intermediate Python developer.

Of course, there are other Python courses, tutorials, and resources available online. The right choice is personal—compare a few and pick what fits your goals and learning style. The official Python documentation is a solid, free reference to keep handy. Just be aware that the material can be less beginner-friendly than what you’ll find at Real Python.

Above all, it’s important that you don’t fall into trying to find the best book or video ever and get lost in the process. Do some research. Ask around. But pick something and stick with it! Open your code editor and start coding a Python project! Make a commitment to yourself to find a way to bring your vision to life and complete your project.

How Can You Approach Programming Challenges?

Coding is like riding a bike. You can watch people to learn how it’s done, but in the end, you have to do it yourself. When you get stuck or need to learn a new concept, you can often work through the problem yourself by doing some research on the web or asking an AI chat.

For example, if you get an error, then typing the exact error message into Google or an AI chat can help you solve the problem. Stack Overflow is another place you can visit when looking for answers.

If you get stuck on a problem, then try these suggestions:

  1. Stop coding!

  2. Get a piece of paper and map out how to solve the problem using plain words. Use a flowchart if necessary.

  3. Don’t use a tryexcept block until your code is working. The try can suppress valuable error messages that help identify problems in your code.

  4. Use print() to quickly inspect your variables and make sure they have the expected value. This is an effective, quick-and-dirty debugging technique.

  5. Use the rubber duck debugging technique. Explain your code, line by line, to the duck. You might find the solution to your problem in the process.

  6. If you’re still stumped, use the Python Visualizer. This tool allows you to step through your code as it executes. The Python Visualizer has examples to help you if needed.

One final and important note: a frustrated brain won’t help. When you feel stuck because something isn’t working, take a break to clear your mind. Go for a quick walk or run, stretch, or do something unrelated. You’ll be amazed at just how effective this can be. More often than not, you’ll come back with fresh eyes and see a simple typo, a misspelled keyword, or another small oversight.

Conclusion

You’ve taken your first steps with Python, learning how to install it, write and run your first programs, and understand its clear and readable syntax. You’ve explored the core building blocks of Python coding, including variables, data types, loops, functions, classes, and error handling, and you’ve discovered tools and resources that make programming in Python efficient and enjoyable.

Along the way, you’ve learned about coding style, the Python standard library, and third-party packages. Understanding these foundational concepts is crucial for any Python developer. They’re the basis for writing clean, reliable, and maintainable code.

In this tutorial, you’ve learned how to:

  • Install and run Python on your operating system and use the REPL for interactive exploration
  • Work with Python’s built-in data types, including strings, lists, dictionaries, and sets
  • Use control flow constructs like conditionals and loops to manage program execution
  • Define your own functions and classes to structure your code effectively and promote reusability
  • Detect and handle errors and exceptions in your code
  • Use Python’s built-in help system to get help interactively

With these skills, you can confidently start writing and running Python programs, explore new features and libraries, and build on your foundation to tackle more complex projects.

Frequently Asked Questions

Now that you’ve taken your first steps with how to use Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs are related to the most important concepts you’ve covered in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.

When you use Python, it checks types at runtime instead of requiring you to declare them. This makes it a dynamically typed language. It’s also strongly typed, meaning Python prevents unsafe operations on incompatible types and raises an error instead.

To run the Python interpreter, open your terminal or command prompt and type python3 or python (on macOS/Linux), or py (on Windows). This will start an interactive session, known as the REPL, where you can type and execute Python code directly.

You create a variable in Python by assigning a value to a name using the = operator. For example, x = 10 defines a variable named x that refers to the value 10.

A variable name is the label you choose, while the variable value is the object stored in memory that the name refers to. You can use the name to access or modify the underlying value.

Python provides built-in data types such as numbers, Booleans, strings, bytes, lists, tuples, dictionaries, and sets. Each of them comes with its own methods and operations for manipulation.

An integer represents whole numbers without decimals, while a floating-point number represents numbers with decimal points. Floating-point values can approximate fractions but have limited precision.

Booleans express truth values in Python. They only have two possible values, True or False, and are commonly used in conditions and comparisons.

A list is mutable, so you can change its contents after creation. A tuple is immutable, which means once created, you can’t change its contents.

A dictionary is a collection of key-value pairs where each key maps to a specific value. Keys must be unique and hashable, while values can be any object.

You use comments to explain what your code does when it’s not clear or to clarify why you chose a specific approach or algorithm. This makes your code easier to read, understand, and maintain for you and others.

The help() function opens Python’s interactive help system. You can use it to quickly access documentation about functions, methods, classes, or modules directly in your Python interactive session.

A syntax error occurs when your code violates Python’s rules and prevents execution. An exception occurs at runtime in otherwise syntactically valid code when something unexpected happens, such as dividing by zero.

Take the Quiz: Test your knowledge with our interactive “How to Use Python: Your First Steps” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

How to Use Python: Your First Steps

Review the basics of Python with this quiz. Practice syntax, keywords, variables, errors, and tools every beginner should know.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.

» More about Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!