Python conditional statements and loops

Source: Internet
Author: User

1. Judgment and Circulation
Python indent
Main
Print ("Hello")
Print ("Hello world.")

if 判断条件:    执行语句elif 判断条件:    执行语句else:    执行语句
while 判断条件:    执行语句
a = 100while a>1:    print(a)    a-=1    if a==50:        break   # 退出循环    if a==55:        print("5555555555")        continue   # 此次循环结束,进入下一个循环

Break jumps out of the loop
Continue into the next cycle

for item in sequence:   执行语句
l = ["a","b","c","d","e","f"]print(l[:])print(l[0:5])        # 大于等于0     小于5  0 <= a > 5print(l[0:-1])        # 大于等于0     小于5  0 <= a > 5for x,y in enumerate(l):    # 打印列表中元素以及下标    print(x,y)

2, the programming idea is the most important

The most important thing in a programming language is thought.
ABCD Times 9=DCBA, begging for a=? , b=? , c=? , d=?

for A in range(1,10):    for B in range(0,10):        for C in range(0,10):            for D in range(1,10):                start = 1000*A+100*B+10*C+D                end = 1000*D+100*C+10*B+A                if start * 9 == end:                    print("A={}".format(A))                    print("B={}".format(B))                    print("C={}".format(C))                    print("D={}".format(D))                    print("{0} * 9 = {1}".format(start,end))

return Result:
A=1
B=0
C=8
D=9
1089 * 9 = 9801

3. Seeking factorial
To find the factorial of 1-n and
1! + 2! + 3! + 4! +5! + ··· + n!
0! = 1
1! = 1
2! = 1 2 = 2
3! = 1
2 * 3 = 6

def one(n):    total = 1    if n ==0:        total = 1    else:        for i in range(1,n+1):            total *= i    return totalprint(one(3))status=1while status:    result = 0    n= input("Please input a number(n>=0) : ")    for i in n:        if not i.isdigit():            print("The number of you input is error.")            exit(1)    if int(n) < 0:        print("The number of you input is error.")        break    for i in range(0,int(n)+1):        result += one(i)    print("0! + 1! + 2! + ··· ··· + n! = {}".format(result))

Python conditional statements and loops

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.