TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Statement and Indentation Explained
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Statement and Indentation Explained

Last updated: Apr 23, 2024 9:30 pm
By Meenakshi Agarwal
Share
10 Min Read
Python Statement, Multi-line Statement, Expression And Indentation
SHARE

A Python statement is the most basic executable element of the code. The other entities around it are indentation and expressions. In this tutorial, we’ll explain each of them in detail and the difference between them. This tutorial also contains several examples to explain the concept more clearly.

Contents
What is a Statement in Python?What is an Expression in Python?Simple Assignment StatementCase-1: The right-hand side (RHS) is just a value-based expression.Case-2: The right-hand side (RHS) is a current Python variable.Case-3: The right-hand side (RHS) is an operation.Augmented Assignment OperatorMulti-line Statement in PythonExplicit line continuationImplicit line continuationPython IndentationHow many spaces is an indent in Python?Why is indentation so crucial in Python?Short Summary

Understand Python Statement, Indentation, and Expression

We’ll walk you through many topics in this tutorial. Starting from a single statement to multiline statements, we’ll cover how to use indentation and expressions in your Python programs.

We’ll try to answer questions like “Why is indentation so important in Python?”, “How many spaces is an indent in Python?” and so on.

What is a Statement in Python?

A statement in Python is a logical instruction that a Python interpreter can read and execute. In Python, it could be an expression or an assignment statement.

The assignment statement is fundamental to Python. It defines the way an expression creates objects and preserves them.

Let’s now find out more details on this topic.

What is an Expression in Python?

An expression is a type of Python statement that contains a logical sequence of numbers, strings, objects, and operators. The value in itself is a valid expression and so is a variable.

Using expressions, we can perform operations like addition, subtraction, concatenation, and so on. It can also have a call to a function which evaluates results.

Also Read: What are Keywords in Python?

Examples

# Using Arithmetic expressions
>>> ((10 + 2) * 100 / 5 - 200)
40.0
# Using functions in an expression
>>> pow(2, 10)
1024
# Using eval in an expression
>>> eval( "2.5+2.5" )
5.0

Simple Assignment Statement

In a simple assignment, we create new variables, assign values, and modify them. This statement provides an expression and a variable name as a label to preserve the value of the expression.

# Syntax
variable = expression
# LHS <=> RHS

Let’s now take a close look at three types of assignment statements in Python and see what’s going on under the hood.

Case-1: The right-hand side (RHS) is just a value-based expression.

Let’s consider the most basic form of assignment in Python.

>>> test = "Learn Python"

Python will create a string “Learn Python” in memory and assign the name “test” to it. You can confirm the memory address with the of a built-in function known as id().

>>> test = "Learn Python"
>>> id(test)
6589040

The number is the address of the location where the data lives in memory. Now, here are a few interesting points which you should know.

1. If you create another string with the same value, Python will create a new object and assign it to a different location in memory. So this rule would apply to most of the cases.

>>> test1 = "Learn Python"
>>> id(test1)
6589104
>>> test2 = "Learn Python"
>>> id(test2)
6589488

2. However, Python will also allocate the same memory address in the following two scenarios.

  • The strings don’t have whitespaces and contain less than 20 characters.
  • In the case of Integers ranging between -5 to +255.

This concept is known as Interning. Python does it to save memory.

Case-2: The right-hand side (RHS) is a current Python variable.

Let’s take up the next type of assignment statement where the RHS is a current Python variable.

>>> another_test = test

The above statement won’t trigger any new allocation in memory. Both the variables would point to the same memory address. It’s like creating an alias for the existing object. Let’s validate this by using the id() function.

>>> test = "Learn Python"
>>> id(test)
6589424
>>> another_test = test
>>> id(another_test)
6589424

Case-3: The right-hand side (RHS) is an operation.

In this type of statement, the result would depend on the outcome of the operation. Let’s analyze it with the following examples.

>>> test = 2 * 5 / 10
>>> print(test)
1.0
>>> type(test)
<class 'float'>

