Thursday, October 6, 2011

Loop de loop

As I'm feeling worse than I was yesterday, I decided. Let's keep going on Python. I know. I'm crazy. Right now the thought of not making Silicon Valley Code Camp is bumming me out since I'm getting sicker by the minute.

Anyways, onto for loops, strings, and tuples!

What I find pretty nice is that the for loop for Python is super flexible. You can use it to traverse a word and it would stop at the end of the word.  It also pretty simple and straight forward.

for <variable> in <range>:
   DO SOMETHING!

So you can do something like:

for letter in word:
   print letter

This will print each letter on a separate line of the word. So simple!

OMG you can do "in" statements too to do comparison. It's like heaven. Built in! So you can say

if "a" in phrase:
   print "There's a letter 'a' in your phrase."

I use "in" in SQL all the time. It's like crazy nuts. OH...well you can only use single characters for "in."

Indexing is a little weird. So say:

word = "Flouncy"
print word[-2] --> c

That's right you can do negative indexing. That's just weird to me as it's not standard to what I've learned. But what's crazier is slicing with negative and positive indices.

print word[-4:5] --> un

Get it?

Tuples is just a list, but unlike other languages, it's not restricted to be one type of list. So you can create tuples with integers, strings, candy, muffins, pie...I guess I'm hungry.

I'm actually super sleepy, so I'll have to code this chapter's work another day. Good night world.

No comments:

Post a Comment