Loops
We’ll mainly use for loops in this course. Here’s the python syntax for a for-loop:
for i in range(a, b):
The
range
function produces a list of numbers between the starting number a to the ending number b. By cycling through all the numbers in this list, we run a loop these many times.Run the next cell, which contains a for-loop to print every number between 1 and 9. In the next cell, write a for-loop to print the employee IDs of the employees mentioned in exampleDf.
Set
There are two easy ways to create a set. The first one is just a direct initialization:
set1 = {"item1", "item2", "item3"}
The second way involves using the set constructor to create a set:
set2 = set(("item1", "item2", "item3"))
Just like with Dictionaries, duplicates are not allowed. Sets don’t have a particular order and the set is unchangeable.
To get the length of a set:
len(set)
Tuples
A tuple is another way of storing many values in a single variable. Like with Sets, there are two ways to create a new tuple.
tupleOne = ("itemOne", "itemTwo", "itemThree", "itemFour")
The second way to create a tuple is using the tuple constructor.
tupleTwo = tuple(("itemOne", "itemTwo", "itemThree", "itemFour"))
The Same length method applies
len(tupleOne)
Dictionaries
A dictionary in Python is a lot like a dictionary in the real world. For every word, there’s a particular meaning associated. This is what a dictionary is like. You look for the word, and find its meaning. You’ll see the syntax to create a new dictionary in the next cell. You can run this.
A dictionary consists of two main parts, a key and a value. If you specify a particular key, you can extract the corresponding value from the dictionary. However, dictionaries don’t allow duplicate keys, for obvious reasons. If a real world dictionary contained two words with the same spelling, but different meanings, how would you know which one to reference?
dictionary["key"]
for example, provides the value at the particular key within the dictionary dict.
len(dictionary)
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.