Python Learning notes Conditional loops and other statements

Source: Internet
Author: User

Assignment statements

Normal Assignment:

>>> x, y, z =
>>> print x, Y, Z
1 2 3
>>> x, y = y,x
>>> print x, y
2 1

Tuple (Sequence) unpack assignment:

>>> a = (a)
>>> x, y, z = a
>>> x
1

Dictionary assignment:

>>> people = {"Name": "CQ", "Age": "20"}
>>> Key,value = People.popitem ()
>>> Key
' Age '
>>> value
' 20 '

Increment Assignment:

>>> x = 5
>>> x + = 2 #x = x + 2

>>> x
7
>>> x *= 3 #x = x * 3
>>> x
21st

Conditional statements:

Remembering statement blocks

If something:

Do

Elif anothing:

Do

Else

Do

Understand the following Boolean operator, the basic ture,false

While loop: (just give a condition, but keep running the program when it meets the criteria)

>>> x = 1
>>> while x < 10:
... print X
... x + = 1
...
1
2
3
4
5
6
7
8
9

For loop: (Gives a range, loops within the range)

>>> for x in range (10):
... print X
...
0
1
2
3
4
5
6
7
8
9

If you can use a for loop, try not to use a while loop (while easily causing a dead loop)

Jump out of the loop:

Break

>>> for I in Range (99,0,-1):
... if i%2 = = 0:
... print I
... break
...
98 #从99 to 0 steps to 1, the first to meet the conditions to jump out of the loop, and not to print all, if there is no break will print all

While True/break

>>> while True:
... word = raw_input (' Enter a word: ')
... if not word:
... break
.. else:
The. print ' the word is ' + word #当输入一个值时, will print the value and continue the loop request Enter a If Word does not enter, then jump out of the loop

List Deduction---Light-weight loops:

>>> [x * x for x in range (10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x * x for x in range] if x%2 = = 0]
[0, 4, 16, 36, 64]

Python Learning notes Conditional loops and other 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.