These are keywords:
break
stops the loopcontinue
skips the rest of the current looping of the loop but continues to loop as usual afterwards
Let's print powers of two up to $2^{10}$.
x = 1
while x<1000:
x *= 2
print(x)
Try to guess what will happen if we run this:
x = 1
while True:
x *= 2
if x > 100:
break
print(x)
When the break keyword was called, it stopped the loop without doing the print statement underneath.
Continue
is similar, but it will skip the rest of only one looping. Afterwards, the loop will continue as before.
x = 1
while x<1000:
x *= 2
if x == 128 or x == 256:
continue
print(x)
The above output should be missing 128 and 256. The print
statement did not execute during those loopings of the loop because continue skipped over to the next loop.
So far, the types we have seen are: int, float, boolean, function (and builtin_function). Today, a brand new type in python: list.
Lists are really awesome. They represent sequences of objects. They allow us to store lots of things in memory.
Here is how to define them:
xs = [1,2,3,4,5]
print(xs)
type(xs)
They can have all kinds of objects:
words = ["One", "for", "all"]
print(words)
Mixed too:
mylist = [1,2,"Hello", True]
If course you can access the elements. Here is the element at index 0, i.e. the 0th spot in the list.
mylist[0]
The numbering always starts from zero.
print(mylist[0], mylist[1], mylist[2], mylist[3])
This is what happens if you ask for more than they can give ya:
mylist[4]
The list had length 4 and by asking at index 4, we were asking for the 5th element.
Length of the list:
len(mylist)
You can change the contents of a list after you have created it. (they are mutable, this is an important keyword)
mylist = [1,2,"Hello", True]
mylist[2] = "Goodbye"
print(mylist)
Can we add an element? Yes: we use the append function. But the syntax is a little funny:
list_you_want_to_extend.append(the_new_element_you_are_adding)
mylist = [1,2,"Hello", True]
mylist.append("love")
print(mylist)
The 5th element was "love". Just like in the movie.
Deleting elements in a list:
mylist = [14,13,12,11,10,12]
del mylist[2]
print(mylist)
mylist = [14,13,12,11,10,12]
mylist.remove(12)
print(mylist)
By the way, there is an empty list:
xs = []
print(xs)
xs.append("element 0")
print(xs)
list(range(10))
In Python 2, range
produces a list. But not so in Python 3. We have to call list(range(n))
to get an actual list. This is because range creates something which can produce a list but you have to ask it to. We'll come back to this.
# not a list
range(10)
Other ways of using range.
list(range(10,15))
list(range(10,22,3))
for item in [1,10,100,1000,12344]:
print(item)
Easier and cleaner than while
loops.
total = 0
for i in range(100):
total += i
print(total)