Python入门(四)

来源:互联网 发布:linux查看cpu核心数 编辑:程序博客网 时间:2024/04/30 07:31

循环

1.for循环,注意冒号:,缩进代表在循环体内相当于大括号;

cities=["austin","dallas","houston"]for city in cities:      print(city)  

#austin
#dallas
#houston
2. while循环

i=0while i<3:    i+=1    print(i)

#1
#2
#3

i=0while 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=0while True:    print(count)count+=1

布尔类型值bool

  1. true/false
    cat=true
    dog=false
    print(type(cat))

  2. 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=700greater=(sample_rate>5)if greater:    print(sample_rate)else:    print("less than")
t=truef=falseif 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=48guess=int(input(">>:"))if guess>age:    print("try smaller")elif guess<age:    print("try bigger")else:    print("right!")

continue和break

i=0while i<=100:    print("loop",i)    if i==5break    i+=1print("------out of while loop------")
i=0while i<=100:    print("loop",i)    if i==5continue    i+=1print("------out of while loop------")

#输出无限多的5
break用于完全结束一个循环,跳出循环体执行循环后面的语句;
continue只是终止本次循环,接着还执行后面的循环,break则完全终止;

while……else
在Python中while还可以与else搭配,指当while循环正常执行完,中间没有被break终止的话,就执行else后面的语句。

count=0while count<=5:    count+=1    print("loop",count)else:    print("循环正常执行完啦")print("-------out of while loop--------")
原创粉丝点击