In [2]:
word = 'lead'
print word[0]
print word[1]
print word[2]
print word[3]


l
e
a
d

In [3]:
word = 'tin'
print word[0]
print word[1]
print word[2]
print word[3]


t
i
n
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-3-7974b6cdaf14> in <module>()
      3 print word[1]
      4 print word[2]
----> 5 print word[3]

IndexError: string index out of range

In [4]:
word = 'lead'
for character in word:
    print character


l
e
a
d

In [5]:
word = 'tin'
for character in word:
    print character


t
i
n

In [10]:
word = 'oxygen'
for character in word:
    print character
    character = 'Z'
print "done"


o
x
y
g
e
n
done

In [11]:
word = 'oxygen'
for char in word:
    print char


o
x
y
g
e
n

In [14]:
length = 0
for vowel in 'aeiou':
    length = length + 1
print "There are", length, 'vowels'


There are 5 vowels

In [15]:
print len('aeiou')


5

In [16]:
'Z' * 3


Out[16]:
'ZZZ'

In [17]:
cube = 1
for count in 'Z' * 3:
    cube = cube * 5
print cube


125

In [18]:
print range(3)


[0, 1, 2]

Challenge:

Write code using for loop and range() that takes a number and computes its exponent.

E.g. if you have 2 and 3, the answer should be 8. Use print to display the result.

Solution:

Use result to accumulate the result in, so that the sum for 5^3 effectively become 1*5*5*5. Note that the loop variable isn't actually used (it is a simple counter), we the anonymous variable _ has been used as a loop variable.


In [4]:
number = 5
exponent = 3
result = 1
for _ in range(exponent):
    result = result * number
print number


5

Reverse a string

Given a string, print its reverse.


In [3]:
string = 'abcdef'
reversed_string = ''
length = len(string)
for count in range(length):
    reversed_string = reversed_string + string[length - count - 1]
    #print (length - count - 1), reversed_string
print reversed_string


5 f
4 fe
3 fed
2 fedc
1 fedcb
0 fedcba
fedcba

In [ ]: