Python Loop (vi)

Source: Internet
Author: User
Tags first string

Turn from http://www.cnblogs.com/mangood/p/6026141.html one, while loop

If the condition is true, repeat the same operation, the condition is not met, and the loop jumps out

While loop condition:

Looping operations

(1) While loop example

Example: Input Wang Xiaoming 5 course test results, calculate the average score

1 I=1                                            # Initialize loop counter i2 sum=0                                          # Initialize total score variable 3 while i<=5:                                    # from I to 1 start to 5, repeat for 5 times to receive exam results, sum operation 4         print (' Please enter% ' D-Course exam results '%i '    # Prompts the user to enter scores, which uses formatted output,%d values are displayed with the value of I, 1th course, 2nd course ... 5         Sum=sum+input ()                        # Assigns the user input to sum, finally holds 5 scores and 6         i=i+1                                  # each cycle I increment 1, until greater than 5 jump out of the Loop 7 avg=sum/(i-1)                                  # When the fifth execution of I=i+1, I is 6, jump out of the loop, calculate the value of sum/(i-1) is the mean, and assigned to Avg8 print (' Wang Xiaoming 5 course average score is%d '%avg)          # Formatted output AVG value, due to%d so the calculated% The AVG number is omitted, and the integer part is received.

(2) nested while loop example

After the outer loop satisfies the condition, the execution code begins to perform the inner loop, and so the inner loop executes all, and if the external loop condition is met, the outer loop executes again, and so on, until the outer loop is out.

Example: Enter 5 results for two students respectively, and calculate the average score respectively

 1 J=1 # define the external loop counter initial value 2 prompt= ' Please enter student name ' # defines a string variable that is called when the user enters the                                   Variable can reduce the trouble of knocking Chinese characters 3 while j<=2: # defines an external loop for execution two times 4 sum=0     # defines the score initial value, which is defined here, is to allow sum to be initialized to 0 when the second student enters the score, to re-receive the new student's score and 5 I=1 # to define an internal loop counter initial value of 6 Name = Raw_input (prompt) # receives the student name entered by the user, assigns a value to the name variable 7 while i<=5: # defines the intrinsic function Cycle 5, is to receive 5 courses of the results of 8 print (' Please enter the exam results at gate%d: '%i) #提示用户输入成绩, which used formatted output,%d values with the value of I, 1th course, 2nd course ... 9 sum= sum + input () # Receive user input scores, assign to SUM10 i+=1 # I variable self-increment 1,i change to 2, continue the loop until I equals 6 o'clock, jump out of the loop one avg=sum/(i-1) # calculates the first student's average score sum/(6-1), assigns the value to AVG12 print name, ' the average  Score is%d\n '%avg # Output student achievement average of j=j+1 # after the internal loop executes, the external loop counter J is incremented by 1, becomes 2, and then the external loop ' Student score input completed! ' # The outer loop is over, liftInput completed! 
Second, for Loop

(1) Use the For statement to traverse all elements, such as outputting characters in a string, outputting elements from a list, elements in a tuple, elements in a collection (note the order of each element when assigning values), keys in a dictionary ...

For "python": Print letter Result: Python
fruits=[' watermelon ', ' peach ', ' grape ']for fruit in fruits:    print fruit result: Watermelon Peach grape

(2) Perform the same operation repeatedly

Use the range () function to create a list of numbers

Range of values: from the start number to the ending number

1 for I in Range (0,5):  #依次把0到4保存在变量i中2     print ' Mr.mangood is the coolest! ' 3 4 results: 5 Mr.mangood the coolest! 6 Mr.mangood is the coolest! 7 Mr.mangood is the coolest! 8 Mr.mangood is the coolest! 9 Mr.mangood is the coolest!

Enter the Wang Xiaoming test scores and figure out the average

