循环
1.for循环,注意冒号:,缩进代表在循环体内相当于大括号;
cities=["austin","dallas","houston"]
for city in cities:
print(city)
#austin
#dallas
#houston
2. while循环
i=0
while i<3:
i+=1
print(i)
#1
#2
#3
i=0
while i<3:
if i==2:
pass
else
print(i)
i+=1
pass表示过;
3. range的使用
for i in range(10):
print(i)
#0,1,2,3,4,5,6,7,8,9
4. list的遍历
cities=[["a","b","c"],["d","e","f"]]
print(cities)
for city in cities:
print(city) #打印出来两个list
#["a","b","c"]
#["d","e","f"]
for i in cities: #遍历最外层两个list
for j in i: #遍历最里面的list
print(j)
#a
#b
#c
#d
#e
#f
5.死循环dead loop
count=0
while True:
print(count)
count+=1
布尔类型值bool
true/false
cat=true
dog=false
print(type(cat))print(8==8)
print(8!=8)
print(“8”==”8”)
print([“january”]==[“february”])
print(8.4==8.4)
rates=[10,15,20]
print(rates[0]>rates[1])
if ……else
sample_rate=700
greater=(sample_rate>5)
if greater:
print(sample_rate)
else:
print("less than")
t=true
f=false
if t:
print("true")
if f:
print("false")
animals=["cat","dog",rabbit]
for animal in animals:
if animal=="cats":
print("cat found") #true
animals=["cat","dog",rabbit]
if "cat" in animals:
print("cat found") #cat found
animals=["cat","dog",rabbit]
cat_found="cat" in animals:
print(cat_found) #true
多分支if……elif……else
age=48
guess=int(input(">>:"))
if guess>age:
print("try smaller")
elif guess<age:
print("try bigger")
else:
print("right!")
continue和break
i=0
while i<=100:
print("loop",i)
if i==5:
break
i+=1
print("------out of while loop------")
i=0
while i<=100:
print("loop",i)
if i==5:
continue
i+=1
print("------out of while loop------")
#输出无限多的5
break用于完全结束一个循环,跳出循环体执行循环后面的语句;
continue只是终止本次循环,接着还执行后面的循环,break则完全终止;
while……else
在Python中while还可以与else搭配,指当while循环正常执行完,中间没有被break终止的话,就执行else后面的语句。
count=0
while count<=5:
count+=1
print("loop",count)
else:
print("循环正常执行完啦")
print("-------out of while loop--------")