Python入门(四)

循环

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

  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=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==5break
    i+=1
print("------out of while loop------")
i=0
while i<=100:
    print("loop",i)
    if i==5continue
    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--------")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值