1 subjects= (' Linux system ', ' MySQL database ', ' Python language ')  # Defining a tuple, three elements representing three courses 2 sum=0                                            # Defining variables num for initializing score 3 for I in subjects:< c2/># each element in the tuple is assigned to I, a total of three times 4     print ' Please enter the test score of%s '%i                   # Hint input score, using the format string function, with each time I get the element name to express the result name,%s means the string 5     Score = input ()                              # receives user-entered scores assigned to score 6     sum + = score                                 # Assigns the result to sum, equal to sum = sum + score 7 avg= Sum/len (subjects) c9/># jumps out of the For loop, calculates the average, and uses the function Len () to calculate the length of the variable subjects, because subjects is defined as a tuple, so the length is the number of elements 3 8 print ' Wang Xiaoming has an average score of%d '%avg                    # Output average 9 10 results: 11 Please enter the test results for the Linux system 12 8713 Please enter the test results for MySQL database 14 7815 Please enter the Python language test results 16 9017 Wang Xiaoming average score 85

(3) Nesting for loops

Input Huang, Yolanda 2 students, each of the three courses of examination results, calculate the average score

1 student = (23 ' Huang ', ' Yolanda ')                      #定义学生姓名的元组 2 subjects= (' Linux system ', ' MySQL database ', ' Python language ')  #定义课程名字的元组 3 for J in student :                                #把j依次取两名学生的值进行两次循环 4     sum=0                                        #初始化成绩的值 5     print '%s classmate's exam results '%j                     #打印出标题 6 for     i in subjects:                           # Defining course Loops 7         print ' Please enter the test score for%s '%i               #提示输入其中一名学生的考试成绩 8         score = input ()                          #接收考试成绩赋值给score 9         if score <0 or score>100:                 #判断分数取值范围, do remind the             print ' pay attention to the result size ' one         by one sum+=score                               #每次输入成绩后, sum value is accumulated 12     avg= Sum/len (subjects)                       #求出平均成绩13     Print J, ' The average score is%d\n '%avg                 #打印平均成绩14 print ' completion of student record entry work '                         # Prompt to complete work

Third, Cycle control

loop control statements can change the normal execution order of loops

Loop control Statements

Break statement: Jump out of this loop (only one layer is out of loop in a nested loop)

Continue statement: Skip the current round of the remaining statement of the loop body, re-test the loop state, into the next cycle, such as the number of cycles a total of 5 times, the fourth time encountered continue, then do not continue to execute, direct 5th cycle judgment

Iv. comprehensive case of cyclic control

1. Demand Analysis

Show Menu

(N) EW User Login

(E) ntering User Login

(Q) uit

Enter Choice:

Note: Enter the letter N, receive the new login name and password, save in the dictionary

Enter the letter E, receive the login name, password, find, match user input is correct

Enter the letter Q, exit

2. Implementation steps

(1) Preparing the menu

(2) using the While statement to implement menu item Selection-Outer loop

(3) using the while statement to receive a new login-Inner loop

(4) Use the IF statement to determine the menu and perform related actions

3. Code structure diagram

4. Specific code

1db={}            2prompt=" "          3(N) EW userLogin 4(E) ntering userLogin 5(Q) uit6Enter Choice:" " 7  whileTrue:8Choice = Raw_input (prompt). Strip () [0].lower () #读取控制台输入的字符串 the first string is converted to a lowercase letter after removing its trailing and ending spaces9Print'\n--you picked:[%s]'%ChoiceTen     ifChoice notinch 'NEQ': OnePrint'--invaild option:,try again--' A     Else: -         ifChoice = ='N': -PROMPT1 ='--login Desired:' the              whileTrue: -Name =raw_input (PROMPT1) -                 ifDb.has_key (name): #判断字典里的键值是否已经有输入的name值, if some words trigger continue to re-execute the while loop because PROMPT1 was redefined before triggering continue, so a new name was executed =raw_input (PROMPT1) -PROMPT1 ='--name taken,try Another:' +Continue -                 Else: + Break A             pwd= Raw_input ('Password:'#验证字典中的键没有输入的name值后, jump out of the loop and assign the user's password to pwd atDb[name] =pwd#把值传给字典db中的name键实现字典数据的完善 -         elifChoice = ='e': -Name = Raw_input ("Login:") -             pwd= Raw_input ('Password:') -Password =db.get (name) #登录时, after receiving the login name and password entered by the user, assign the value of the name key in the dictionary db to password -             ifPassword = =pwd: #比较字典中的密码password和用户输入的密码pwd是否一致 inPrint'Welcome', name -             Else: toPrint'Shibai' +         Else: -Print'quit!' the Break *         

Python Loop (vi)

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.