Python_11_Codecademy_11_While Loop

总目录


课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾


While loop

  • while 后面的 condition 是 true 的时候,就执行代码
count = 0
while count <= 3:
    print "Hello, I am a while and count is", count
    count += 1
Console:
Hello, I am a while and count is 0
Hello, I am a while and count is 1
Hello, I am a while and count is 2
Hello, I am a while and count is 3
  • 【练习1:打印0-10的平方】
i = 0
while i <= 10:
    print i ** 2
    i += 1
Console:
0
1
4
9
16
25
36
49
64
81
100
  • 【练习2:询问对课程是否满意,while loop来check是否用户输入指定值】
answer = raw_input("Enjoying the course? (y/n) ")
while answer != "y" and answer != "n":
    answer = raw_input("Sorry, I didn't catch that. Enter again: ")
Console:
Enjoying the course? (y/n) yes
Sorry, I didn't catch that. Enter again: nope
Sorry, I didn't catch that. Enter again: yeah
Sorry, I didn't catch that. Enter again: y
Process finished with exit code 0

Infinite loop & break

  • 当while后面的condition不可能为假的时候,这个while loop就是infinite loop
  • 要在这种loop里面设定停止机制,就是需要简单地加入一个break就好了。我之前在Python 10 Battleship!的笔记里面就用到:
while 2 == 2:
    if raw_input("Are you ready? Enter Y or N. ") == "Y":
        print "\n  Let's play Battleship!"
        break

while / else

  • 如果while里面有break,那么else不会被执行 (for / else也存在,也是如果for正常结束就会else,如果for里面有break就不会执行else)
  • 其他情况下,譬如while执行到condition为false,或者while根本没有执行就成为false的时候,else都会被执行。

    This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of a break
    , the else will not be executed.

【练习1:掷骰子,三次机会,掷到2就输了,否则就赢了】

from random import randint
print "Lucky Numbers! 3 numbers will be generated."
print "If one of them is a '2', you lose!"

n = 3
while n > 0:
    number = randint(1, 6)
    print number
    if number == 2:
        print "You lose."
        break
    n -= 1
else:
    print "You win!"
Console:
Lucky Numbers! 3 numbers will be generated.
If one of them is a '2', you lose!
6
5
1
You win!

你可能感兴趣的:(Python_11_Codecademy_11_While Loop)