Python Essentials: Concepts For Every Programmer

Python Essentials: Concepts For Every Programmer

A Deep Dive into Variables, Data Types, Collections, and More

It’s true that there’s a lot to learn about Python, as it is uniquely different from other programming languages. Python can be used on a server to create web applications - check out my recent article on web applications.

I am currently undergoing training to become a certified backend developer, and during this process, I’ve been learning a lot about Python’s data types and their characteristics. This article was inspired by a recent project where I’m building an ATM simulator. In this article, I’ll discuss Python’s core concepts and its uses.

A Beginner’s Journey Through Python’s Core Concepts and Best Practices

Quick tips

  • In addition to web development (server-side), Python can also be used for software development, creating workflows, and script writing.

  • Python is capable of handling large data sets and complex mathematics, connecting to databases, and reading and modifying files.

  • Compared to other programming languages, Python has a simple syntax that resembles the English language.

If you're like me, structured and someone who loves to break down and explain code clearly in comments - the above tip is a life-saver!

  • In Python, a variable name cannot be one of the reserved Python keywords.

  • Python really relies on indentation and using whitespace to define scope, such as the scope of loops, functions and classes. Other programming languages use curly brackets for this purpose.

In Python, comments are represented by # for single-line comments, and they can be placed at the top of the code or beside a code line. For multi-line comments, you can use multiple # symbols, or use triple quotes (""" """ or ''' ''') for blocks of comments, which Python will ignore as they aren't assigned to a variable. Below are the different ways to use comments in Python:

👉 Single-line comments using #

👉 Inline comments after a statement

👉 Multi-line comments using multiple #

👉 Docstring-style comments using triple quotes (""" """ or ''' '''), though typically used for documentation. Docstrings can be accessed at runtime using help() or __doc__.

Below is the difference between comments and docstrings:

