The learning record of the Python basic loop

Source: Internet
Author: User

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

I=1                                            # Initialize loop counter isum=0                                          # Initialize the total score variable while i<=5:                                    # from I to 1 start to 5, repeat for the total of 5 times to receive exam results, sum operation        Print (' Please enter the% 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        ... Sum=sum+input ()                        # Assigns the user input to sum, and finally holds 5 results and        i=i+1                                  # each cycle I increment 1, until more than 5 jump out of the Loop avg=sum/(i-1)                                  # When the fifth time to execute i= I+1, I is 6, jump out of the loop, calculate the value of sum/(i-1) is the mean, and assign to Avgprint (' 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

J=1 # define External loop counter initial value prompt= ' Please enter student name ' # defines a string variable that is called when user input can be reduced The trouble of knocking Chinese characters while j<=2: # defines an external loop for performing two times Sum=0 # defines the initial value of the score, the This is defined here to allow sum to be initialized to 0 when the second student enters a score, to re-receive the new student's score and I=1 # define the internal loop counter initial value name = Raw_input        (prompt) # receives the student name entered by the user, assigns a value to the name variable while i<=5: # defines an internal function loop 5 times, which is the result of receiving 5 courses                  Print (' Please enter Test score at gate%d: '%i ') #提示用户输入成绩, where formatted output is used, the value of%d is displayed with the value of I, 1th course, 2nd course ... sum= sum + input ()                           # Receive user input scores, assign to sum i+=1 # I variable self-increment 1,i to 2, continue execution loop until I equals 6 o'clock, jump out of Loop avg=sum/(i-1)                                   # Calculate the average score of the first Student sum/(6-1), assign to AVG print name, ' The average score is%d\n '%avg # Output average of students ' results j=j+1 # after the internal loop executes, the external loop counter J is incremented by 1, becomes 2, and then the external loop print ' student score input completed! ' # external loop end, prompt input complete!

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

For I in Range (0,5):  #依次把0到4保存在变量i中    print ' Mr.mangood is the coolest! ' Result: Mr.mangood is the coolest! Mr.mangood is the coolest! Mr.mangood is the coolest! Mr.mangood is the coolest! Mr.mangood is the coolest!

Enter the Wang Xiaoming test scores and figure out the average

subjects= (' Linux system ', ' MySQL database ', ' Python language ')  # defines a tuple, three elements representing three courses sum=0                                            # defines the variable num for the initialization score fraction for the I in subjects:                               # Each element in the tuple is assigned to I, a total of three times    print ' Please enter the test score of%s '%i                   # Prompt for results, using the format string function, with each time I get the element name to express the result name,%s means the string    Score = input ()                              # receives user-entered scores assigned to score    sum + = score                                 # Assigns the result to sum, equal to sum = sum + scoreavg= Sum/len (subjects)                         # After jumping out of the for loop, calculate the average, where the function Len () is used to calculate the length of the variable subjects, because subjects is defined as a tuple, so the length is the number of elements 3print ' Wang Xiaoming's average score is%d '%avg                    # Output average Result: Please enter the test score of the Linux system 87 Please enter the test result of the MySQL database 78 Please enter the Python language test score 90 Wang Xiaoming's average score is 85.

(3) Nesting for loops

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

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

db={} prompt= "(N) EW user login (E) ntering user Login (Q) uitenter choice:" While True: Choice = Raw_input (prompt). Strip () [0].lower () #读取控制台输入的字符串, remove the extra space from the first string to lowercase print ' \n--you pick  ed:[%s] '%choice if choice not in ' NEQ ': print '--invaild option:,try again--' else:if choice = =                ' n ': prompt1 = '--login desired: ' While true:name = Raw_input (PROMPT1) If Db.has_key (name): #判断字典里的键值是否已经有输入的name值, if some words trigger continue to re-execute the while loop because PROMPT1 was redefined before triggering continue, so the new Nam was executed                E = Raw_input (prompt1) prompt1 = '--name taken,try another: ' Continue            Else:break pwd = raw_input (' Password: ') #验证字典中的键没有输入的name值后, jump out of the loop and assign the password entered by the user to the PWD            Db[name] = pwd #把值传给字典db中的name键实现字典数据的完善 elif Choice = = ' 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 if password = pwd        : #比较字典中的密码password和用户输入的密码pwd是否一致 print ' welcome ', name Else:print ' Shibai '            Else:print ' quit! ' Break

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.