In Class: Week 2 Tuesday, Thursday


We will wrap up some material from Week 1 before moving on to loops and numbers.

String formatting

First, let us work on string formatting - an approach for more easily handling complex print statements. Move into your week 1 directory and remove the previous version of calcTax.py in order to get the updated exercise:
$ cd cs21/inclass/w01-intro
$ pwd
/home/asas/cs21/inclass/w01-intro
$ rm calcTax.py 
rm: remove regular file 'calcTax.py'? yes
$ update21
inclass/w01-intro/calcTax.py
$ ls
WHAT_I_EXPECT_FROM_YOU	add.py	calcTax.py  firstProg.py  loop.py  welcome.py
	
Next, implement a solution for calculating sales tax in calcTax.py that utilizes the string formatting options.

for Loops

Open loop.py. Examine the provided code and run it to see if it follows your understanding. Then, complete the following three exercises:
  1. print out only odd numbers up to 10
  2. print out all of the squares from 1 to some user entered value
  3. EXTRA: loop 3 times, asking the user for a new number and outputting its square value

Week 2 Topics


Move into your week 2 directory for the remaining exercises:

$ cd
$ cd cs21/inclass/w02-loops/
$ ls
accumulateCake.py avg.py	factorial.py sliceAndDice.py triangleString.py
We are going to do some of the following:
  1. Accumulate numbers In avg.py, we are going to write a program that computes the average of integer values that are entered by a user by employing the accumulator pattern. Be careful to avoid errors due to integer division. To create an accumulator pattern, we should first answer these questions to help us code the solution:
  2. Together, we will, implement a solution for calculating the factorial of a user-entered value (e.g., if user enters 6, calculate 6! = 6*5*4*3*2*1)
  3. Numerical expressions Python follows the same precedence of operations as in your math learning (i.e., order of operations). Mainly, we process operators in the following order:
    ()Parentheses
    **exponentiation
    -negation
    *,/,%multiplication, division, modulo
    +,-addition, subtraction
    Symbols on the same tier are processed left to right. Test your understanding of types and mathematical expressions. Evaluate these expressions and see if the result and type are as expected:
    		num1 = 2.5
    		num2 = 4
    		print(type(num1))
    		print(type(num2))
    		print(num1+num2)
    		print(type(num1+num2))
    		print(int(num1+num2))
    
    		print(3/4)
    		print(3%4)
    		print(5%4)
    		print(float(3/4))
    		print(float(3)/4)
    
    		print(3 + 2 * 6**2 + 8 / 2)
    
    		print(3 + (2 * 6)**2 + 8 / 2)
    
    		print(3-7*10**2/6+3)
    
    		#Add parens to make that expression easier to read
    		

  4. The next exercise will bring a few ideas together. Open accumulateCake.py in vim. I have already give the calculation for the volume of one cheesecake. Use your knowledge of accumulator patterns to calculate the total volume of multiple cakes. If you finish quickly, try printing out the accumulating sum as a table using string formatting.
  5. Loops and Strings After introducing strings, we will have some fun printing out interesting patterns with strings. Take a look at triangleString.py where we will print out a right triangle using for loops e.g.,
    			$
    			$$
    			$$$
    			$$$$
    			
    Try it out yourself by adding new patterns to print. First, add a bottom part to the triangle:
    			$
    			$$
    			$$$
    			$$$$
    			$$$
    			$$
    			$
    			
    If there is time, try to print just a diagonal line of characters. Can you further generalize by letting the user choose what character to repeat instead of using the $ symbol?
  6. Accumulation of strings We can accumulate strings using a similar pattern as with numbers. To demonstrate this, we'll do some more complex string patterns in sliceAndDice.py. Together, we'll first slice a word to print a triangle:
    			C
    			Co
    			Com
    			Comp
    			Compu
    			Comput
    			Compute
    			Computer
    			
    On your own, try a few exercises. First, add an asterisks * between each letter in the user entered word:
    			C*o*m*p*u*t*e*r*
    			
    If there is time, or after class, try advancing this idea by putting two asterisks between every two letters:
    			Co**mp**ut**er**
    			

Post-class questions

