A. while loop
1. ? Need a loop variable
? ? – Initialized outside loop
? ? – Changes within loop
? ? – Test for termination depends on variable
? ?? Useful to think about a decrementing function
? ?– Maps set of program variables into an integer
? ?– When loop is entered, value is non-negative
? ?– When value is <= 0, loop terminates, and
? ?– Value is decreased every time through loop
? ?eg: abs(x) – ans**3 (smaller the solution, nearer we will done.)
2. different between branching program and looping program:
? ? Branching structures (conditionals) let us jump?to different pieces of code based on a test
? – Programs are constant time
? ? Looping structures (e.g., while) let us repeat?pieces of code until a condition is satisfied
? – Programs now take time that depends on values?of variables, as well as length of program
3. some command
a.
b. If the command break is executed within a loop, it halts evaluation of the loop at that point and passes control to the next expression.
c. stop infinite loop : control C
B. for loop: ? ?for <identifier> in <sequence>:
? ? ? ? ? ? ? ? ? ? ? ? ? ?<code block>
1. some logics:
? Identifier bound to first value in sequence
? Code block executed
? Identifier bound to next value
? Code block executed
? Continues until sequence exhausted or a break?statement is executed
? To generate a sequence of integers, use
– range(n) = [0, 1, 2, 3, …, n-1]
– range(m,n) = [m, m+1, …, n-1]
PS: spaces in strings as characters too!
2. range function:
more info: https://docs.python.org/3/library/functions.html#range
3. in range, 'num' variable will assign new value. (In python you can?assign?new values to variables. In this case the for loop will iterate in the list [0, 1, 2, 3, 4], each time the for loop iterates from the list it will assign num a new value.)
4. 5%2=1 5/2=2 5.0/2=2.5
5. if no indent, continue execute following if?
6. Approximation Methods
? Suppose we now want to find the square root?of any non-negative number?
? Can’t guarantee exact answer, but just look?for something close enough
? Start with exhaustive enumeration
– Take small steps to generate guesses in order
– Check to see if close enough
?general method:
-Exhaustive enumeration
– Bisection search
– Newton-Raphson (for root finding)
7. Print on the same line: use comma
# 習題中出現(xiàn)的問題:
a. 多次重復的部分可以命名成變量
b. 盡量避免在循環(huán)判斷當中有重復惫皱。