【Python-13】Loops

 

 第一节

     1 介绍了另外一种循环while循环

     2 while循环的结构如下

        while condition:

                  statement

 

 第二节

     1 while循环的练习,写一个while循环,打印出1~10的平方数

num = 1

while num <= 10:# Fill in the condition (before the colon)
    print num**2# Print num squared
    num = num+1# Increment num (make sure to do this!)

 

 

 

 第三节

     1 while循环的练习,写一个循环,判断输入的字符是不是"y"或"n",如果是退出,否则继续输入

choice = raw_input('Enjoying the course? (y/n)')

while choice != "y" and choice != "n":# Fill in the condition (before the colon)
    choice = raw_input("Sorry, I didn't catch that. Enter again: ")

 

 

 

 第四节

     1 介绍了,我们可以使用 x += y 来代替 x = x+y

     2 练习:在对应的循环上面补上count的增量

count = 0

while count < 10: # Add a colon
    print count
    # Increment count
    count += 1

 

 

 第五节

     1 介绍了一个结构while/else结构

     2 while/else 结构如下,else当while循环是执行到condition为False的时候才会执行,如果while循环是中间某一步break是不会执行的

        while condition:

                   statement

        else:

                   statement

     3 练习:利用while循环最多执行三次,每次输入一个值,判断是否和已知的随机数相等输出"You win!" ,如果是break出循环,否则继续输入,如果三次输入都不想等输出"You lose."    

from random import randrange

random_number = randrange(1, 10)

count = 0
# Start your game!
while count < 3:
    guess = int(raw_input("Enter a guess:"))
    if guess == random_number:
        print "You win!"
        break
    count += 1
else:
    print "You lose."

 

 

 

 

 

 

 第五节

     1 介绍了Python中的输出的问题,我们可以在输出的后面加一个","表示输出一个空格而不是输出换行

     2 比如有一个一个字符串s = "abcd"

        我们使用for c in s: print c,  那么最后将输出a b c d,中间有一个空格

 

 第六节

      1 介绍了for循环的另外一种用法,我们可以在for循环里面使用多个的变量

         比如我使用三个变量

         for a,b,c in zip(list_one , list_two , list_three): statement

      2 练习:通过for循环输出两个列表中的大的值

list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):
    # Add your code here!
    if a > b:
        print a
    else:
        print b

 

 

 

 第七节

     1 介绍了for/else结构,和while/else结构一样,for/else也是只有当正常退出for循环的时候才执行else语句

     2 比如下面这个例子,没有正常的退出是break出for循环的,因此不会执行else语句

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
        break
    print 'A', f
else:
    print 'A fine selection of fruits!'

 

 

 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值