python基础4

IF语句

等值检验

1
2
3
4
5
6
7
8
# 等值检验 (==必须使用双等号)(!=代表不等检验)
name = 'jody'
if name == 'jody':
print('hello,jody!')
elif name != 'jody':
print('who are you')
--------------------------------------
hello,jody!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
names = ['Anan','Jody','John','wang']
for name in names:
if name == 'wang':
print(name.upper())
elif name.lower() == 'jody':
print(name.title())
elif name.upper() == 'ANAN':
print(name)
else:
print('you may be '+name)
------------------------------------------
Anan
Jody
you may be John
WANG
  • IF语句可以使用and,or语句来增加检验条件
  • else是一条保罗万象但并非必须具备的语句,只要不满足if和elif中的条件,else就会被执行,即使在输入错误的情况下。因此,若知道else语句具体指那种条件,应该使用elif语句。
1
2
3
4
5
6
7
8
9
10
11
12
available_toppings = ['mushroom','olives','green peppers',
'pepperoni','pineapple']
request_toppings = ['mushroom','fries','cheese']
for request_topping in request_toppings:
if request_topping in available_toppings:
print('a '+request_topping)
else:
print("sorry,we don't have this")
------------------------------------------------
a mushroom
sorry,we don't have this
sorry,we don't have this
  • 这两个表的if检验挺有意思。

数值比较

1
2
3
4
5
6
7
8
9
10
11
ages = list(range(7,9))
for age in ages:
if age <= 8:
print(age)
elif age in [9,20]:
print(age-1)
elif age >= 20:
print(age-10)
----------------------------------------------
7
8

小结

  • if 与 for 循环的结合;
  • if 与 .title() .upper() .lower() 的结合;
  • if 判断语句的等值(==),不等(!=)以及其他数值判断符号(>,>=,<,<=)。

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!