Python Lesson 15
Python Lesson 15
• Python Scope
• What is a Module?
• Create a Module
• Use a Module
• Variables in Module
• Naming a Module
• Re-naming a Module
• Built-in Modules
• Using the dir() Function
• Import From Module
• Python - Modules Exercises
• Python Dates
• Date Output
• Creating Date Objects
• The strftime() Method
• Python - Datetime Exercises
Python Scope
A variable is only available from inside the region it is created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used
inside that function.
Example
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global
scope.
Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables
If you operate with the same variable name inside and outside of a function, Python will treat them as
two separate variables, one available in the global scope (outside the function) and one available in the
local scope (inside the function):
Example
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.
The global keyword makes the variable global.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Also, use the global keyword if you want to make a change to a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using
the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Python Modules
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module Built-in Modules
You can create an alias when you import a There are several built-in modules in Python,
module, by using the as keyword: which you can import whenever you like.
Example Example
Create an alias for mymodule called mx: Import and use the platform module:
import mymodule as mx import platform
a = mx.person1["age"] x = platform.system()
print(a) print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Note: When importing using the from keyword, do not use the module name when referring to
elements in the module. Example: person1["age"], not mymodule.person1["age"]
x = datetime.datetime.now()
print(x)
Date Output
When we execute the code from the example above the result will be:
2023-01-28 13:47:51.369249
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Example
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond,
tzone), but they are optional, and has a default value of 0, (None for timezone).
The strftime() Method
The datetime object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned
string:
Example
Display the name of the month:
import datetime
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
%j Day number of year 001-366 365
%C Century 20
%% A % character %