if…else条件判断
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
条件判断类型
- 布尔判断:
# Boolean check
game_over = True
if game_over:
print('Game Over :(') # game_over是对的,那就执行if后的语句
alive = False
if alive:
print('Alive')
else:
print('You died :(') # alive是错的,就要执行else后的语句
- 数值比较:
# Numerical comparisons
age = 18
print(age == 18)
# , =
if age <= 21:
print('You can\'t drink!')
- 字符串相等性比较:
# check for equality
car ='bmw'
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") # 招聘
- 多条件判断(括号可写可不写):
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 嵌套
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中有if-else行内表达式:var = var if condition else var 2
height = 180
result = "tall" if height >= 180 else 'short'
print(result)
# 如果》180,那么结果就是tall,不然就是short
While 循环
while语句格式如下,其中condition为判断条件,在Python中就是True和False其中的一个,如果为True,那么将执行expressions语句块,否则将跳过该while语句块借着往下执行。
while condition: expressions
num = 0
while num < 10:
print(num)
num = num + 1
#这段代码将会输出0, 1, 2, 3, 4, 5, 6, 7, 8, 9
#先打印出num,然后将num的值加1,至此完成一次循环。
#当num等于10后,num < 10将会为False,就结束了循环。
智能循环:break和continue
我们使用一个变量当做条件标记,当变量为False时候,循环语句就会自动结束:
# Using a flag
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message) # 当输入的是quit的时候才会停止
使用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: # 如果num是偶数,那就跳过打印的步骤,进行while的下一环
continue
print(num)
# 将0-9的奇数都打印出来
在数组和字典中使用while语句
- 通过用户的输入,将列表list构建起来:
friends = []
prompt = "Enter your friend's name: "
while True:
friend = input(prompt) # 一直输入好友的名字
if (friend == 'q'): # 如果输入的名字是q,则终止while语句
break
friends.append(friend)
print(friends)
- 也可以使用循环,将一个列表中的元素全部添加到另一个列表中:
# Moving items from one list to another
unconfirmed_users = ['alice', 'brain', 'candace']
confirmed_users = []
while unconfirmed_users: # 只要unconfirmed_users不是空的,就能继续执行while语句
confirmed_users.append(unconfirmed_users.pop()) # 从后往前导入到confirmed_users中去
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 循环
for item in sequence:
expressions
- 将sequence里面的元素都遍历一遍
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)
"""
1
2
3
4
5
6
Python
1991
"""
Range函数
- Python中的range函数可以生成一系列的数字:
# range(start, stop)
for i in range(1, 10): # 输出结果是1-9
print(i)
# range(stop) start from 0
for i in range(10): # 只有一个数字时,python就会默认从0开始,到9结束
print(i)
# range(start, stop, step)
for i in range(0, 13, 5): # 每5个一跳
print(i)
Python中的迭代
待定