Python Learning Five "program control structure-choice structure && cycle structure" __python

Source: Internet
Author: User

Speak a lot of branch structure directly (Chained), relatively simple, on the summary:

Like what

Example 1: Converting test scores to levels
Score >= 90
A
Score >= 80
B
Score >= 70
C
Score >= 60
D
Score < 60
E

Python Statement implementation:

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

Output A

Example 2: Solving the solution of a two-time equation

Python Code implementation:

Import Math
a=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 ',-b/(2*a)
    else:
        root =math.sqrt (delta)
        s1= (-b+root)/ (2*a)
        S2= (-b-root)/(2*a)
    print ' Two distinct solutions are: ', s1,s2

The results of the operation are as follows:


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

Code implementation:

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

Output 55

Example 4: Compute constant E

Train of Thought: (1) Call function, (2) Write function

Code implementation

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

Output: E is 2.71828182846

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

You can see that the results of the two methods are the same, but note that the second, for Loop, the second or more lines are aligned to the left of the first line, otherwise the run is a single statement

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

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.