I still do not fully understand the second modification to the code in the factorial solution program
We did two modifications: * We changed the range operator to have two arguments, so that we didn't have to deal with starting the for
loop variable at zero. Before, we had:
for i in range(num):
numToAdd = i + 1
fact = fact * numToAdd
In the loop above, the variable i
starts by being assigned value 0. Then on the next iteration it has value 1, then 2, then ... and so on. We changed this to:
for i in range(1, num+1):
fact = fact * i
This helped simplify the for loop, since the variable i
in our updated program starts by taking the value 1, then 2, then 3, then...
*=
to rewrite the line where we updated the value of the accumulator variable fact
. Previously: fact = fact * i
. Updated: fact *= i
.Why is the letter for the substitution of integers d? (e.g. %d)
The d
indicates that Python will be substituting a value which is a decimal (base 10) integer.
Not a question about today's material, but rumor has it you have a Nerf gun that you use to battle ninjas. If so, you should definitely have it on hand during Friday's class!
Noted.
how to subtract letters (strings) in accumulators?
This is a great question! In Python, strings are immutable, which means that the value cannot be changed. If we have a variable like word
which is storing the string "computer" and we want to remove the last letter, there is no way to do this directly. Instead, we would have to build a new string, and then reassign the variable word
to store that new string.
>>>word = "computer"
>>>word
'computer'
>>>newWord = ""
>>>newWord
''
>>>for i in range(len(word) -1):
... newWord = newWord + word[i]
...
>>>newWord
'compute'
>>>word = newWord
>>>word
'compute'
In the code above, the string accumulator newWord
accumulates the letters of word
, but because the range
has been subtracted by 1, it leaves off the last letter of the string stored in variable word
.
Can you use the % string formatting technique in program files?
Yes, definitely!
When would the accumulator in a for loop be a number other than 0 or 1 and how do you tell which one to use?
Selecting an initial value for accumulators depends on what you are accumulating, and how you are updating the accumulator value. As we get more practice working with accumulators, you'll see many different examples.