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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容