Basic Examples

To demonstrate, let’s look at a few simple examples of the if statement at work. All parts are optional, except the initial if test and its associated statements. Thus, in the simplest case, the other parts are omitted:

>>> if 1:
...     print('true')
...
true

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Notice how the prompt changes to ... for continuation lines when typing interactively in the basic interface used here; in IDLE, you’ll simply drop down to an indented line instead (hit Backspace to back up). A blank line (which you can get by pressing Enter twice) terminates and runs the entire statement. Remember that 1 is Boolean true, so this statement’s test always succeeds. To handle a false result, code the else:

>>> if not 1:
...     print('true')
... else:
...     print('false')
...
false