Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Five things to know before learning Python

September 10, 2021
Jason Dobies
Related topics:
Artificial intelligenceLinuxPython
Related products:
Red Hat Enterprise Linux

Share:

    Getting started with a new programming language can be challenging. Whether you're a beginner or a grizzled veteran, there are a number of larger context questions to answer that go beyond simply learning the language's syntax. This article provides a high-level overview of five important things to keep in mind as you begin your journey into Python. You won't learn the specifics of the language here, but you'll gain a general picture of how Python works. 

    Note: Also see the Five things to know before learning Python video from Red Hat Developer.

    1: Python is an interpreted language

    Programming languages fall into two categories: Those that require a compilation step prior to running (such as Java and C) and those that are interpreted directly from the source code (like JavaScript and Ruby). Python falls into the latter category. Python source code files, commonly referred to as “scripts,” are used directly by a Python interpreter to execute.

    For example, take the following code:

    print(‘Hello World’)

    When saved to a file, for example hello.py, it can be passed to a Python interpreter without the need for an explicit compilation step:

    $ python hello.py
    Hello World

    2: Python is object-oriented, but not exclusively

    If you come from an object-oriented background, particularly Java where everything is an object, the hello.py example may look a little strange. The single-line script not only doesn’t define any classes, but it isn’t even inside of a method declaration.

    Python supports object-oriented programming, but you aren’t locked into it. You can add functions directly to a script when there isn’t a need for the overhead and complication of defining a class.

    For example, take the following (obviously academic) class:

    class PhoneNumber(object):
    
        def __init__(self, area_code, number) -> None:
            self.area_code = area_code
            self.number = number
    
        def display(self):
            print(f'({self.area_code}) {self.number}')
    
    pn = PhoneNumber('973', '555-1234')
    pn.display()

    Note: This article won't get into the details of Python. However, it is worth mentioning that the self reference in this snippet is used to indicate object variables.

    Running this script produces the formatted output (973) 555-1234.

    If the output is the only goal, it arguably doesn’t need to be a class. You could rewrite it as a function, instead:

    def display_pn(area_code, number):
        print(f'({area_code}) {number}')
    
    display_pn('973', '555-7890')

    A third option is to combine the two, defining stateless functions where appropriate and having objects use those methods:

    class PhoneNumber(object):
    
        def __init__(self, area_code, number) -> None:
            self.area_code = area_code
            self.number = number
    
        def display(self):
            display_pn(self.area_code, self.number)
    
    def display_pn(area_code, number):
        print(f'({area_code}) {number}')
    
    pn = PhoneNumber('973', '555-1234')
    pn.display()

    3: Python is not strongly typed (which is a double-edged sword)

    Take a look at the following, perfectly valid, Python code:

    x = 'ba'
    x = 1
    x = print
    x = None

    That snippet assigns to the variable x a string literal, an integer, a function, and the Python value for null. On top of that, the variable didn't even need to be explicitly declared.

    Python uses the concept of duck typing—if it swims like a duck and quacks like a duck, it's probably a duck. In other words, if the value of a variable has certain abilities, the actual type of object it is doesn't really matter.

    Take the concept of iteration as an example. The for built-in function iterates over a collection of items. How those items are stored is irrelevant; the important part is that the object supports the ability to be iterated.

    This is fairly obvious for simple constructs such as lists and sets:

    x = [1, 2, 3]  # list
    y = {1, 2, 3}  # set
    
    for i in x:
        print(i)
    
    for i in y:
        print(i)

    For key-value pairs (known as a dict in Python), the for function will iterate over just the keys (producing the output a b c from the following snippet):

    z = {'a': 1, 'b': 2, 'c': 3}
    
    for i in z:
        print(i)
    

    There are times, however, where this power and flexibility can produce ... interesting results. For example, a string is also considered iterable, meaning it can be passed into a for loop without producing a runtime error. But the results are often unexpected:

    w = 'water'
    
    for i in w:
        print(i)

    That snippet will run without error, producing the following:

    w
    a
    t
    e
    r

    Note: This particular example is meant to demonstrate a situation where a list of length 1 (in other words, a list with the word water) was expected, rather than the literal string. There are many other situations where duck typing doesn't produce a runtime exception; however, the behavior is not what was intended.

    4: Whitespace matters in Python

    It may seem odd to highlight something as seemingly trivial as whitespace, but it's such an important aspect of Python's syntax that it warrants mentioning.

    Python uses indentation to indicate scope, freeing it from the arguments about curly brace placement that other languages encounter. Generally speaking, a code block is defined by statements that share the same indentation level. Looking again at the phone number example:

    class PhoneNumber(object):
    
        def __init__(self, area_code, number) -> None:
            self.area_code = area_code
            self.number = number
    
        def display(self):
            display_pn(self.area_code, self.number)
    
    def display_pn(area_code, number):
        print(f'({area_code}) {number}')

    The two assignments in the __init__ method (Python's implementation of a constructor) are considered part of the method definition. We know this because they are indented further than the declaration and share the same indentation level. If the second statement (self.number = number) was offset by even a single space in either direction, the code would fail to run (with an error similar to IndentationError: unexpected indent).

    Along the same lines, the display_pn function is indented at the same level as the PhoneNumber class, indicating it is not part of the class definition. Keep in mind, however, that the indentation of the body of display_pn has no bearing on the bodies of the class methods (in other words, there are no syntactic implications to the fact that the body of display_pn and the definition of display() are both indented by four spaces).

    Note: See the PEP 8 Style Guide for Python Code for more details about whitespace, as well as general Python code style guidelines.

    5: Use virtual environments to prevent dependency conflicts

    In many cases, you'll already have a Python interpreter installed on your system. For development, however, you'll likely want to create a virtual environment, which is effectively a copy of the interpreter that is scoped specifically to that environment.

    The reason for using virtual environments largely revolves around installing dependencies. Without using a virtual environment, any dependencies that are installed for your project (such as the Django, Flask, pandas, or numpy libraries) are installed to the global interpreter. Having such dependencies installed system-wide is a risk for a number of reasons, including version compatibility issues.

    Instead, creating a virtual environment for your project provides an individually scoped interpreter to use. Any dependencies installed to the virtual environment only exist for that environment, allowing you to easily develop on multiple projects without fear of system-wide implications or conflicts.

    There are a number of ways to manage Python virtual environments, including the built-in venv command, as well as the (arguably more user-friendly) utility packages pyenv and virtualenv.

    Conclusion

    This article is not a comprehensive overview of the Python language or its syntax. But it should help set the stage for what to expect and how to best work with the language. With these basic concepts in mind, the next step is to dive in and start to experiment.

    Last updated: October 6, 2022

    Related Posts

    • Build your first Python application in a Linux container

    • micropipenv: Installing Python dependencies in containerized applications

    • Faster web deployment with Python serverless functions

    • Debugging Python C extensions with GDB

    Recent Posts

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    • How to integrate vLLM inference into your macOS and iOS apps

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue