if…else条件判断

计算机之所以能做很多自动化的任务,是因为它可以自己做条件判断。比如,根据用户年龄,打印不同的内容。在Python中可以使用if语句实现条件判断:

age = 20
adult = False
if age >= 18:
    adult = True

if 语句的一般形式如下,每个条件判断后加冒号:,然后是满足条件后要执行的语句块。在Python我们使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。(补充:Python没有switch-case语句)

if condition_1:
    statement_block_1 # Execute if condition_1 is True
elif condition_2:
    statement_block_2 # Execute if condition_1 is False & condition_2 is True
elif condition_3:
    statement_block 3 # Execute if condition_3 is True and 1 & 2 are False
else:
    statement_block_3 # Execute if previous conditions are all Falser 

具体例子:

age = 12 
if age = 13 and age <= 18:
    print(“teenager”)
else:
    print(“adult”)

条件判断类型

条件判断类型:布尔语句,查询是否相等或不等,区分大小写,数值比较,数组条件判断,多个条件判断(使用and,or)

布尔判断:

# Boolean check
game_over = True
if game_over:
    print('Game Over :(')
    
alive = False
if alive: 
    print('Alive')
else:
    print('You died :(')

数值比较:

# Numerical comparisons
age = 18
print(age == 18)
# , =
if age <= 21:
    print('You can\'t drink!')

if 常用的操作运算符,等号的判断使用的是 ==,=是用来赋值的

操作符描述
<小于
<=小于或等于
>大于
>=大于或等于
==等于,比较两个值是否相等
!=不等于

字符串相等性比较:

# check for equality
car ='bmw'
print(car == 'bmw')
print(car == 'audi')
# checking for equality is case sensitive
print(car == 'Bmw')
print(car.upper() == 'BMW')
# checking for inequality
if car != 'audi':
    print('I want an Audi')

列表遍历 + 条件判断:

# simple example use for and if
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

# List checking
cars = ['bmw', 'audi', 'toyota']
if 'bmw' in cars:
    print('I will buy the bmw')
    
programmers = ['enoch', 'fandy']
new_programmer = 'alice'
if new_programmer not in programmers:
    print(f"{new_programmer.title()} should also be hired")

多条件判断(不需要括号):

# Checking multiple conditoins
age_1 = 22
age_2 = 18
if (age_1 >= 21) and (age_2 >= 21):
    print('You can both drink.')
else:
    print('You can\'t drink together.')

# parentheses are not required
if age_1 >= 21 or age_1 >= 21:
    print('one of you can drink.')

age_1 >= 21 and age_2 >= 21

if 嵌套

我们可以把if…elif…else结构放入另一个if…elif…else结构中:

num = int(input(“Please input an number: “))
if num % 2 == 0: 
    if num % 3 == 0:
        print(“Your input can be divisible by 2 and 3”)
    else:
        print(“Your input can be divisible by 2, but cannot be divisible by 3.”)
else:
    if num % 3 == 0:
        print(“Your input can be divisible by 3, but cannot be divisible by 2.”)
    else:
        print(“Your input can’t be divisible by both 2 and 3”)

行内表达式,Python中没有类似其他语言的三目操作符:condition?value1:value2,但是有if-else行内表达式:var = var if condition else var 2

height = 180
result = "tall" if height >= 180 else 'short'
print(result)

While 循环

循环可以帮助更好地执行重复的任务,在Python中,用来控制循环的主要有两个语句,while和for语句,我们先来聊聊while语句的使用。

while语句格式如下,其中condition为判断条件,在Python中就是True和False其中的一个,如果为True,那么将执行expressions语句块,否则将跳过该while语句块借着往下执行。

while condition:
    expressions

比如我们想要打印出数字0~9:

num = 0 
while num < 10:
    print(num)
    num = num + 1

这段代码将会输出0, 1, 2, 3, 4, 5, 6, 7, 8, 9,在第一行num的初始值被设为1,在while判断的时候,如果num < 10是True,将会执行while内部的代码,先打印出num,然后将num的值加1,至此完成一次循环。下一个循环再将num和10比较,如果还是True,重复相同过程,直至num等于10后,num < 10将会为False,就结束了循环。

以下是另一个例子,当条件判断为一个列表的时候,如果列表不为空,那么循环内的语句就会被执行:

a = range(10)
while a:
    print(a[a[-1]])
    a = a[:len(a) - 1] # 使用切片操作去掉最后一个元素

在使用 while 句法的时候一定要注意在循环内部一定要修改判断条件的值,否则会造成“死循环”,也就是说程序的 while 部分将永远执行下去

while True:
    print("Forever ...")

此时,只能使用使用 Ctrl + C 退出程序,或者强制结束 Python 进程。

智能循环:break和continue

为了让程序更加智能,我们需要让循环的结束判断更加智能,在以下的例子中,我们就来学习用不同的方法来结束循环语句。

第一个方法,我们直接根据用户的输入内容来判断是否结束语句:

# Letting the user choose when to quit 
prompt = "Enter 'quit' to end the program."
message = ""
while message != 'quit':
  message = input(prompt)
  print(message)

或者我们使用一个变量当做条件标记,当变量为False时候,循环语句就会自动结束:

# Using a flag
active = True
while active:
  message = input(prompt)
  if message == 'quit':
    active = False
  else:
    print(message)

我们也可以在语句中使用break,当符合break条件时,就直接结束循环:

# Using break to exit a loop
while True:
  city = input(prompt)
  if city == 'quit':
    break
  else:
    print(f"I'd like to go to {city.title()}")

有时我们需要循环能更灵活地执行,我们可以使用continue,直接跳过当前的循环,进入下一次循环:

# Using continue in a loop
num = 0
while num < 10:
  num += 1
  if num % 2 == 0:
    continue
  print(num)

在数组和字典中使用while语句

我们可以使用while语句对list进行更智能的操作。在以下的代码中,我们通过用户的输入,将列表构建起来:

friends = []
prompt = "Enter your friend's name: "
while True:
  friend = input(prompt)
  if (friend == 'q'):
    break
  friends.append(friend)

print(friends)

我们也可以使用循环,将一个列表中的元素全部添加到另一个列表中:

# Moving items from one list to another
unconfirmed_users = ['alice', 'brain', 'candace']
confirmed_users = []
while unconfirmed_users:
  confirmed_users.append(unconfirmed_users.pop())

for user in confirmed_users:
  print(user)

我们还可以通过循环语句,将列表中的某一个特定元素完全删除干净:

# Removing all instances of specific values from a list 
pets = ['dog', 'cat', 'dog', 'cat', 'rabbit', 'cat']
while 'cat' in pets:
  pets.remove('cat')
print(pets)

For 循环

学习了如何使用while语句进行循环控制后,接下来我们来学习另一种循环语句for。以下是for语句在Python中的基本使用方法:

for item in sequence:
    expressions

来看一看两个基础的例子:

list = [1, 2, 3, 4, 5, 6]
for i in list:
    print(i)

# 内置的序列类型 list, tuple, dict, set 都能迭代
tup = ("Python", 1991)
for i in tup:
    print(i)

Range函数

Python中的range函数可以生成一系列的数字:

# range(start, stop)
for i in range(1, 10): 
    print(i)

# range(stop) start from 0
for i in range(10):
    print(i)

# range(start, stop, step)
for i in range(0, 13, 5):
    print(i)

Python中的迭代

Python共内置了list, tuple, dict和set四种序列数据,每个序列对象都能被迭代:

# tuple
tup = ('python', 'java', 'c++')
for i in tup:
    print(i)

# dictionary
dic = {'language': 'Python', 'version': '3.7.4'}
for key in dic: # key是乱序的:输出和插入的顺序不同
    print(key, dic[key])

# set
versions = set(['python2.7', 'python3.0', 'python3.7', 'python2.7'])
for version in versions: 
    print(version) # 输出结果也不是按照输入的顺序

Python 中的 for 句法实际上实现了设计模式中的迭代器模式 ,所以我们自己也可以按照迭代器的要求创造迭代器对象,以便在 for 语句中使用。 只要类中实现了 __iter__和 next 函数,那么对象就可以在 for 语句中使用。 以下我们创建 Fibonacci 迭代器对象:

# define a Fib class
class Fib(object):
    def __init__(self, max):
        self.max = max
        self.n, self.a, self.b = 0, 0, 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < self.max:
            r = self.b
            self.a, self.b = self.b, self.a + self.b
            self.n = self.n + 1
            return r
        raise StopIteration()

# using Fib object
for i in Fib(5):
    print(i)

除了使用迭代器以外,Python 使用 yield 关键字也能实现类似迭代的效果,yield 语句每次 执行时,立即返回结果给上层调用者,而当前的状态仍然保留,以便迭代器下一次循环调用。这样做的 好处是在于节约硬件资源,在需要的时候才会执行,并且每次只执行一次。

def fib(max):
    a, b = 0, 1
    while max:
        r = b
        a, b = b, a+b
        max -= 1
        yield r

# using generator
for i in fib(5):
    print(i)

课后练习

请创建一个永久执行的循环语句:在循环中,提示用户输入两个数字,并打印出两个数字中的所有奇数字,如果用户输入1和5,那就打印1, 3, 5,如果用户输入的第一个数字大于等于第二个数字,就结束循环。

while True:
    num1 = input("num1: ")
    num2 = input("num2: ")
    if num1 >= num2: 
        break
    for i in range(num1, num2 + 1):
        if i % 2 != 0:
            print(i)