Format of an if statement:
if (condition):
code block
We can also add else: code block afterwards. Adding it means that if the if condition is not met, the else block will execute. We can also add another code block between if and else.
Before looking at the code, let's learn about indentation.
Indentation is dividing long code blocks into two, three, or more lines, without the compiler reading it as a new block. Beginners must pay special attention to this because the compiler we use doesn't automatically handle indentation, so many times errors occur due to improper indentation. Usually, we indent with four spaces.
Usage — see the code in Figure 1.
Note: Because spaces cannot be used here in Lexun, I use ~ to represent spaces.
a = 10
if (a > 5):
# If greater than 5, print the following statement
~~~~print 'a > 5'
else:
# Otherwise, print the following statement
~~~~print 'a < 5'
Some friends may ask, why not let the program ask for a number to assign to a? Good question! It's not that we can't, it's just that our foundation isn't enough yet. We will learn this in the intermediate tutorial.
Alright, isn't it very simple? If you still don't understand, watch it a few more times and ask if needed.
The above two files are the code for Figures 3 and 4, converted to .py files.
Replying is a virtue! Visa status: Not required\Also, there is an attachment on the first floor!