Range Over Built in Karel

Using range in Python to iterate over various built-in data structures. Let’s see how to use range and similar constructs with some common data structures.

def main():
    # Here we use a loop to sum the numbers in a list. Arrays work similarly.
    nums = [2, 3, 4]
    sum = 0
    for num in nums:
        sum += num
    print(f"sum: {sum}")
    
    # `enumerate` provides both the index and value. Above we didn't need the index, so we didn't use `enumerate`.
    # Sometimes we actually want the indexes though.
    for i, num in enumerate(nums):
        if num == 3:
            print(f"index: {i}")
    
    # Iterating over a dictionary to get key/value pairs
    kvs = {"a": "apple", "b": "banana"}
    for k, v in kvs.items():
        print(f"{k} -> {v}")
        
    # Iterating over just the keys of a dictionary
    for k in kvs.keys():
        print(f"key: {k}")
    
    # Iterating over a string to get Unicode code points.
    # The first value is the starting byte index of the character and the second the character itself.
    for i, c in enumerate("go"):
        print(i, ord(c))

if __name__ == "__main__":
    main()

To run the program, save the code in a file named range_over_built_in_types.py and execute it with Python.

$ python range_over_built_in_types.py
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Now that we can run basic Python programs and see how to iterate over various data structures, let’s learn more about the language.

查看推荐产品

Comments powered by Disqus