Lecture 16 + HW

posted Feb 26, 2013, 1:04 PM by Samuel Konstantinovich   [ updated Feb 26, 2013, 1:08 PM ]

Homework:

1. Figure out what it means when you index strings like this:

x="blammajamma!"

print x[3:10]

print x [1:4]

2. Also remember your lab should be done by tomorrow, you need to know the chr(i) command, which converts an integer i, into a symbol.

chr(65) --> 'A'

chr(97) --> 'a'

chr(98) --> 'b'


Class notes:

Consider why the program below acts the way it does. 

If you run this code, the results would be on the right side:

Python Code:

Python Shell output + input

def double(x):

return 2*x


def double2(x):

print 2*x


print "Part 1:"

double(5)

double2(6)

#why does the output say 12 only,

#notice that double 5 works when

#it is tested later


print "Part 2:"

x=double(9)

y=double2(10)


print "Part 3:"

print x

print y

=============RESTART============

>>>

Part 1:

12

Part 2:

20

Part 3:

18

None

>>> "I AM TYPING STUFF HERE!"

'I AM TYPING STUFF HERE!'

>>> double(5)

10

>>> double2(6)

12


A discussion on return vs print, and some questions followed

Main ideas:

-Values typed onto the shell get printed back automatically. Part of the confusion is because typing 5+1 by itself on the python shell prints the answer 6. Typing 5+1 in a python program by itself does NOT print 6. If you want to see a result, you should explicitly print it. -Seeing none as a result is when you print a function that had no return.

-A return means that a function evaluates to some value

-Strings are data, keep them in variables so you can use them later, don't print them

-Printing is throwing the data away, the computer doesn't see it anymore.


Indexing strings:

We can use square brackets to get a single location inside of a string.

x="Hello Dolly"

x[0]   refers to the 'H' , we always use 0 to signify the beginning of a list or string.

x[1] refers to the 'e'

x[5] refers to the space ' ', spaces, tabs and newlines count as single characters.

>>>y= "h\ne\nl\nl\no"

y[0] is the h

y[1] is the \n or newline character.


you can look at y, the way we write it by typing the variable name in the python shell:

>>>y   

'h\ne\nl\nl\no'

>>>

you can also print it to see how it looks:

>>>print y

h

e

l

l

o

>>>



Comments