If, while, for syntax and instances in Python

Source: Internet
Author: User

1.if/while/for

Python indentation:

MAIN:PASSC Main (param) {}java main (param) {}


If judgment:

If judgment condition: Execute statement elif judgment condition: Execute statement else: EXECUTE statement


While loop:

Whle judgment Condition: Execute statement break jump out of the loop continue jump out of the loop and into the next loop


For loop:

For item in sequence: Execute statement for I,J in Enumerate (list1): Print (I,J)


Slice:


L = [' A ', ' B ', ' C ', ' d ', ' E ']print (L[0:5]) # 0 << x < 5for x, y in Enumerate (l): print (x, y) Result: [' A ', ' B ', ' C ', ' d ', ' E '] 0 a 1 B 2 c 3 D 4 E print (l[:]) Take all


2.Python instance

The idea and thought of doing a problem is the most important:

Example 1:

ABCD*9=DCBA a=? B=? C=?   D=? Answer: 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))

Answer:

1089 * 9 = 9801


Example 2:

Ask for factorial 0 of N! + 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&nbSp;in range (0,int (n) +1):         result += one (i)          print ("0! + 1! + 2! + 3! ...+ &NBSP;N!&NBSP;=&NBSP;{0} ". Format (Result))


If, while, for syntax and instances in Python

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.