1.布尔变量
# searching using a boolean variable 用布尔变量搜索
目标:遇到3显示True
i=0
numbers = [9,41,12,3,74,15]
found = False
found1 = False
print('Before',found)
for num in numbers:
i+=1
if num == 3:
found1 = 'True'
print(i, found1, 'We Found', num)
else:
print(i,found)
try:
print('After', found1)
except:
print('After',found)
运行结果:
Before False
1 False
2 False
3 False
4 True We Found 3
5 False
6 False
After True
目标:输入start开始,判断数组中是否有3
# 使用while语句应避免infinite loops无穷循环
# 可以使用break结束循环
# continue回到循环初始位置
while True:
line = input('>')
# print(type(line))
# 第一个字符是#的时候跳到循环开头
if line[0] == '#':
continue
if line == 'start':
break
print(line)
print('Start!')
found=False
print('Before',found)
for value in [19,43,15,7,65,13]:
if value == 7:
found = True
print(found,value)
print('After',found)
运行结果:
>start
Start!
Before False
False 19
False 43
False 15
True 7
True 65
True 13
After True
2.is 和 is not的用法
逻辑性比“==”更强,要求变量类型和变量的值都相等,一般只用在无类型和布尔值,最好不要用在数字和字符型,处理整型、浮点型和字符型可以使用“==”
-'is' and 'is not' operators is stronger than equals
meaning that it demands equality in both
the type of the variable and the value of variable
-'is' and 'is not' just use on none or true/false(boolean) types
DON'T OVERUSE IT DEALING WITH NUMBERS OR STRINGS
-we can use double equals on integers,floats,strings
3.各类循环及continue,break,return,pass的应用
循环类型:
-While loops(indefinite 不确定)
-Infinite loops 无限循环
-Using break
-Using continue
-None constants and variables 无常量和变量
-For loops
-Iteration variables 迭代变量
-Loop idioms 循环惯用语
-Largest or smallest
continue,break,return,pass的应用
continue
print('--------continue-----------')
print(numbers)
for D in numbers:
if D == 3:
continue
print(D)
continue运行结果:
--------continue-----------
[9, 41, 12, 3, 74, 15]
9
41
12
74
15
#continue跳过,即遇到3跳过
break
print('--------break-----------')
print(numbers)
for D in numbers:
if D == 3:
break
print(D)
break运行结果:
--------break-----------
[9, 41, 12, 3, 74, 15]
9
41
12
# break跳出循环,即遇到3停止
return
print('--------return-----------')
print(numbers)
def thing():
for D in numbers:
if D == 3:
return D
print(D)
print(D)
print(thing())
def greet(lang):
if lang=='es':
return'Hola!'
elif lang=='fr':
return'Bonjour!'
else:
return'Hello!'
print(greet('en'),'Briton')
print(greet('es'),'Español')
print(greet('fr'),'Français')
return运行结果:
--------return-----------
[9, 41, 12, 3, 74, 15]
3 # for循环外的print(D)显示了D的返回值为3
9
41
12
3 # print(thing()) 展示了thing()中运行的过程,最后返回D
Hello! Briton # lang 等于 en 的时候,非 es 和 fr ,返回 Hello!
Hola! Español # lang 等于 es 的时候,返回 Hola!
Bonjour! Français # lang 等于 fr 的时候,返回 Bonjour!
pass
print('--------pass-----------')
def pas():
for p in range(1,11):
if p%2 == 0.0:
pass
else:
print(p)
pas()
pass运行结果:
--------pass-----------
1
3
5
7
9
# pass用作占位,余数等于0.0时,即遇到偶数时什么都不做



