This article is participating in Python Theme Month. See the link to the event for more details

directory

In this blog, you’ll learn about Python statements, expressions, and the differences between them. This tutorial also includes several examples to explain this concept more clearly.

Next, we’ll explain how to use multi-line statements and indentation in Python programming.

In addition, I’ll try to answer questions like “Why is indentation so important in Python?” “, “How many Spaces are indented in Python? And so on.

๐ŸŽช i. Statements in Python

๐Ÿง 1.1 What is a statement?

Statements in Python are logical instructions that can be read and executed by the Python interpreter. In Python, it can be an expression or an assignment statement.

Assignment statements are the foundation of Python. It defines how expressions create and store objects.

๐Ÿฐ 1.2 What is an expression

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

Using expressions, we can add, subtract, join, and so on. It can also call a function that evaluates the results.

example

# Use arithmetic expressions
>>> ((10 + 2) * 100 / 5 - 200)
40.0
Copy the code
Use functions in expressions
>>> pow(2.10)
1024
Copy the code
# Use eval in expressions
>>> eval( "2.5 + 2.5" )
5.0
Copy the code

Return to the directory


๐Ÿš’ 1.3 Simple assignment statement

In a simple assignment, we create new variables, assign values, and change values. This statement provides an expression and a variable name as tags to hold the expression’s value.

# Syntax
variable = expression
# LHS <=> RHS
Copy the code

Now let’s take a closer look at the three assignment statements in Python to see what happens.

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"
Copy the code

Python will create a string “Learn Python” in memory and assign the name “test” to it. You can use a built-in function called id() to verify the memory address.

>>> test = "Learn Python"
>>> id(test)
6589040
Copy the code

The number is the address of where the data is located in memory. Now, here are some interesting things you should know.

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

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

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

  • The string has no Spaces and contains less than 20 characters.
  • If the integer ranges from -5 to +255.

This concept is called Interning. Python does this to save memory.

Case 2: The right (RHS) is the current Python variable.

Let’s discuss the next type of assignment statement, where RHS is the current Python variable.

>>> another_test = test
Copy the code

The above statement does not trigger any new allocations in memory. Both variables point to the same memory address. This is like creating an alias for an existing object. Let’s verify this using the id() function.

>>> test = "Learn Python"
>>> id(test)
6589424
>>> another_test = test
>>> id(another_test)
6589424
Copy the code

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

In this type of statement, the result will depend on the result of the operation. Let’s analyze it with the following example.

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

In the example above, assignment results in the creation of a “float” variable.

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

In this example, the assignment results in the creation of an “int” variable.

Return to the directory


๐Ÿฌ 1.4 Enhanced assignment statements

You can combine arithmetic operators in assignments to form extended assignment statements.

See the following example for enhanced assignment statements.

x += y
Copy the code

The above statement is shorthand for the following simple statement.

x = x + y
Copy the code

Next, for a clearer example, we add new elements to the tuple.

>>> my_tuple = (10.20.30)
>>> my_tuple += (40.50.)>>> print(my_tuple)
(10.20.30.40.50)
Copy the code

The next example uses a vowel list. It is demonstrating the addition of missing vowels to a list.

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

Return to the directory


๐ŸŽข Multiline statements in Python

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

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

๐ŸŽ  2.1 Explicit line continuation

When you immediately use line continuation () to split a statement into multiple lines.

example

# Initialize a list with a multi-line statement
>>> my_list = [1, \
.2.3\
..4.5 \
.]
>>> print(my_list)
[1.2.3.4.5]
Copy the code
Evaluate expressions using multi-line statements
>>> eval(\."2.5 \... + \... 3.5")
6.0
Copy the code

๐ŸŽก 2.2 Implicit line continuation

Implicit continuation is a split statement that uses any of the brackets (), square brackets [], and braces {}. You need to enclose the target statement with the constructs mentioned.

example

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

Another example

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

Return to the directory


๐ŸŽฏ 3. Indent Python

Many high-level programming languages (such as C, C++, C#) use braces {} to mark blocks of code. Python does this by indentation.

A block of code representing the body of a function or loop begins with an indent and ends with the first unindent line.

๐Ÿงต 3.1 How many Spaces are there in indentation in Python?

The Python Style Guide (PEP 8) states that the indentation size should remain 4. Google, however, has its own unique style guide that limits indentation to two Spaces. So you can also choose different styles, but we recommend following PEP8.

๐Ÿ›ซ 3.2 Why is indentation important?

Most programming languages provide indentation for better code formatting and are not mandatory.

In Python, however, you must follow the indentation rules. Typically, we indent each line in a code block by four Spaces (or the same amount).

In the examples in previous sections, you might have seen that we wrote simple expression statements without indentation.

However, in order to create compound statements, indentation will be 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')
Copy the code

Now, you can also see the scenario where the unwanted indentation led to the error. So let’s try to indent a simple expression statement.

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

Return to the directory


๐ŸŽฐ Quick summary — Python statements, expressions, and indentation

If you’re going to be a professional programmer who believes in clean coding practices, it’s important to know Python statements, expressions, and indentation. I’ve tried to cover all the relevant details about them so that you can learn them quickly and use them effectively.

If you enjoyed this article and are interested in seeing more of it, you can check out the source code for all my originals and works here:

Making, Gitee

Related articles

  • Python keywords, identifiers, and variables | Python theme month
  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 100 Basic Python Interview Questions Part 5 (81-100) | Python topic month
  • 30 Python tutorials and tips | Python theme month

Recommended articles of the past:

  • Teach you to use Java to make a gobang game
  • Interesting way to talk about the history of JavaScript โŒ›
  • The output of a Java program | Java exercises ใ€‘ ใ€ 7 sets (including parsing)
  • โค๏ธ5 VS Code extensions that make refactoring easy โค๏ธ
  • It is said that if you have light in your eyes, everywhere you go is light
  • 140000 | 400 multichannel JavaScript ๐ŸŽ“ interview questions with answers ๐ŸŒ  items (the fifth part 371-424)

If you do learn something new from this post, like it, bookmark it and share it with your friends. ๐Ÿค— Finally, don’t forget โค or ๐Ÿ“‘ for support