78144666 发表于 2017-4-29 09:50:15

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 =
list_b =
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!'


  

  
页: [1]
查看完整版本: Python 入门教程 13 ---- Loops