[python]-loops-codecademy

step1:while you are here?

The while loop is similar to an if statement: it executes the code inside of it if some condition is true.?

The difference is that the while loop will continue to execute?as long as?the condition is true. In other words, instead of executing?if?something is true, it executes?while?that thing is true.

count = 0

if count < 5:

print "Hello, I am an if statement and count is", count

while count < 10:

print "Hello, I am a while and count is", count

count += 1

step2:Condition

The?condition?is the expression that decides whether the loop is going to be executed or not. There are 5 steps to this program:

1.The loop_condition variable is set toTrue

2. The while loop checks to see if loop_condition isTrue. It is, so the loop is entered.

3. The print statement is executed.

4.The variable loop_condition is set to False.

5.The while loop again checks to see if loop_condition is True. It is?not, so the loop is not executed a second time.

loop_condition = True

while loop_condition:

print "I am a loop"

loop_condition = False

step3:While you're at it

Inside a while loop, you can do anything you could do elsewhere, including arithmetic operations.

num = 1

while num<=10:? # Fill in the condition

print num**2 # Print num squared

num+=1 # Increment num (make sure to do this!)

step4:Simple errors

A common application of awhileloop is to check user input to see if it is valid. For example, if you ask the user to enteryornand they instead enter7, then you should re-prompt them for input.

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: ")

step5:Infinite loops

Aninfinite loopis a loop that never exits. This can happen for a few reasons:

The loop condition cannot possibly be false (e.g.while1!=2)

The logic of the loop prevents the loop condition from becoming false.

Example:

count =10

while count >0:?

?? count +=1# Instead of count -= 1

count = 0

while count < 10: # Add a colon

print count

count+=1# Increment count

step6:Break

The break is a one-line statement that means "exit the current loop." An alternate way to make our counting loop exit and stop executing is with thebreakstatement.

First, create awhilewith a condition that is always true. The simplest way is shown.

Using anifstatement, you define the?stopping?condition. Inside theif, you writebreak, meaning "exit the loop."

The difference here is that this loop is?guaranteed?to run at least once.

count = 0

while True:

? ? ? ? ?print count?

? ? ? ? ?count += 1

? ? ? ? ? if count >= 10:

break

step7:While / else

Something completely different about Python is thewhile/elseconstruction.while/elseis similar toif/else, but thereisa difference: theelseblock will executeanytimethe loop condition is evaluated toFalse. 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 abreak, theelsewill not be executed.

In this example, the loop willbreakif a 5 is generated, and theelsewill not execute. Otherwise, after 3 numbers are generated, the loop condition will become false and the else will execute.

import random

print "Lucky Numbers! 3 numbers will be generated."

print "If one of them is a '5', you lose!"

count = 0

while count < 3:

num = random.randint(1, 6)

print num

if num == 5:

print "Sorry, you lose!"

break

count += 1

else:

print "You win!"

step8:Your own while / else

Now you should be able to make a game similar to the one in the last exercise. The code from the last exercise is below:

count =0

while count <3:? ?

?num = random.randint(1,6)

print num

if num ==5:

print"Sorry, you lose!"

break

count +=1

else:print"You win!"

In this exercise, allow the user to guess what the number isthreetimes.

guess = int(raw_input("Your guess: "))

Remember,raw_inputturns user input into a string, so we useint()to make it a number again.

from random import randint

# Generates a number from 1 through 10 inclusive

random_number = randint(1, 10)

guesses_left = 3

# Start your game!

while guesses_left>0:

guess = int(raw_input("Your guess: "))

if(guess==random_number):

print "You win!"

break

guesses_left-=1

else:

print "You lose"

step9:For your health

An alternative way to loop is theforloop. The syntax is as shown; this example means "for each numberiin the range 0 - 9, printi".

print "Counting..."

for i in range(20):

print i

step10:For your hobbies

This kind of loop is useful when you want to do something a certain number of times, such as append something to the end of a list.

hobbies = []

for i in range(3):

guess = raw_input("Your hobby: ")

hobbies.append('guess')# Add your code below!

step11:For your strings

Using aforloop, you can print out each individual character in a string.

The example in the editor is almost plain English: "for each charactercinthing, printc".

Instructions

thing = "spam!"

for c in thing:

print c

word = "eggs!"

# Your code here!

for d in word:

print d

step12:For your A

String manipulation is useful inforloops if you want to modify some content in a string.

word ="Marble"forcharinword:printchar,

The example above iterates through each character inwordand, in the end, prints outM a r b l e.

The,character after ourprintstatement means that our nextprintstatement keeps printing on the same line.