So * changes its function based on whether you're using it on a float/int or string?
Yes! This is a common occurrence in programming. It's borrowed from the biological concept of polymorphism. Basically, the idea is that * does different things in different contexts, but all are similar in effect (e..g, * means multiplying in all cases - it is multiplying numbers or strings).

in the factorial problem, can you make it such that the program prints "6!=6*5*4*3*2*1=720" for any number given as the input
Yes - but that's a little tough and we'll have to use string accumulation. Maybe see if you can try this after Tuesday's class.
multString = str(x)+"!="  #"6!="
for i in range(x,1):
    multString += str(i)+"*"  #adds next number to string stops at 2

multString += "1="+str(product) # adds "1=720" to the string
print(multString)
		


Why is modulo useful? Why would you need to know if something is even or odd? Couldn't you figure it out without the computer?
If I want to create 4 groups in class and assign each student to a group in round-robin fashion (1,2,3,4,1,2,3,4) I could use modulo. I could do odds and evens on paper, but what if I need my program to figure it for some user-entered value? There is also a way to store values called a hash table that needs to use modulo. If we didn't have hash tables, Google wouldn't exist. Most of cryptography/security protocols use modulo (look up Caesar cypher for an example method to encrypt messages that uses modulo).

Do you have to import the math library into the program in order to use its functions?
Yes!

how to print the $'s backwards
Great question - it was the next exercise on the example we ended with. Think about you can play with the for loop to accomplish this

using another letter instead of i in "for i in range()"?
i is short for iteration. But, you can use whatever you want. Some people use x, others iter, I've also seen ind (for index) In many cases we should use a more meaningful name if it applies (e.g., cake for the accumulateCake example)

When does slicing come in use?
Whenever you need to read data from a file, you'll need slicing. Think about an excel spreadsheet. Imagine if an entire row was a string in your program and I said "Get me all the values in column H". You'd need slicing to jump to the middle of the string. If I am a biologist and I have a DNA sequence, I may want the value of a gene somewhere in the middle of the chromosome - I need slicing to do that. Anytime you need a portion of a full string, slicing is useful. It's unique to Python and tremendously useful.

One question I have about today's topic is that what is the difference between import math and math import*, how do we know which command we should give to access the math library.
Both work. But they work slightly differently. For example, if I want to use the sqrt function it would like like this:
		from math import *
 		
		x = 16
		y = sqrt(x)

		OR

		import math

		x=16
		y=math.sqrt(x)
    
Very subtle difference there - importing still requires us to say where the function is located (math.sqrt); from math import * says to bring all the stuff in the library automatically.

Can you concatenate strings with other data types?
Not unless you convert it to a string first. Outside of floats/ints, you can't mix and match types.

When are ints better than floats?
Floats take up more space in memory. They also are not 100% precise (although usually ok for integers). Memory is not infinite - as an example, my research student was able to create a neural network with 10 times the computing capacity by converting all floats to a more efficient representation.

Will we be able to make an accumulator that will increase something and later decrease after it reaches a maximum?
Yes! We'll need to know about conditionals (next week) to do that

How can we continue to build upon our use of loops?
Can we put a for loop inside of another for loop? And then another one inside of that? And then...(universe collapses into a black hole) (The answer is yes!)

What else besides strings in python are immutable?
int and float are immutable. Tuples are the other major type (we won't use them). You can test this out with theid function which tells you how Python internally represents the location of a value. Notice the id changes when I update i - Python is creating a new number and throwing away the old. We'll see mutable types soon like lists (note that x does not change id even though I modified it).
>>> i = 5
>>> id(i)
18796792
>>> i += 10
>>> id(i)
18796672
>>> x = [5,10]
>>> id(x)
140551779755072
>>> x[1] = 15
>>> id(x)
140551779755072
>>> x
[5, 15]
		


in general, what's the advantage of starting counting with 0?
What is the advantage of counting at 1? :) This is common in math as well (combinatorics). But the answer has to do with the history of indexing and what is really going on. In a nutshell, the index or iteration can be interpreted as "how far from the beginning am I?". When you are starting off, you are at the beginning so you are 0 iterations/elements from the beginning.