Python Crash Course study notes - Chapter 5: IF STATEMENTS

A simple example

$ cat months.py
months = ['jan', 'feb', 'march', 'apr']
for m in months:
        if m == 'apr':
                print(m.upper())
        else:
                print(m.title())
$ python months.py
Jan
Feb
March
APR

Points should be noted:

  1. if and else end of the sentence has a semicolon ( :)
  2. Equal use ==, instead =. The latter represents the assignment.
  3. In row 4 for loop is indented

Test conditions

if a conditional test, return Trueand False. Note that these two values is case sensitive.
Test for equality with ==, and C language. It is not equal with !=.

>>> n=1
>>> n==1
True
>>> n=1
>>> n==2
False
>>> n != 2
True

Comparison string is case-sensitive, can be done with a lower or upper case-insensitive comparison method does not.
Comparative figures can also be used >, <, >=and<=

To bind a plurality of test conditions can be used and, or.
Plus recommendations for each condition (), the priority has been to avoid speculation.

Checking whether a value in the list, inand not in:

>>> nums=[1,2,3,4]
>>> 2 in nums
True
>>> 5 in nums
False
>>> 5 not in nums
True

Test conditions has become a Boolean expression that returns a Boolean value, namely True, or False:

>>> a = True
>>> a
True
>>> a = False
>>> a
False
>>> a = TRUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'TRUE' is not defined

The if statement

The first form of the if statement:

if conditional_test:
    do something

The second form:

if conditional_test:
    do something
else:
	do something

The most complex form, which elif may appear multiple times. elif and else are not required:

if conditional_test:
	do something
elif:
	do something
else:
	do something

The if statement in conjunction with the List

After addition if may determine whether List List is empty:

>>> months=[]
>>> if months:
...     print('list is not empty')
...
>>> if not months:
...     print('list is empty')
...
list is empty

if it can be combined with List for loop

>>> nums=[1,2,3,4]
>>> for n in nums:
...     if n == 4:
...             print('My birth month')
...
My birth month

Beautify the if statement

Before and after comparison symbols require a single space. For example, a > 4it is better than a>4.

发布了352 篇原创文章 · 获赞 42 · 访问量 55万+

Guess you like

Origin blog.csdn.net/stevensxiao/article/details/103983343