phrase = "A bird in the hand..."

# Add your for loop

for char in phrase:

if char=='A' or char=='a':

print 'X',

else:

print char,

#Don't delete this print statement!

print

print 語句后面加逗號,是為了將輸出顯示為同一行

step13:For your lists

Perhaps the most useful (and most common) use offorloops is to go through a list.

On each iteration, the variablenumwill be the next value in the list. So, the first time through, it will be7, the second time it will be9, then12,54,99, and then the loop will exit when there are no more values in the list.

numbers? = [7, 9, 12, 54, 99]

print "This list contains: "

for num in numbers:

print num

# Add your loop below!

for num in numbers:

print num**2

step14:Looping over a dictionary

You may be wondering how looping over a dictionary would work. Would you get the key or the value?

The short answer is: you get the key which you can use to get the value.

d = {'x':9,'y':10,'z':20}

for key in d:

?if d[key] ==10:

print"This dictionary has the value 10!"

First, we create a dictionary with strings as the keys and numbers as the values.

Then, we iterate through the dictionary, each time storing the key inkey.

Next, we check if that key's value is equal to 10.

Finally, we printThisdictionary has the value10!

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:

# Your code here!

print key+' '+d[key]

step15:Counting as you go

A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at. Generally this isn't an issue, but at times it is useful to know how far into the list you are. Thankfully the built-inenumeratefunction helps with this.

enumerateworks by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop,indexwill be one greater, anditemwill be the next item in the sequence. It's very similar to using a normalforloop with a list, except this gives us an easy way to count how many items we've seen so far.

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'

for index, item in enumerate(choices):

print index+1, item

step16:Multiple lists

It's also common to need to iterate over two lists at once. This is where the built-inzipfunction comes in handy.

zipwill create pairs of elements when passed two lists, and will stop at the end of the shorter list.

zipcan handle three or more lists as well!

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

step17:For / else

Just like withwhile,forloops may have anelseassociated with them.

In this case, theelsestatement is executed after thefor, butonlyif theforends normally—that is, not with abreak. This code willbreakwhen it hits'tomato', so theelseblock won't be executed.

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

step18:Change it up

As mentioned, theelseblock won't run in this case, sincebreakexecutes when it hits'tomato'.

fruits = ['banana', 'apple', 'orange', 'peach', '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!'

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末疑苫,一起剝皮案震驚了整個濱河市曲横,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌孽椰,老刑警劉巖迈嘹,帶你破解...
    沈念sama閱讀 222,627評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件覆劈,死亡現(xiàn)場離奇詭異坤候,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評論 3 399
  • 文/潘曉璐 我一進店門谓媒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來抢野,“玉大人恃轩,你說我怎么就攤上這事∷盅蓿” “怎么了?”我有些...
    開封第一講書人閱讀 169,346評論 0 362
  • 文/不壞的土叔 我叫張陵补鼻,是天一觀的道長锌半。 經(jīng)常有香客問我记焊,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,097評論 1 300
  • 正文 為了忘掉前任蔫磨,我火速辦了婚禮搀罢,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘邢享。我一直安慰自己湾碎,他們只是感情好柔滔,可當我...
    茶點故事閱讀 69,100評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著疏遏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上俐东,一...
    開封第一講書人閱讀 52,696評論 1 312
  • 那天,我揣著相機與錄音娄昆,去河邊找鬼谷浅。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 41,165評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼许起,長吁一口氣:“原來是場噩夢啊……” “哼接校!你這毒婦竟也來了睦柴?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,108評論 0 277
  • 序言:老撾萬榮一對情侶失蹤尖奔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,646評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡隆檀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,709評論 3 342
  • 正文 我和宋清朗相戀三年裳仆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,861評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡畅姊,死狀恐怖倾鲫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤伶丐,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響腾誉,放射性物質(zhì)發(fā)生泄漏瘦癌。R本人自食惡果不足惜西傀,卻給世界環(huán)境...
    茶點故事閱讀 42,196評論 3 336
  • 文/蒙蒙 一莫秆、第九天 我趴在偏房一處隱蔽的房頂上張望茄螃。 院中可真熱鬧,春花似錦、人聲如沸署海。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽抖剿。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間脓恕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評論 1 274
  • 我被黑心中介騙來泰國打工跺讯, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留愈污,地道東北人创夜。 一個月前我還...
    沈念sama閱讀 49,287評論 3 379
  • 正文 我出身青樓现斋,卻偏偏與公主長得像限书,于是被迫代替她去往敵國和親赁严。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,860評論 2 361

推薦閱讀更多精彩內(nèi)容