Concise Python tutorial-6. Control Flow

Source: Internet
Author: User

 

Concise Python tutorial --- 6. Control Flow

 

In python, there are three control flow statements: if, for, and while.

If statement

The IF statement is used to detect a condition. If the condition is true, the program jumps to execute a statement block (called the if statement block ), otherwise, the program will jump to execute another statement block (else statement block ). Else clauses are optional.

Num1 = 1;

Num2 = 2;

If num1> num2:

Print (u'num1 is greater than num2. ');

Elif num1 = num2:

Print (u'num1 equals num2. ');

Else:

Print (u'num1 is smaller than num2. ');

Print U "program execution ends. ";

Note that Elif and else are optional. The simplest if statement is as follows:

If true:

Print 'true ';

You can also use the if statement in the IF statement block. This internal if statement is called a nested if statement.

Num1 = 1;

Num2 = 2;

If num1 <num2:

If num2 = 2:

Print u'num2 is equal to 2. ';

Else:

Print u'haha. ';

Note: Python does not have the switch statements in C/C ++, Java, and C #. You can use the IF-Elif-else statement to indirectly implement the switch function.

While statement

The while statement allows you to execute a piece of code repeatedly. This is similar to the while in C/C ++, Java, and C. The difference is that the while statement of python can have an optional else clause.

Num = 10;

While num> 0:

Print "num =", num;

Num = num-1;

Else:

Print U "num is less than or equal to 0. ";

For statement

Num = 1;

For I in range (1, 5 ):

Print "I =", I;

I = I + 1;

Else:

Print "over ";

Note: In the for and while loops of Python, The else statements (as long as there are else statements) after the loops exit ).

Break and continue statements

Similar to C/C ++, Java, and C #, Python also contains the break and continue statements, which are used to forcibly end loop execution.

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.