Python中的if、while、for 文法及執行個體

來源:互聯網
上載者:User

標籤:切片   white   abc   ==   star   執行個體   階乘   ase   進入   

1.if/while/for

python縮排:

main:    passc  main(param) {}java  main(param){}


if判斷:

if 判斷條件:    執行語句elif  判斷條件:    執行語句else:    執行語句


While迴圈:

whle 判斷條件:       執行語句       break   跳出迴圈continue  跳出本次迴圈,進入下一次迴圈


for 迴圈:

for item in sequence:    執行語句    for i,j in enumerate(list1):    print(i,j)


切片:


l = ['a','b','c','d','e']print(l[0:5])  # 0 << x < 5for x,y in enumerate(l):    print(x,y)結果:    ['a', 'b', 'c', 'd', 'e']    0 a    1 b    2 c    3 d    4 e    print(l[:]) 取到所有


2.Python執行個體

做題的思路和思想最重要:

例1:

ABCD*9=DCBA  A=?B=? C=? D=?   答案: A=1,B=0,C=8,D=9   1089*9=9801

#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time:   2018-01-23 16:31# @Author: Feng Xiaoqing# @File:   if-while-for.pyfor a in range(1,10):    for b in range(0,10):        for c in range(0,10):            for d in range(0,10):                Start = a * 1000 + b * 100 + c * 10 + d                End = d * 1000 + c * 100 + b * 10 + a                if Start * 9 == End :                print ('{0} * 9 = {1}'.format(Start,End))

答案:  

 1089 * 9 = 9801


例2:

求n的階乘0! + 1! + 2! + 3! ...+ n!

#!/usr/bin/env python# -*- coding:utf-8 -*-# @Time:   2018-01-23 15:31# @Author: Feng Xiaoqing# @File:   if-while-for.pydef one(n):    total = 1    if n == 0:        total = 1    else:        for i in range(1,int(n)+1):        total *= i    return totalwhile True:    result = 0    n = input("please input a number:")    if  not n.isdigit() :        print(" the number is error!")        break    for i in range(0,int(n)+1):        result += one(i)        print("0! + 1! + 2! + 3! ...+ n! = {0}".format(result))


Python中的if、while、for 文法及執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.