Professional Documents
Culture Documents
Python: For Loop
Python: For Loop
For Loop
Quang-Vinh Dinh
Ph.D. in Computer Science
Year 2021
For Loop
keyword colon
Code before for
Last True
element
done?
False
Iterables
indentation
String
Code in for
Tuple
List
Dictionary
Code after for
range()
Year 2021 1
For Loop
Last True
element
done?
False
Code in for
2
For Loop
Code before for range(start=0, stop, step=1)
Last True
element range(start=0, stop=5, step=1)
done?
False 0, 1, 2, 3, 4
0, 1, 2, 3, 4
Code after for
3
For Loop
Code before for
break keyword
Last True
element
done?
False Example
break
Code in for
4
For Loop
Code before for
continue keyword
Last True
element
done?
False Example
continue
Code in for
5
Example
PI estimation
Gregory-Leibniz Series
𝑛
−1 𝑖+1
𝑃𝐼 ≈ 4
2𝑖 − 1
𝑖=1
Nilakantha Series
𝑛
−1𝑖
𝑃𝐼 ≈ 3 + 4
2𝑖 + 2 2𝑖 + 3 2𝑖 + 4
𝑖=0
Year 2021 6
Example
Euler's number
𝑛
1
𝑒 ≈ 1+
𝑛
https://www.mathsisfun.com/numbers/e-eulers-number.html
Year 2021 7
Example
Euler's number
𝑒 = 2.71828
1) Compute factorial
2) Compute sum
Formula
Year 2021 8
Example
Euler's number
Demo
Year 2021 9
Example: Quadratic Root
Compute quadratic root for the number N
𝑁=9
9
𝑠𝑒𝑡 𝑥0 = = 4.5
Newton Method 2
Compute 9
𝑛=0
Set a value for 𝑥0 ; n = 0
(𝑥0 = N/2)
𝑛=0
𝑁 9
𝑥0 + 𝑥 4.5 +
𝑥1 = 0
= 4.5 = 6.5 = 3.25
𝑁 2 2 2
𝑥𝑛 +
𝑥𝑛
𝑥𝑛+1 = 𝑛=1
𝑁
2 𝑥1 + 𝑥 3.25 +
9
𝑥2 = 1
= 3.25 = 6.019 = 3.009
2 2 2
n=n+1 𝑛=2
𝑁 9
𝑥2 + 𝑥 3.009 + 3.009
2
𝑥3 = = = 3.00001
2 2
Year 2021 104
Example: Quadratic Root
Compute quadratic root for the number N
Newton Method
𝑁
𝑥𝑛 +
𝑥𝑛
𝑥𝑛+1 =
2
n=n+1
11
Exercises
Fibonacci Sequence
+
0, 1, 1, 2, 3, 5, 8, 13, 21
Length = 9
Year 2021 12
4
Exercises
∞
𝑛
𝑥 2𝑛+1 𝑥3 𝑥5 𝑥7 𝑥9
𝑠𝑖𝑛 𝑥 ≈ −1 =𝑥− + − + −⋯
2𝑛 + 1 ! 3! 5! 7! 9!
𝑛=0
∞
𝑛
𝑥 2𝑛 𝑥 2 𝑥 4 𝑥 6 𝑥 8 𝑥 10
𝑐𝑜𝑠 𝑥 ≈ −1 =1− + − + − +⋯
2𝑛 ! 2! 4! 6! 8! 10!
𝑛=0
∞ 𝑛 1 2 3 4 5
𝑥 𝑥 𝑥 𝑥 𝑥 𝑥
𝑒𝑥 ≈ =1+ + + + + +⋯
𝑛! 1! 2! 3! 4! 5!
𝑛=0
Year 2021 13
4
Exercises
∞
𝑥 2𝑛+1 𝑥3 𝑥5 𝑥7 𝑥9
𝑠𝑖𝑛ℎ 𝑥 ≈ =𝑥+ + + + +⋯
2𝑛 + 1 ! 3! 5! 7! 9!
𝑛=0
∞
𝑥 2𝑛 𝑥 2 𝑥 4 𝑥 6 𝑥 8 𝑥 10
𝑐𝑜𝑠ℎ 𝑥 ≈ =1+ + + + + +⋯
2𝑛 ! 2! 4! 6! 8! 10!
𝑛=0
Year 2021 14
4
Common Errors
Error 1
Year 2021 15
Common Errors
Error 2
Year 2021 16
Common Errors
Error 3
Year 2021 17
Common Errors
Error 4
Year 2021 18
Common Errors
Error 5
Year 2021 19
Common Errors
Error 6
Year 2021 20
Common Errors
Error 7
Year 2021 21
Common Errors
Error 8
Year 2021 22
Common Errors
Error 9
Year 2021 23
Common Errors
Error 10
Year 2021 24
Common Errors
Error 11
Year 2021 25
Common Errors
Error 12
Year 2021 26
Common Errors
Error 13
Year 2021 27
Common Errors
Error 14
Year 2021 28
Common Errors
Error 15
Year 2021 29
Common Errors
Error 16
Year 2021 30
Common Errors
Error 17
Year 2021 31
Common Errors
Error 18
Year 2021 32
Common Errors
Error 19
Year 2021 33
Common Errors
Error 20
Year 2021 34
Common Errors
Error 21
Year 2021 35