In the above example, the assignment would lead to the creation of a “float” variable.

>>> test = 2 * 5
>>> print(test)
10
>>> type(test)
<class 'int'>

In this example, the assignment would lead to the creation of an “int” variable.

Augmented Assignment Operator

You can combine arithmetic operators in assignments to form an augmented assignment statement.

Check out the below examples for the augmented assignment operator.

x += y

The above statement is a shorthand for the below simple statement.

x = x + y

The next one is a bit clearer example where we are appending new elements to the tuple.

>>> my_tuple = (10, 20, 30)
>>> my_tuple += (40, 50,)
>>> print(my_tuple)
(10, 20, 30, 40, 50)

Let’s take another example that has a list of vowels. It demonstrates the addition of missing vowels to the list.

>>> list_vowels = ['a','e','i']
>>> list_vowels += ['o', 'u',]
>>> print(list_vowels)
['a', 'e', 'i', 'o', 'u']

Multi-line Statement in Python

Usually, every Python statement ends with a newline character. However, we can extend it over to multiple lines using the line continuation character (\).

Also Read: Multiline Strings in Python

And, Python gives us two ways to enable multi-line statements in a program.

Explicit line continuation

When you right away use the line continuation character () to split a statement into multiple lines.

Example

# Initializing a list using the multi-line statement
>>> my_list = [1, \
... 2, 3\
... ,4,5 \
... ]
>>> print(my_list)
[1, 2, 3, 4, 5]
# Evalulate an expression using a multi-line statement
>>> eval ( \
... " 2.5 \
... + \
... 3.5")
6.0

Implicit line continuation

Implicit line continuation is when you split a statement using either parentheses ( ), brackets [ ], or braces { }. You need to enclose the target statement using the mentioned construct.

Example

>>> result = (10 + 100
... * 5 - 5
... / 100 + 10
... )
>>> print(result)
519.95

Another Example

>>> subjects = [
... 'Maths',
... 'English',
... 'Science'
... ]
>>> print(subjects)
['Maths', 'English', 'Science']
>>> type(subjects)
<class 'list'>

Python Indentation

Many of the high-level programming languages like C, C++, and C# use braces { } to mark a block of code. Python does it via indentation.

A code block that represents the body of a function or a loop begins with the indentation and ends with the first unindented line.

How many spaces is an indent in Python?

Python style guidelines (PEP 8) state that you should keep an indent size of four. However, Google has its unique style guideline which limits indenting up to two spaces.

So you too can choose a different style, but we recommend following the PEP8.

Why is indentation so crucial in Python?

Most programming languages provide indentation for better code formatting but don’t enforce it.

However, in Python, it is mandatory to obey the indentation rules. Typically, we indent each line by four spaces (or by the same amount) in a block of code.

In the examples of the previous sections, you might have seen us writing simple expression statements that didn’t have the indentation.

However, for creating compound statements, the indentation will be utmost necessary.

Example

def demo_routine(num):
 print('I am a demo function')
 if num % 2 == 0:
 return True
 else:
 return False

num = int(input('Enter a number:'))
if demo_routine(num) is True:
 print(num, 'is an even number')
else:
 print(num, 'is an odd number')

Now, also see a scenario when undesired indentation causes an error. So let’s try indenting a simple expression statement.

>>> 6*5-10
 File "<stdin>", line 1
 6*5-10
 ^
IndentationError: unexpected indent

Short Summary

If you plan to become a professional Python programmer who follows good coding practices, knowing about Python statements, expressions, and indentation is a must.

Hence, get the most out of this tutorial, practice with the examples, and use Python in the interactive mode. It has a reasonable command history capability, so you can use the up-arrow key to recover a previous statement.

If you learned something new today, then don’t mind sharing it further. And, follow us on our social media accounts to get quick updates.

Happy Learning,
TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Write Your First AngularJS App Your First AngularJS Application
Next Article Python Comment, Multiline Comment, & DocString Python Comment vs Multiline Comment

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x