Python Learning Five "program control structure-Select structure && loop Structure"

Source: Internet
Author: User

Directly talk about multi-branch structure (Chained), it is relatively simple, just summarize:

Like what

Example 1: Converting an exam score to a grade
Score >= 90
A
Score >= 80
B
Score >= 70
C
Score >= 60
D
Score < 60
E

Python Statement implementations:

Score =98if score>=90:    print ' A ' elif score>=80:    print ' B ' elif score>=70:    print ' C ' elif score>= :    print ' D ' else:     print ' E ' </span>

Output A

Example 2: Finding the solution of a one-dimensional two-time equation

Python Code implementation:

Import matha=float (raw_input (' Input A: ')) B=float (raw_input (' Input B: ')) C=float (raw_input (' Input C: ')) if a==0:    print ' not quadratic ' else:    delta=b**2-4*a*c    if delta <0:        print ' no real root! '    Elif Delta ==0:        print ' Only one root is ',-b/(2*a)    else:        root =math.sqrt (delta)        s1= (-b+root)/(2*a)        s2= (-b-root)/(2*a)    print ' Both distinct solutions is: ', s1,s2
The results of the operation are as follows:


Example 3: Calculating the value of a 1+2+3+...+10
Note: The range function generates 0, 1, ..., 10 sequences

Code implementation:

s = 0i=1for I in range (one):    s + = i      print ' sum is ', s

Output

Example 4: Calculating the constant E

Idea: (1) Call function, (2) write function yourself

Code implementation

Import mathe = 1for i in range (1,100):   e + = 1.0/math.factorial (i) print ' E is ', E

Output: E is 2.71828182846

E = 1fib=1for i in range (1, +):    fib *= i    e +=1.0/fibprint ' E is ', E
Output: E is 2.71828182846

You can see that the two methods are the same, but note the second, the second or more lines below the For loop, to keep the left alignment with the first row, otherwise run as a single statement

Attention:

Range (2, 10) = [2, 3, 4, 5, 6, 7, 8, 9]
Range (2, 10, 3) = [2, 5, 8]
Range (10, 2,-1) =[10, 9, 8, 7, 6, 5, 4, 3]

Python Learning Five "program control structure-Select structure && loop Structure"

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.