Python Statement

The Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an assignment statement. if statement, for statement, while statement etc. are other kinds of statements which will be discussed later.

What is Statement

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

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

Multi-line statement

In Python, end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\). For example:

1

2

3

a=1+2+3+\

4+5+6+\

7+8+9

This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as

1

2

3

a=(1+2+3+

4+5+6+

7+8+9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For example:

1

2

3

colors=['red',

'blue',

'green']

We could also put multiple statements in a single line using semicolons, as follows

1

a=1;b=2;c=3

Expression Statement

An expression is a type Python statement which contains a logical sequence of numbers, strings, objects, and operators. The value in itself is a valid expression and so it 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.

1

2

3

4

5

6

7

8

9

10

11

# Using Arithmetic expressions

>>>((10+2)*10/2-20)

40.0

# Using functions in an expression

>>>pow(2,5)

32

# Using eval in an expression

>>>eval("2.5+2.5")

5.0

Assignment Statement

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects.

Here is the general form or syntax of an assignment statement:

1

target0=target1=...=expression

In most cases, there will be one target that is a name. Python will evaluate the expression, reducing it to a single value, and then bind that name to that value.

A binding is an association between name and a value.

It is important to note that in Python, unlike many other languages, names themselves are not associated with a specific type. A name is just a label, and it can be bound to any value of any type at any time.

In this example, name x is bound first to an int value 5, then to a str value ‘Hello World’.

1

2

3

4

5

6

>>>x=5

>>>x

5

>>>x='Hello World'

>>>printx

Hello World

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.