FeatureComments (#)Docstrings (""" """)
PurposeExplain code for developersDescribe the purpose of modules, functions, and classes
VisibilityIgnored by PythonCan be accessed at runtime using help()
PlacementAnywhere in codeTypically at the start of functions, classes, or modules
# This is a single-line comment
print("Welcome to International Bank!")

print("Welcome to International Bank!")  # This is an inline comment

# This is a comment
# written in
# more than just one line
print("Welcome to International Bank!")

"""
This is a comment
written in
more than just one line
"""
print("Welcome to International Bank!")

You can download the latest version of Python here, where you can practice on its IDE or create new files.

Variables in Python

A variable is a name that stores a value in memory. In Python, you don’t need to declare a variable type explicitly; the type is inferred based on the assigned value.

Rules for Naming Variables

  1. Must start with a letter (A-Z or a-z) or an underscore (_).

  2. Cannot start with a number.

  3. Can only contain letters, numbers, and underscores and Python allows assigning multiple values to multiple variables in one line.

  4. Case-sensitive (age and Age are different variables).

  5. Cannot use Python keywords (e.g., if, while, import).

Legal variable naming:

myvar = "John"
my_var = "John"
_my_var \= "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"


Declaring and Assigning Variables

name = "Alice"   # String
age = 15            # Integer
accountBalance = 1500.75   # Float
is_active = True    # Boolean

print(name, age, accountBalance, is_active)

Multiple Assignments

Python allows assigning multiple values to multiple variables in one line.

x, y, z = 10, 20, 30
print(x)
print(y)
print(z)

Assigning the same value to multiple variables:

a = b = c = "Python"
print(a, b, c)

Type Checking

To check the type of a variable, use type().

x = 5
print(type(x))  # Output: <class 'int'>

Dynamic Typing

Python is dynamically typed, meaning you can change the type of a variable by reassigning it.

var = 10    # Initially an integer
var = "Now a string"  # Reassigned as a string
print(var)

Variable Scope

  • Global Variable: Accessible throughout the script. It can be used by everyone, both inside of functions and outside.

  • Local Variable: Defined inside a function and only accessible there.

global_var = "Greetings - Welcome to International Bannk"

def my_function():
    local_var = "Transaction - Account balance"
    print(local_var)

my_function()
print(global_var)

However, you can create a global variable inside a function by using the global keyword. Also, use the global keyword if you want to change a global variable inside a function.

Video: Learn more about Python Variable Names

Data Types

One of the important concepts of Python is its data type. When you have a variable and assign a data or value to it, it is important to know what data type is required for that function. This determines the output and the overall performance of your code.

Python has several built-in data types that define the kind of values a variable can hold.

Below is a summary table and a breakdown of the most common ones with examples of them being assigned to a variable:

Summary Table

TypesCategory
Numericint, float, complex
Sequencestr, list, tuple, range
Setset, frozenset
Mappingdict
Booleanbool
Binarybytes, bytearray, memoryview
NoneNoneType

Breakdown

Numeric Types

Data TypeDescriptionExample
intInteger values (whole numbers)x = 10
floatDecimal numbersy = 10.5
complexComplex numbers with j as the imaginary partz = 2 + 3j
x = 10         # Integer
y = 10.5       # Float
z = 2 + 3j     # Complex
print(type(x), type(y), type(z))

Sequence Types

Data TypeDescriptionExample
strString (text)name = "International Bank"
listOrdered, mutable collectionfruits = ["apple", "banana", "cherry"]
tupleOrdered, immutable collectioncoordinates = (10, 20, 30)
rangeSequence of numbersnumbers = range(5) (0 to 4)
name = "International Bank"   # String
fruits = ["apple", "banana", "cherry"]  # List
coordinates = (10, 20, 30)  # Tuple
numbers = range(5)  # Range

print(type(name), type(fruits), type(coordinates), type(numbers))

Set Types

Data TypeDescriptionExample
setUnordered, unique collectionunique_nums = {1, 2, 3, 3}
frozensetImmutable version of a setfrozen_nums = frozenset({1, 2, 3})
unique_nums = {1, 2, 3, 3}  # Set (removes duplicate)
frozen_nums = frozenset({1, 2, 3})  # Frozenset (immutable)

print(type(unique_nums), type(frozen_nums))

Mapping Type

Data TypeDescriptionExample
dictKey-value pairsuser = {"name": "John", "age": 30}
customer = {"name": "Alice Johnson", "account_no": "1234567890", "pin": "1234", "balance": 5000.75}  # Dictionary
print(type(customer))

Boolean Type

Data TypeDescriptionExample
boolRepresents True or Falseis_active = True
is_active = True  # Boolean
print(type(is_active))

Binary Types

Data TypeDescriptionExample
bytesImmutable sequence of bytesb = b"Hello"
bytearrayMutable sequence of bytesba = bytearray(5)
memoryviewView of a bytes objectmv = memoryview(bytes(5))
b = b"Hello"  # Bytes
ba = bytearray(5)  # Bytearray
mv = memoryview(bytes(5))  # Memoryview

print(type(b), type(ba), type(mv))

None Type

Data TypeDescriptionExample
NoneTypeRepresents no valuex = None
x = None  # NoneType
print(type(x))

Collections in Python

Collections in Python are specialized data types that allow you to store multiple values in a single variable. The four main collection types are:

  • List: Ordered, mutable (changeable), allows duplicates.

  • Tuple: Ordered, immutable (unchangeable), allows duplicates.

  • Set: Unordered, mutable, does not allow duplicates.

  • Dictionary: Stores key-value pairs, unordered (in Python 3.6 and earlier), mutable.

Python also provides a feature called unpacking, which allows you to extract values from a collection and assign them to variables. This is especially useful for collections like tuples, which can be both packed and unpacked.

A tuple is particularly interesting not only because of its immutability (compared to a list) but also due to its unpacking nature. When a tuple is created, values are "packed" into it. However, Python allows you to extract (or "unpack") these values into variables as needed, making it a versatile data structure.

Basic Unpacking

Tuple unpacking allows us to assign multiple values from a tuple to variables in a single line.

fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits  # Unpacking tuple values into variables

print(green)   # Output: apple
print(yellow)  # Output: banana
print(red)     # Output: cherry

However, If there are more values than variables, you can use * to collect the remaining values into a list.

Unpacking with * (Assigning Remaining Values to a List)

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits  # Assigns first two values to variables, rest to "red"

print(green)  # Output: apple
print(yellow) # Output: banana
print(red)    # Output: ['cherry', 'strawberry', 'raspberry']  # Rest assigned as a list

Unpacking When * is Not the Last Variable

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits  # First value goes to "green", last to "red", rest to "tropic"

print(green)  # Output: apple
print(tropic) # Output: ['mango', 'papaya', 'pineapple']
print(red)    # Output: cherry

You can iterate through a tuple using loops, join two tuples with the + operator, and repeat a tuple’s elements using the * operator.

I hope this article has clarified key Python concepts. If you're navigating tech or learning to code, stay motivated, prioritize your learning, choose suitable resources, ask questions, seek mentorship, and keep practicing.

To celebrate Women’s Month, I’m launching the EmpowerHer Mentorship Program in March-April 2025, offering free mentorship for women in technology, entrepreneurship, cybersecurity, and more. This initiative aims to empower women with personalized guidance to build skills and advance their careers.

Here’s the registration link for prospective mentees to sign up and book mentorship sessions. #AccelerateAction


Sources: Some content in this article has been sourced from W3Schools and GeeksforGeeks.

Image Credits: Images sourced from 4K Wallpapers, Alpha Coders, and other web sources.