Session 4 - Modules & list comprehensions
Today we will examine modules in Python. You will create your own modules and learn how to use Python’s built-in modules. In two weeks, we will continue with 3rd party modules (code created by others) and you will learn how to incorporate these into your own code and ensure that others using your code have access to the same 3rd party modules and the correct versions.
First, we will examine list comprehensions, a concise way to generate lists.
Today on the practical level, you will work with four modules in addition to comprehensions:
Os module
Subprocesses module
Requests module
Learning goals
After this week you will be able to:
Use listcomprehensions.
Use Python’s built-in modules.
Find and use 3rd party modules.
Use the requests module to fetch website data.
Materials
Exercises
List Comprehensions
Ex 1: Alphabet List Comprehensions
Create a list of capital letters in the english alphabet
Create a list of capital letter from the english aplhabet, but exclude 4 with the Unicode code point of either 70, 75, 80, 85.
Create a list of capital letter from from the english aplhabet, but exclude every second between F & O
Ex 2: Clothes List Comprehension
From 2 lists, using a list comprehension, create a list containing:
[(‘Black’, ‘s’), (‘Black’, ‘m’), (‘Black’, ‘l’), (‘Black’, ‘xl’), (‘White’, ‘s’), (‘White’, ‘m’), (‘White’, ‘l’), (‘White’, ‘xl’)]
1 colors = ['Black', 'White']
2 sizes = ['s', 'm', 'l', 'xl']
If the tuple pair is in the following list, it should not be added to the comprehension generated list.
1 soled_out = [('Black', 'm'), ('White', 's')]
Ex 3: list Comprehension exercises
Create a list of even numbers from 0 to 20.
Create a list of squares of numbers from 1 to 10.
Create a list of all the vowels in a given string.
Create a list of common elements in two given lists.
Create a list of words from a given string that have more than 4 letters.
Modules
Ex 5: OS Module exercise
1# Do the following task using the os module
2
31. create a folder and name the folder 'os_exercises.'
42. In that folder create a file. Name the file 'exercise.py'
53. get input from the console and write it to the file.
6 * In VSCode and using Notebooks the console will pop up in the top of the editor. So ```input()``` will propt the user for input, and i VScode this is in the top of the editor.
74. repeat step 2 and 3 (name the file something else).
85. read the content of the files and and print it to the console.