When To Use Colon (:) in Python?

When To Use A Colon In Python

As we all know, Python is an easy-to-use and implement language with many freedoms in its syntax. This makes it perfect for even a beginner for making things like applications to design efficiently. But, like every other language, it also has some of the basic rules and regulations on which the whole code runs and depends. So, in this article, we shall learn them. This is important for our programming aspect.

Introduction to Python and PEP8

Now. to make things clear let us look at the features of Python.

  1. Object-Oriented
  2. Multi-Paradigm
  3. Cross-Platform

The main thing that makes python different is that it runs on an Interpreter. This runs the code line-by-line and then executes.

An essence of PEP8

We can say that Python Enhancement Proposals (PEP) is the official book or set of rules that tell us how we can write the best Python codes. It also provides a set of restrictions or not-to-do things while programming. Some of them are as follows:

  1. Modules shall not have short lowercase names.
  2. Class names should be in CapWords style.
  3. Most variables and function names should be lowercase_with_underscores.
  4. Constants should be in CAPITAL_WITH_UNDERSCORES – this helps in identifying them.
  5. Use sufficient spaces between parameters, and operators to make the codes more readable.

To get more PEP info we can open the Python shell and in there type the following command:

>>> import this

Output:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

The importance of colons in Python

So, in some of the interpreted languages, curly braces are not crucial. Rather we work with “colons”.’ Unlike other languages say JavaScript and Ruby, Python has most of the important syntax in which the colon is important. Here is a list of those:

  1. List slicing.
  2. String slicing.
  3. In dictionaries for inserting key-value pairs.
  4. Function declaration
  5. Loop declarations
  6. Conditional Statements
  7. To increase the function readability.
  8. Class declaration.

NOTE: Indexing starts from 0 in lists and strings. For more reference please read this article: https://www.askpython.com/python/list/negative-indexing

1. List Slicing

The list is an important data structure to implement and study in Python. It is just like a dynamic array where we can insert elements of multiple data types. In lists, we use the colon to retrieve a particular element. They work on index numbers. So, we can use them to get elements concerning the index position.

Syntax to fetch elements:

a = [0 : n -1] # indexing in lists starts from zero till n -1 

Example:

>>> a = [5, -9, 8, 33, 4, 64] # declaring a list
>>> a[:] # retrieving all the elements
[5, -9, 8, 33, 4, 64]
>>> a[2:3] # retrieing the elements from third index and ignoring the fourth index
[8]
>>> a[4:] # retrieving the elements above fifth till last index
[4, 64]
>>> a[1:] # retrieving the elements above second index
[-9, 8, 33, 4, 64]

2. String Slicing

The string is another data type in Python that makes enclosing a long set of sentences within quotes. In the old programming paradigm, a string is a sequence of characters. Python follows the same approach to retrieving single characters from a string. They are immutable (un-editable) but we can fetch characters. In memory, they are stored in a character array. So, to get them colon is used:

Also read: How to Slice Strings in Python?

Syntax to fetch characters:

s = [0 : n -1] # indexing in strings starts from zero till n -1 

Example:

>>> s = "abcdefgh"
>>> s[2:4] # fetch characters from third till fifth index
'cd'
>>> s[::-1] # reverse the string
'hgfedcba'
>>> s[:-2] # print the string ignoring the second and last characters
'abcdef'
>>> s[1:5]  # print the elements from second till 
'bcde'

3. In dictionaries for inserting key-value pairs

The dictionaries in Python are an unordered collection of key-value pairs. They are one of the fundamental data structures like hashmaps in Java. But, their syntax declaration is much more different.

Syntax to declare a dictionary:

d = {key_1 : value_1, key_2 : value_2, key_3 : value_3, ..., key_N : value_N}

As we can see that the colon is an important entity here. Without this symbol, dictionaries cannot exist in Python.

Example:

 >>> d = {"a" : 1, "b" : 2, "c" : 3, "d" : 4} # declaring a dictionary

4. Function declaration

The general syntax for function involves a colon. This is because Python uses indentation (empty code spaces) instead of curly braces “{ }” to retain the block of code under functions. After the function and parenthesis, we need to use the colon to start writing code inside the function.

Syntax:

def func_name(param_1, .., param_2): ->  colon used here
    # fuction code lies below colon and is considered as its code body

    return # value

5. Loops declaration

The loops in Python are statements that continuously execute a piece of code until the code meets a specific condition. So, to execute a for() or a while() loop, we use a colon. All the code under the colon is considered as the part of the loop if and only if it takes proper indentation.

Example:

for i in range(4): # -> colon is used here
    print(i) 


#Output:
# 0
# 1 
# 2
# 3

So, as we saw that the code under the colon symbol is giving out numbers from 0 to 3. The same way we can use it in while loop.

i = 0
while i != 5: # -> colon is used here
    i += 1
    print(i)
# output
# 1
# 2
# 3
# 4
# 5

6. Using conditional statements

The conditional statements are special blocks of code. They are decision-making statements that execute a block of code when the expressions inside it evaluate to true. We use colons in them also. They are placed after the condition and the interpreter recognizes that the indented code is under the conditional block.

if condition: # -> colon is used here
    # code body

else: # -> colon is used here
    # code body

7. To increase the function readability

This somewhat advances the python topic. The beginners can simply ignore this one. Like in statically typed programming languages where we need to specify the data type and return type of the variables and functions, Python allows the same but with a different kind of syntax:

Let us say that we declare a function and we need to explicitly mention the data type. There is a simple way we can do it:

  1. When declaring the parameters inside the function use the datatype with colon and then the parameter name.
  2. Then, to mention what the function returns insert the datatype after the parenthesis using the arrow operator (->).
def add(a : int, b : int)->int:
    c = a + b
    print(c)
    return c

add(3, 4)

# outputs 7

Te colon lies between the parameter name and its data type.

8. For declaring classes

Python is an OOP language. So, to declare classes we need to use the colons. The colon decides the scope of a variable and the function of a class. This is to signal the interpreter that entities of a class lie under a colon. Here is one simple example:

Code:

class Sample:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        
    def printVal(self):
        print(self.a, self.b)
        
sample = Sample(3, 4)
sample.printVal()  

# outputs: 3, 4

so, in this class, we insert a colon. After that give an indentation of four spaces. This will make sure that everything is under the class scope. So, to make things more clear we can declare a constructor __init__() method and printVal() method.

The error and common mistakes that happen when using colons

When we declare a function or a loop or any block of code where a colon is necessary, there is an important rule we need to follow. If we fail to do so, then things go wrong and the code ends up giving an error.

When we give a colon, always remember to give an indentation/empty space. This defines the scope of the further code under that parent code.

Modern code editors have a built-in auto-indentation setting. But, when using Notepad, we need to be more careful.

Example – using a function:

def sayHello():
print("Hello world")

sayHello()

Example – for loop:

for i in range(0, 3):
    
print(I)

Example – if conditional:

if (i % 2 == 0):
print(i)

Output:

IndentationError: expected an indented block

Conclusion

So, in this way, we can consider that colon is an important or a heart piece of Python’s syntax tree. Remember we can get into very much trouble if we miss even a single colon in our code. So, I recommend carefully reading this article if you are a newbie in Python programming.