In [1]:
#example task: print each character in a word
#one way to do is use a series of print statements
word = 'lead'
print(word[0])
print(word[1])
print(word[2])
print(word[3])
In [5]:
word = 'tin'
print(word[0])
print(word[1])
print(word[2])
print(word[3])
In [6]:
#better approach
word = 'lead'
for char in word:
print (char)
In [7]:
#better
word = 'supercalifragilisticexpialidocious'
for char in word:
print (char)
for loop
to repeat operations general form:
for variable in collection:
do things with variable
loop variable can be arbitrary, need colon at the end
In [10]:
length = 0
for vowel in 'aeiou':
length = length + 1
#print(vowel, length)
print('There are', length, 'vowels')
Let's trace the execution:
In [11]:
#note loop var still exists after loop
letter = 'z'
for letter in 'abc':
print(letter)
print('after the loop, letter is', letter)
In [12]:
print(len('aeiou'))
Python has a built-in function called range that creates a sequence of numbers. Range can accept 1-3 parameters. If one parameter is input, range creates an array of that length, starting at zero and incrementing by 1. If 2 parameters are input, range starts at the first and ends at the second, incrementing by one. If range is passed 3 parameters, it starts at the first one, ends at the second one, and increments by the third one. For example, range(3) produces the numbers 0, 1, 2, while range(2, 5) produces 2, 3, 4, and range(3, 10, 3) produces 3, 6, 9. Using range, write a loop that uses range to print the first 3 natural numbers:
1
2
3
In [1]:
# solution
for i in range(1, 4):
print(i)
In [2]:
result = 1
for i in range(0, 3):
result = result * 5
print(result)
In [3]:
for i in range(0,3):
print(i)
In [3]:
newstring = ''
oldstring = 'Newton'
length_old = len(oldstring)
for char_index in range(length_old):
newstring = newstring + oldstring[length_old - char_index - 1]
print(newstring)
In [ ]: