Learn to write: Python for loop range function Xrange function

Source: Internet
Author: User

Script one:

#!/usr/bin/env python
# Coding:utf8
sum100 = 0

For I in range (101):
sum100 + = i
# (1) range is a function that can be valued, the top of which is 0-100 and does not contain 101

# (2) can also be specified, such as range (1,101) from 1 to 100

# (3) can also specify the step size, such as range (1,101,2) is to go from 1 to 100 end of the odd number

Print sum100

Script two:

Xrange uses the method of delay calculation, when you need to produce this number, the top is to use not all produced

Xrange (3)
>>> for I in Xrange (3):
... print I
...
0
1
2

Script three: output Fibonacci sequence

#!/usr/bin/env python

Fibs = [0, 1]

For I in range (8):
Fibs.append (Fibs[-1] + fibs[-2])//append Append-1 and-2 for the last two numbers

Print fibs


#!/usr/bin/env python

A, b = 0, 1

For I in range (10):
Print A,
A, B = B, a + B//python support Direct swap, no intermediate variables required


>>> [For I in Range (3)]//Put 30 in the list, put several times by range

[30, 30, 30]

>>> [i * * 2 for I in range (1,6)]//Put the results of the previous execution in the list, put several times by range to decide

[1, 4, 9, 16, 25]

>>> [i * * 2 for I in range (1,11) if I% 2]//will execute result put list, plus judgment, not 0 is true

[1, 9, 25, 49, 81]




This article is from the "Court of the Odd Tree" blog, please be sure to keep this source http://zhangdl.blog.51cto.com/11050780/1827617

Learn to write: Python for loop range function Xrange function

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.