In [2]:
word = 'lead'
print word[0]
print word[1]
print word[2]
print word[3]
In [3]:
word = 'tin'
print word[0]
print word[1]
print word[2]
print word[3]
In [4]:
word = 'lead'
for character in word:
print character
In [5]:
word = 'tin'
for character in word:
print character
In [10]:
word = 'oxygen'
for character in word:
print character
character = 'Z'
print "done"
In [11]:
word = 'oxygen'
for char in word:
print char
In [14]:
length = 0
for vowel in 'aeiou':
length = length + 1
print "There are", length, 'vowels'
In [15]:
print len('aeiou')
In [16]:
'Z' * 3
Out[16]:
In [17]:
cube = 1
for count in 'Z' * 3:
cube = cube * 5
print cube
In [18]:
print range(3)
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
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
In [ ]: