'Zhuan' Python Beginner Tutorial 4 — if Statements

The original poster: , cool A Views: 424 Replies: 4 Posted in: 2012-04-18 17:01:59
File Description: Python Beginner Lesson 4 — If Statements. What is an if statement? Literally, 'if' means 'if,' so an if statement is also called a conditional statement. If the condition is true, a block of code will execute; if it is not true, it will not execute. It's easy to understand, right!

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!
× Preview
reply 🤍 0 📤 share collect
Download Attachment 4
Um, learning the PY platform takes time. I got to know PY in the Spicy Pepper development team.
Statement, assignment statement
Hehe, we learned it in the first year of high school~
— All replies loaded —

Leave a Reply