Python learning basics (learning Python) -- 4.1 Python conditional loop body while statement

Source: Internet
Author: User

The main purpose of loop in a program is to avoid unnecessary labor caused by repeated statements being typed multiple times. Therefore, we need to learn and master the loop programming technology under Python.

This section describes how to use the while LOOP body mechanism in Python. The syntax structure of the while condition loop body is as follows:

[Python]View plaincopy
  1. Conditon_variable_init
  2. While conditon:
  3. (TAB) statement1
  4. (TAB) statement1
  5. (TAB) statement1
  6. Etc.
  7. Condition_modify

The while condition loop body usually requires initialization of the condition (variable) before the while statement (1st rows). The condition in the while statement can be a Boolean expression or a relational operation expression, in the while clause, TAB is used to indent each statement. Generally, some judgments in the while clause use variables in the while clause (7th rows ), if the while statement is not corrected, it will be an infinite loop.

 


For example (print n times in a loop ).

[Python]View plaincopy
  1. Def pwhile (num ):
  2. C = 0
  3. While c <num:
  4. Print (c)
  5. C + = 1
  6. Def main ():
  7. N = int (raw_input ("plz input a num "))
  8. Pwhile (n)
  9. Main ()

Check the running result.

 

Note that the program has a type parameter num used to control the number of loops. row 2nd is a variable in the while LOOP body condition c <num, when c is smaller than num, The while statement (Row 4-5) can be executed. The first row is the print statement, and the second row is the correction condition of the loop body, which is used to control the number of while loops for a certain number of times.

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.