Python Learning lesson--for and while loops

Source: Internet
Author: User

    • While loop

While loop, is a combination of loops plus judgment, satisfies the judging condition to return , True (true) starts loop code block , false (false) does not loop

While loop main structure:

# !/usr/bin/env python # -*-coding:utf-8-*-  while codition:    expressions# Note: When Codition=true, the program will be executed forever, to stop using CTRL + C to terminate the program

code block

Note : in In the while loop, if the judgment or keyword does not terminate the loop, it will always loop (dead loop)

Such as:

# !/usr/bin/env python # -*-coding:utf-8-*- Import  Time # Reference Timer module a=trueb=1 while  A:    print(b)    Time.sleep ( 1)# Call Timer

as listed above The while loop determines if the variable A is true (true) when it starts looping inside the code block, printing the variable b to the timer waits 1 seconds after the process is repeated (dead loop)

The combined use of the while loop and if judgment, from 1 cycles to 10 termination

Such as:

# !/usr/bin/env python # -*-coding:utf-8-*-a=trueb=1 while a:    print(b)     if b==10:        a=False    b+=1# variable b self-accumulating plus 1    Time.sleep (1)# Call Timer

The list above is terminated from 1 to 10, while the loop evaluates the a variable to true (true), starts the loop code block, prints a variable value of 1, and encounters if the value of B variable equals 10, obviously not equal, does not mean to skip judgment , in the Down encounter B+=1 (is the value of the B variable itself plus 1, equal to b=b+1), at this time the B variable value is 2, in the Down encounter timer wait 1 seconds And then start repeating the loop again until the s variable accumulates to 10,if to determine that the B variable equals 10, execute if the code block inside the if code block is a variable value re-assignment equals false (False), At this point the n variable is false (false), while in the secondary loop, the while loop condition determines that the a variable is false, not executing while the loop terminates

While loop keyword (break) jumps out of the entire loop no longer loops

1 to ten

 #  !/usr/bin/env python  #  -*-coding:utf-8-*-  Import   time  #   reference Timer module  a=trueb  = 1 while   a:  print   (b)  if  b==10 :  break   b  +=1#   Variable b itself accumulates plus 1  time.sleep (1 #   call timer  

above, when looping to 10 o'clock, if the b variable equals 10, execute if the code block encounters a break (jumping out of the loop is not the loop) and it jumps out and is not in the loop.

While loop keyword (continue) jumps out of this loop to continue the next loop

such as: Loop out 1, 2, 3, 4, 6, 7, 8, 9, 10 jump out of 5

#!/usr/bin/env python#-*-coding:utf-8-*-Import Time#Reference Timer ModuleA=Trueb=1 whileA:ifB==5: b+=1Continue    Print(b)ifb==10:         Breakb+=1#variable b self-accumulating plus 1Time.sleep (1)#Call Timer

as listed above, when the loop to 5 when the If judgment, execute if inside the code block, if the b variable plus 1 is 6,continue jump out of this cycle, the second loop when the B variable is 6, If judgment equals 5 does not set up skip judgment, execution down until the second if judgment to equals 10 after encountering break jump out of the loop

While loop 1-100 sum of sums (1+2+3+4+5...+100)

Such as:

# !/usr/bin/env python # -*-coding:utf-8-*-a=trueb=1s=0 while a:    if b ==100:        a=False    s+ =b    b+=1print(s)

as listed above,s+=b (s=s+b) is every time the loop here, the s variable itself plus the value of the B variable is re-assigned to the S variable (this can be understood as,b variable Each loop itself cumulative plus the value of 1, in addition to the value of the s variable, is re-assigned to the S variable to do a registration) Finally in print this s,s variable last registration, is the whole loop added and

While loop plus if to determine all odd numbers in output 1-100

Such as:

# !/usr/bin/env python # -*-coding:utf-8-*-a=1 while a<=100:    if a%2==0:        Print  (a)    Else:        pass    a+=1

While loop plus if to determine all the even numbers in output 1-100

# !/usr/bin/env python # -*-coding:utf-8-*-a=1 while a<=100:    if a%2!=0:        Print  (a)    Else:        pass    a+ =

While loop plus if to determine the 1-2+3-4+5...99 of all numbers

Such as:

# !/usr/bin/env python # -*-coding:utf-8-*-a=1b=0 while a<=99:    if a%2!=0 :        b=b-a    else:        b=b+a    a+=1print (b)

That is, in the loop to make the judgment, the loop to the odd number of the addition, if it is even the subtraction, the addition or subtraction of each cycle, the assignment to the B variable record,b variable The last record is we get the addition and subtraction and

While loop plus if the user is given a 3 chance to enter the user name and password

Such as:

#!/usr/bin/env python#-*-coding:utf-8-*-A=0 whileA<=3: Name=input ("Please enter user name:") Password=input ("Please enter your password:")    ifname=="Luqinag"  andpassword=="HelloWorld":        Print("Congratulations on your successful login")         Break    Else:        Print("Sorry, user name or password error") A+=1

That means using While loop plus if judgment, in the loop to determine whether the user entered the user name and password is correct, the correct login successfully exited the entire loop, incorrect prompt error, variable a plus 1, repeat the operation again, when the value of variable A is greater than 3 o'clock, the loop condition is not established, stop the loop

    • For loop

It can traverse sequence members (strings, arrays, tuples), mainly used for looping a list of strings, etc.

no need to judge, define a loop variable to

format:for (loop-defined variable) in (loop variable) automatically exits the entire loop after the loop is completed

The print loop defines the variable to

Key Words (continue) jump out of this cycle to continue the next ring

Key Words (break) jumps out of the loop not in the loop

A For loop can traverse each element in a string

# !/usr/bin/env python # -*-coding:utf-8-*-a="life wasshort,you need python" for in A:     Print (b)
    • Keyword app

#!/usr/bin/env python#-*-coding:utf-8-*-A="Life is short,you need python" forBinchA:ifb=="P":        Continue#jump out of this loop and continue the next loop .    Else:        Print(b)#loop out all letters and spaces, except P

how to get only the first value of "focus" in for

#!/usr/bin/env python#-*-coding:utf-8-*-a=[12,23,34,45,56,67,78,89] forKvinchEnumerate (a,1):#The first thing to do is to use the enumerate () function to add a key, or subscript, to the loop object, so that you can define two variables in the loop to accept the key and the value separately .#print (k,v) so that you can get the keys and values, use if to determine the key to get the value of a certain time#For example, to get the value of the sixth loop    ifK==6:        Print(v)#if the key equals 6, the value of this loop is printed.#Output

Add:

In other programming languages, such as Java,C + + , there is a do-while Loop

Note : The Do-while loop and The while loop are basically the same, but the difference is that it executes the loop body once and then determines the loop continuation condition

Python Learning lesson--for and while loops

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.