Basic python cycle Learning Record

Source: Internet
Author: User
This article shares the Learning Record of the basic python Loop 1. while loop

If the condition is true, the same operation is performed repeatedly. if the condition is not met, the system jumps out of the loop.

While loop condition:

Cyclic operation

(1) while loop example

For example, enter the score of Wang Xiaoming's five courses to calculate the average score.

I = 1 # Initialize the cyclic counter isum = 0 # Initialize the total score variable while I <= 5: # from 1 to 5, print a total of five times of examination scores and sum ('Enter the test scores for the % d course '% I) # prompt the user to enter the score, the formatted output is used, and the value of % d is displayed with the value of I. 1st courses, 2nd courses ...... Sum = sum + input () # assign the user's input score to sum, and save the sum of the 5 scores and I = I + 1 # I increase by 1 for each loop, until 5 jump out of the loop avg = sum/(i-1) # When the fifth execution of I = I + 1, I is 6, jump out of the loop, calculate the sum/(i-1) the value is the average value, and is assigned to avuplint ('average score of five courses of Wang Xiaoming is % d' % avg) # format and output the avg value, because % d is used, the calculated % avg value can be omitted if it is a decimal number.

(2) nested while loop example

After the external loop meets the conditions, the execution code starts to execute the internal loop. when all the internal loops are executed, if the external loop conditions are met, the external loop is executed again, and so on, until the outer loop exists.

For example, enter the five scores of two students and calculate the average scores respectively.

J = 1 # define the initial value of the external loop counter prompt = 'Enter the student name' # define the string variable, this variable can be called when users enter Chinese characters to reduce the hassle of Chinese characters while j <= 2: # defines the external loop as the execution of two sum = 0 # defines the initial score value, which is defined here, this is to enable the sum initialization to be 0 when the second student enters the score, and re-receive the score of the new student and I = 1 # define the initial value of the internal loop counter name = raw_input (prompt) # receive the student name entered by the user and assign the value to the name variable while I <= 5: # define the internal function for five cycles, it is to receive the print of the scores of five courses ('Enter the % d score: '% I) # prompt the user to enter the score, which is formatted and output, the value of % d is displayed with the value of I. There are 1st courses and 2nd courses ...... Sum = sum + input () # receives the user's input score, assigns the value to sum I + = 1 # I variable auto-Increment 1, I changes to 2, continues to execute the loop, until I equals 6, jump out of the loop avg = sum/(i-1) # calculate the average score of the first student sum/(6-1), assign the value to avg print name, 'average score is % d \ n' % avg # average output student score j = j + 1 # After the internal cycle is completed, the external cycle counter j increases from 1 to 2, print the student score in an external loop! '# When the external loop ends, the system prompts that the input is complete!
II. for loop

(1) the for statement can be used to traverse all elements, such as outputting characters in strings one by one, outputting elements in the list one by one, and elements in tuples, elements in the set (pay attention to the order of each element when assigning values), keys in the dictionary ......

For letter in 'Python': print letter result: Python
Fruits = ['watermelon ', 'peach', 'grape '] for fruit in fruits: print fruit result: watermelon peach grape

(2) repeat the same operation

Use the range () function to create a number list

Value range: from the starting number to the ending number

For I in range (): # store 0 to 4 in sequence and print 'Mr. Mangood is cool! 'Result: Mr. Mangood is the coolest! Mr. Mangood is cool! Mr. Mangood is cool! Mr. Mangood is cool! Mr. Mangood is cool!

Enter Wang Xiaoming's scores and calculate the average value.

Subjects = ('Linux system', 'MySQL database', 'Python ') # define a tuple, three elements represent three courses sum = 0 # define the variable num to initialize the score for I in subjects: # assign each element in the tuples to I in sequence, for a total of three print times, enter the % s test score '% I # to indicate the score. the formatted string function is used to name the score using the element table obtained by I each time, % s indicates the string score = input () # The score that receives user input is assigned to score sum + = score # The score is assigned to sum, equivalent to sum = sum + scoreavg = sum/len (subjects) # calculate the average value after jumping out of the for loop. here we use the len () function to calculate the length of the variable subjects, because subjects is defined as a tuples, the length is the number of elements. 3 print 'Wang Xiaoming's average score is % d' % avg # The average score is output: enter the linux system test result 87. enter the Mysql database test result 78. enter the Python language test result 90. Wang Xiaoming's average score is 85.

(3) nested for loop

Enter the scores of Huang Xiaoming and Yang Ying for each of the three courses to calculate the average score.

Student = (23 'Huang Xiaoming ', 'Yang Ying') # define the student name's tuples subjects = ('Linux system', 'MySQL database', 'Python ') # define the course name's tuples for j in student: # take the values of the two students in j for two cycles, sum = 0 # Initialize the score value print '% s students' exam scores' % j # print the title for I in subjects: # define course cycle print 'Enter % s test score' % I # prompt to enter the test score = input () of one of the students () # receive exam scores assigned to score if score <0 or score> 100: # determine the score value range and make a reminder print 'Note score size 'sum + = score # after each score input, sum = sum/len (subjects) # obtain the average score print j, 'average score is % d \ n' % avg # print average score print 'finish student score input work' # prompt to finish the work

III. loop control

The loop control statement can change the normal execution sequence of the loop.

Loop control statement

Break statement: jump out of this loop (only one loop exists in the nested loop)

Continue statement: Skip the remaining statement of the current loop body, re-test the loop state, and enter the next loop. for example, the number of cycles is five times, and the fourth occurrence of the continue occurs, if you do not continue the execution, you can directly perform the 5th cycle judgment.

IV. Comprehensive circular control cases

1. requirement analysis

Display menu

(N) ew User Login

(E) ntering User Login

(Q) uit

Enter choice:

Note: Enter the letter N to receive the new login name and password and save it in the dictionary.

Enter the letter E to receive the logon name, password, search, and matching user information.

Enter Q to exit

2. perform steps

(1) compiling menus

(2) use the while statement to select a menu item-Outer Loop

(3) use the while statement to receive new login name-Inner Loop

(4) Use the if statement to determine the menu and perform related operations.

3. code architecture

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 () # read the string entered on the console, remove unnecessary spaces at the beginning and end of the string, and convert the first string to the lowercase letter print '\ n -- You picked: [% 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): # determine whether the dictionary has input keys. Name value of, if any, triggers the continue to re-execute the while loop. because prompt1 is redefined before the continue is triggered, the new name = raw_input (prompt1) is executed) prompt1 = '-- name taken, try another: 'continue else: break pwd = raw_input ('password:') # After verifying that the key in the dictionary does not have the name value entered, it jumps out of the loop, assign the password you entered to pwd db [name] = pwd # pass the value to the name key in the dictionary db to improve the dictionary data elif choice = 'e ': name = raw_input ("login:") pwd = raw_input ('password: ') password = db. get (name) # upon logon, after receiving the user's login name and password, assign the name key value in the dictionary database to p Assword if password = pwd: # compare whether the password in the dictionary is consistent with the user-entered pwd: print 'Welcome ', name else: print 'shibai' else: print 'Quit! 'Break

The above is the details of the basic python Loop Learning Record. For more information, see other related articles in the first PHP community!

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.