What is code block in python?

Block

What is code block in python?

In Python, code block refers to a collection of code that is in the same block or indent. This is most commonly found in classes, functions, and loops.

You can where code blocks are because they are 1) on the same indent and 2) are uninterrupted by other lines of code not on the same indent.

Python code blocks are useful because they tell you what pieces of code will run as a part of a loop, class, or function.

def code_block():
  # Everything in this function is part of the same code block
  print (1)
  print (2)
  
for i in range(4):
  # Everyting in this loop is part of the same code block
  print (i)

Let’s take a look at a python to assign a variable code sample.

Python Code Block¶

A code block is a collection of code that sits on the same indent. Think of it like a line of code and it's cousins, brothers, or sisters.

Let's take a look at a few code blocks.

In [1]:

for i in range(4):
    print (i)

In [3]:

for i in range(4):
    print (i)
    print (i * 2)

All the code that sits within a function is also a code block

In [6]:

def my_code():
    x = 5 # same block
    x = x + 4 # same block
    print (x) # same block

my_code() # Not on the same block of code as above

Check out more Python Vocabulary on our Glossary Page

Python> Code block

If statements don't decide on skipping or running the entire code. They only make decisions about a code block.

if True:
  print("I'm a code block!")

We use an indentation of two spaces to highlight code blocks, like how we indented the display statement two spaces to the right.

if True:
  print("I'm two spaces away!")

A code block can be more than a one-liner. All lines with the same indentation belong to the same code block.

We can see it here when we use print() to add one more line at the beginning.

if True:
  print("Look at me!")
  print("I'm a code block")

TRY IT ON THE APP

What is code block in python?

It is generally good practice for you not to mix tabs and spaces when coding in Python. Doing this can possibly cause a TabError, and your program will crash. Be consistent when you code - choose either to indent using tabs or spaces and follow your chosen convention throughout your program.

Code Blocks and Indentation

One of the most distinctive features of Python is its use of indentation to mark blocks of code. Consider the if-statement from our simple password-checking program:

if pwd == 'apple':
    print('Logging on ...')
else:
    print('Incorrect password.')

print('All done!')

The lines print(‘Logging on …’) and print(‘Incorrect password.’) are two separate code blocks. These ones happen to be only a single line long, but Python lets you write code blocks consisting of any number of statements.

To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python.

In most other programming languages, indentation is used only to help make the code look pretty. But in Python, it is required for indicating what block of code a statement belongs to. For instance, the final print(‘All done!’) is not indented, and so is not part of the else-block.

Programmers familiar with other languages often bristle at the thought that indentation matters: Many programmers like the freedom to format their code how they please. However, Python indentation rules are quite simple, and most programmers already use indentation to make their code readable. Python simply takes this idea one step further and gives meaning to the indentation.

If/elif-statements

An if/elif-statement is a generalized if-statement with more than one condition. It is used for making complex decisions. For example, suppose an airline has the following “child” ticket rates: Kids 2 years old or younger fly for free, kids older than 2 but younger than 13 pay a discounted child fare, and anyone 13 years or older pays a regular adult fare. The following program determines how much a passenger should pay:

# airfare.py
age = int(input('How old are you? '))
if age <= 2:
    print(' free')
elif 2 < age < 13:
    print(' child fare)
else:
    print('adult fare')

After Python gets age from the user, it enters the if/elif-statement and checks each condition one after the other in the order they are given. So first it checks if age is less than 2, and if so, it indicates that the flying is free and jumps out of the elif-condition. If age is not less than 2, then it checks the next elif-condition to see if age is between 2 and 13. If so, it prints the appropriate message and jumps out of the if/elif-statement. If neither the if-condition nor the elif-condition is True, then it executes the code in the else-block.

Conditional expressions

Python has one more logical operator that some programmers like (and some don’t!). It’s essentially a shorthand notation for if-statements that can be used directly within expressions. Consider this code:

food = input("What's your favorite food? ")
reply = 'yuck' if food == 'lamb' else 'yum'

The expression on the right-hand side of = in the second line is called a conditional expression, and it evaluates to either ‘yuck’ or ‘yum’. It’s equivalent to the following:

food = input("What's your favorite food? ")
if food == 'lamb':
   reply = 'yuck'
else:
   reply = 'yum'

Conditional expressions are usually shorter than the corresponding if/else-statements, although not quite as flexible or easy to read. In general, you should use them when they make your code simpler.

Python Documentation - Indentation


Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

What is code block in Python with example?

In Python, each line of a code block must be indented by the same amount of whitespace. The while loop's two lines of code are both four spaces indented. A statement must be labeled with the code block to which it belongs. For example, i=1 and while (i=4) are not indented and thus do not belong in the while block.

What is meant by code block?

In computer programming, a block or code block or block of code is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements.

What is block code example?

Examples of block codes are Reed–Solomon codes, Hamming codes, Hadamard codes, Expander codes, Golay codes, and Reed–Muller codes. These examples also belong to the class of linear codes, and hence they are called linear block codes.