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]