Python

What is Python?

Python is a high-level, versatile programming language known for its clean syntax and ease of use. It's a great choice for beginners and professionals alike because it's readable, flexible, and supported by a huge community. Python is widely used in web development, data science, automation, artificial intelligence, machine learning, game development, and more.

Installing and Setting Up

You can install and set up Python on your machine for free. To check if you already have it installed, you can open your terminal and type:

python --version

or

python3 --version

If you have Python installed, you will see something like Python 3.x.x.

Otherwise, download the latest version of Python for your operating system from the Python website and clicking on the big yellow Download Python 3.X.X button.

For a windows machine, run through the installation wizard, ensuring that you check the box that says "Add Python to PATH". Once this has completed, you can check that it has installed correctly from your terminal again using:

python --version

or

python3 --version

For other operating systems, see the beginner download Python guide.

With Python installed, you will need pip. This is usually installed automatically when you set up Python but you can check from your terminal using:

pip --version

If it is not installed you can download get-pip.py from the pip installation documentation and run the file.

Writing

Before jumping into writing actual code, it's helpful to outline your logic using pseudocode . This is plain-language writing that describes what your code is supposed to do, step by step. This helps you focus on the logic first, and worry about the syntax later.

Comments start with a hash/pound/hashtag # symbol in Python. They're ignored by the interpreter but help you and others understand what your code is doing.

# This function adds two numbers
def add(x, y):
    return x + y

Indents matter a lot in Python. Whereas JavaScript define blocks of code with curly brackets, Python uses indentation. Stick to four spaces or 1 tab per indent level and pick one (spaces or tabs) and keep to it.

# Correct Indentation
if age >= 18:
    print("You can vote!")

# Incorrect (will raise an IndentationError)
if age >= 18:
print("You can vote!")

PEP8 is the official Python style guide and should be adhered to for best practice and to ensure that your code runs flawlessly. Some basic rules are:

  • Use lowercase_with_underscores for function and variable names.
  • Use CapitalizedWords for class names.
  • Keep lines under 79 characters long.
  • Add a blank line between functions for readability.

File Layout

When writing Python scripts, it's important to structure your code in a clean, readable, and maintainable way. A well-organized file layout makes it easier to understand what your program does, where to find specific functionality, and how to scale your project later on. The files will have a .py file extension and ideally have a filename that is descriptive. It will consist of a series of functions; the main function, aptly named main, and a series of smaller function. The, ahem, function of main is where you can turn your pseudo code into actual code and call functions in logical order. Each line of pseudo code (each… function!) should be split into it's own function that is defined underneath main. These are called helper functions. The end of the file will have a if __name__ == "__main__": block that will call the main function. The whole reason for this, is so that if the file is run on its own, it will execute whatever code is in the main function. But if you are using it as a library, you can import any of the helper functions in other files without running the whole of this file to do so.

# Filename: my_script.py

def main():
    # Step 1: Write pseudocode
    # Step 2: Translate it into real code
    result1 = func1()
    result2 = func2(result1)
    print(result2)

def func1():
    # Performs a specific task, e.g., gets user input
    return "Hello"

def func2(input_str):
    # Manipulates or processes the result from func1
    return input_str + ", world!"

if __name__ == "__main__":
    main()

Running Python Code

To run a Python script, you need to use the command line (also called the terminal or shell) when in the correct directory and use the following command.

python filename.py

If your program gets stuck in a loop or takes too long to run, you can forcefully stop it by pressing Ctrl + C. This sends an interrupt signal to Python and cancels the script. It's especially useful when you are stuck in an infinite loop or your program is waiting for an input that never comes.

Sometimes you need to pause your program and take a look around to check variable values, understand the flow, or find a bug. That's where breakpoints come in. A breakpoint is an intentional pause in your code that tells the interpreter to stop where it is. This allows you to examine variable values, step through code line-by-line or detect logic errors.

Troubleshooting

If python filename.py does not work, it might be because python is pointing to Python2 in your system. If that is the case, try python3 filename.py

Libraries

One of Python's biggest strengths is its vast ecosystem of libraries, which are reusable chunks of code that provide tools and functions for everything from math and web development to machine learning and data analysis. Python comes with a standard library that includes modules like math, datetime, os, and random, which are available without installing anything extra. You can browse the full list of built-in libraries in the official Python documentation. For additional functionality, you can install external libraries using Python's package manager, pip. For example, to install the popular requests library, you would run pip install requests in your terminal.

Object Oriented Programming

In Python, everything is an object, even functions and numbers. This makes the language powerful and flexible, especially for advanced topics like functional programming and OOP.

Object-Oriented Programming in Python revolves around the concept of classes and objects. A class is like a blueprint for creating objects—instances that contain both data (attributes) and behaviors (methods). Python allows developers to define their own data types by creating classes, encapsulating related logic and data together in a clean, reusable way. Key OOP principles such as encapsulation, inheritance, and polymorphism are fully supported in Python, enabling developers to build complex applications that are modular, maintainable, and scalable.

Because everything in Python is an object, even classes themselves are instances of a special class called type, allowing for dynamic behavior and introspection. This object model underpins much of Python's flexibility and makes it easy to extend or customize language behavior using techniques like metaprogramming and decorators.