Python Basics--04 Flow control statements

Source: Internet
Author: User

1.Python Indentation Rules

Preferably four spaces, followed by tab, no spaces tab mixed

2.Python Flow Control Statement code block principle

: represents the beginning of a code block

If you hit the code in a Python interactive environment, also pay special attention to indentation, and exit indentation requires more than one line of return

3.if Statement 3.1 Ordinary if statement

>>> age=20
>>> if age >=18:
... print ' Your is ', age
... print ' Aduit '
...
Your age is 20
Aduit

3.2if-else statements

Note:else there is a ":" later.

>>> if age >= 18:
... print ' Aduit '
.. else:
... print ' teenager '
...
Aduit

3.3if-elif-else statements

If-elif statement and multi-if statement differences

If-elif condition judgment will be judged from top to bottom, if a certain judgment is True, after executing the corresponding code block, the subsequent condition judgment is ignored and no longer executed.

The multi-if statement is executed all, even if the preceding conditions are met.

>>> if age >=18:
... print ' Aduit '
... elif age >=6:
... print "Teenager"
... elif age >=3:
... print ' Kid '
.. else:
... print ' baby '
...
Aduit

4. Looping statements 4.1for Loops

>>> l= [' Adam ', ' Lisa ', ' Bart ']

>>> for name in L:

... print Name

4.2While Loops

>>> n=10

>>> x=0

>>> while X<n:

... print X

... x+=1

4.3break Exit Loop

>>> sum = 0

>>> x=1

>>> while True:

... sum+=x

... x+=1

... if x>100:

... break

4.4continue Continue looping

>>> l=[75,98,59,81,66,43,69,85]

>>> sum =0.0

>>> n=0

>>> for x in L:

... if x<60:

... continue

... sum +=x

... n+=1

4.5 multi-loop nesting

>>> for x in [' A ', ' B ', ' C ']:

... for y in [' 1 ', ' 2 ', ' 3 ']:

... print X+y

Python Basics--04 Flow control statements

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.