Common examples of Python

Source: Internet
Author: User

Python language type: Strong-type language, dynamic language

Examples

1. Ask for the sum of the odd number within 100

The odd number can be printed by a number that is not equal to 0 for 2, or by using the For loop step

S=0

For I in range (1,100,2)

S+=i

Print (s)

2. Seeking the sum of the factorial of the

Use the For loop to set the range, accumulate in the loop

A=1
S=0
For I in Range (1,6):
A=a*i
S=s+a
Print (s)

3. Given a 5-digit number, reverse print

First to determine whether there is a 0 after the five-digit number, if there is not printing, if there are 0 in the middle can not skip. Example: 20500

a=20500

b=10

Flag=false #开关

For I in Range (a):

S=a%b

a=a//b

If flag or S: #第一次和第二次循环s =0,flag=false cannot enter, the third s=5 can enter, enter if after flag=true, so the back of 0 can also print

Print (s)

Flag=true

  

4. Print the Fibonacci sequence within 100

You can use the while loop to implement

A=0

B=1

While b<100:

Print (b)

A,b=b,a+b

5. Finding the 101th Fibonacci sequence

A=0

B=1

For I in range (1,100):

if i = = 101:

Print (b)

A,b=b,a+b

6. Print 99 multiplication table

You can use the For loop to implement

For I in Range (1,10):

For j in Range (i,10):

S=i*j

Print (i, ' * ', j, ' = ', s,end= ' \ t ')
Print ()

or using the. Format implementation

For I in Range (1,10):
line = "
For j in Range (i,10):
line+= ' {0}*{1}={2:<4} '. Format (I,J,I*J)
Print (line)

7. Print Diamond

For I in Range ( -3,4):
L=-i If i<0 else I
Print (' *l+ ' * ' * (7-l*2))

8. Ask for prime numbers within 100000

Count=0 #计数
For I in Range (2,100000):
For j in Range (2,i-1):
If i%j==0:
Break
Else
Count + = 1
Print (Count,i)

Common examples of Python

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.