How to indent block of code in python

You're going to have to change the number of spaces in front of one or more lines of code. It's common in programming like Python. Moving them in is indenting. Moving them out is dedenting (or deindenting).

For example, if you want to move a print statement from the main part of the program into the code block of a loop, you need to indent it. To move it out of the code block of a loop, you need to deindent it. IDLE has tools to indent and dedent code blocks.

Try those -denting tools:

  1. Start with some code.

    Here's some:

    ""This is just a test file""
    DEBUG = True
    print('Hello World! from the editor') # hashes are used for comments too
    "" You usually use hashes at the end of a line
    rather than for a block comment like this one.
    ""
    ###############################################################
    # Nevertheless you can still use hashes for block comments
    # Especially if you want to have a specific visual effect
    ###############################################################
    if DEBUG:
        print('I think I need another print statement in this code block')
    print('See that the comments were ignored?') # even this one
  2. Select the lines to indent.

    Click and drag with your mouse to select the code (the last print statement), or press Shift while using your arrow keys.

  3. Choose Format → Indent Region.

    Ctrl+] also works.

  4. Make sure the code's indented into a valid code block.

    Indentation is meaningful to Python. You'll get a syntax error if you have the wrong level of indent.

    It's best to use four spaces of indent for each code block level. If you use another number of spaces (2, 6, 8), that's fine. The important thing is that all the code in the code block must have the same number of spaces.

    To go the other way, select the code and choose File → Dedent Region (or press Ctrl+[).

About This Article

This article is from the book:

  • Python For Kids For Dummies ,

About the book author:

Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.

This article can be found in the category:

  • Python ,

This chapter is from the book

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.

How do you indent a block of code?

You (these are the default settings I believe) can select a block of code and press the Tab key. This will indent the entire block. So for indenting a whole file: Ctrl + A , then Tab . You can move through the open tabs with Ctrl + Shift + Tab .

How do you indent text in Python?

You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the textwrap. indent() function which was added to the module in Python 3.3.

How do you indent a block of code in Python Pycharm?

If you need to adjust indentation settings, in the Settings/Preferences dialog ( Ctrl+Alt+S ), go to Editor | Code Style. On the appropriate language page, on the Tabs and Indents tab, specify the appropriate indents options and click OK.

How do you indent a block of code in Python Mac?

It is Ctrl + [ in IDLE. You can change it to your favorite Shift + Tab in Options -> Configure IDLE - Keys.