Use of While & for loops

Source: Internet
Author: User

One, while loop

1.while-Loop statements

 while condition: Statement body    statement body

Using a while loop is prone to dead loops and requires a cyclic control condition.

Times = 1  while times <=5:      print("times:", Times)      # Loop over the control statement times      +=1print(" program End ")

For example: Guessing the game, assuming the answer is 9, let the user enter an integer from the keyboard, using the while loop, provide multiple opportunities for users to guess. For example, give users three chances

num = 9 Times= 1 whileTimes <= 3: Num1= Int (Input ("Please enter an integer:"))    ifNUM1 = =Num:Print("you guessed right.")    elifNUM1 <Num:Print("you guessed small.")    Else:        Print("you guessed big.") Times= times + 1

2.break/continue

The break statement jumps out of the loop and terminates the loop; The continue statement jumps out when the layer loops and starts the next loop.

For example: Output 1 to 10, if a multiple of 2, no output (continue usage)

Times =1 while times <=:    if times% 2 = =0:       +=1        Continue    print(times)    = Times +1

For example: Output 1 to 20, if it is a multiple of 5, the end program

Times = 1 while times <=20:     if times% 5 = =0        :+=1        bresk       print(times)     +=1
Print ("End of Program")

Exercise: 1. Ask for the sum of the odd sum within 100 99+97+95+93+.......+1

The first type:
n == 0 while n <= := n + 1 if n% 2 = =0: Contin UE = sum + nprint(sum)

= 0 while n > 0 := sum + n= n-2print (sum)

2. Create a list that contains an odd number within 100

List == 101 while n >= 2:    if n% 2! = 0        := n-2        list.appen D (n)print(list)

Second, for Loop statement

 for inch Range:      for The number of cycles of the loop body ----cycle, by the specified range

1. Traversing a string

" hello,world! "  = 0 for in str:    print(i)    = total + 1  Print(total)

2. Traversing the list

List = [All-in-A-z  , "test", "Python"] for in list:     print(l)

3.range () function range (starting value, end value, step value) range (starting value, end value) ranges: Starting value, to (end value-1)

 for  in range (0,6):     print(i)

For example: Write a python code to delete the repeating element in a list

List = [2,3,4,2,4,3,5,11,23,13=[] for in list:     ifnot In   lst:          lst.append (i)print(lst)print(sorted (LST))

Nesting of 4.for loops

 for inch scope:    statement     for in   range:        loop body
 for  in range (1,10):    print("i-->:", i)      for  in range (1,i+1):        print("j-->:", j,end= " \ t " )    print()

Example: Implementing a 99 multiplication table using a For loop nesting

#1th Type forIinchRange (1,10):     forJinchRange (1,i+1):        Print("%d*%d=%2d"% (i,j,i*j), end ="\ t")    Print()#2nd Type forIinchRange (1,10):     forJinchRange (1,i+1):        Print(Str (i) +"*"+ STR (j) +'='+ STR (i*j), end="\ t")    Print()

5. Bubble sort

For example: Define a list, such as LST = [3,8,2,12,56,9], and then sort the data in the list from high to low and output.

LST = [3,8,2,12,56,9] for in range (0,len (LST)-1):    for in Range (0,len (LST)-i):        if lst[j] < lst[j+1]:            lst[j],lst[j+1] = lst[j+ 1],lst[j]print(LST)

Use of While & for loops

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.