Python: Indenting Multiple Lines of Code At Once


This is very basic but super helpful. Say, you start off building a block of code and then later on you want to take those many lines of code and want to add it into a for-loop or an if-statement (that will need an indent). You can easily do this by highlighting all the code you want to indent and hitting the Tab key.

Example Code:

#Hypothetical Stock Company Ranks
stock_df['Dividend_Yld_Rank'] = stock_df['Dividend Yield'].rank(ascending=True, pct=True) 
stock_df['Earnings_Rank'] = stock_df['Earnings'].rank(ascending=True, pct=True)
stock_df['Value_Rank'] = stock_df['Value'].rank(ascending=True, pct=True)
stock_df['Price_Growth_Rank'] = stock_df['Price_Growth'].rank(ascending=True, pct=True)

Highlight all the code you want to indent

highlighted_python_code

and then hit the Tab key and voila – indented code.

#Hypothetical Stock Company Ranks
stock_df['Dividend_Yld_Rank'] = stock_df['Dividend Yield'].rank(ascending=True, pct=True) 
stock_df['Earnings_Rank'] = stock_df['Earnings'].rank(ascending=True, pct=True)
stock_df['Value_Rank'] = stock_df['Value'].rank(ascending=True, pct=True)
stock_df['Price_Growth_Rank'] = stock_df['Price_Growth'].rank(ascending=True, pct=True)

See more programming posts on our Python Page