Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Lesson 15

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Lesson 15

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Python From Scratch

Python Scope & Modules & Datetime


Lesson 15 Content
• Python Scope
• Local Scope
• Function Inside Function
• Global Scope
• Naming Variables
• Global Keyword
• Python - Scope Exercises

• 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()

Function Inside Function


As explained in the example above, the variable x is not available outside the function, but it is
available for any function inside the function:
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()

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)

Using the dir() Function


There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module


You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])

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"]

Test Yourself With Exercises


Exercise:
What is the correct syntax to import a module named "mymodule"?
mymodule
Python Datetime
Python Dates
A date in Python is not a data type of its own, but we can import a module named datetime to work with
dates as date objects.
Example
Import the datetime module and display the current date:
import datetime

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"))

Creating Date Objects


To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.
Example
Create a date object:
import datetime

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"))

A reference of all the legal format codes:

Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

%p AM/PM PM

%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST
%j Day number of year 001-366 365

%U Week number of year, Sunday as the first 52


day of week, 00-53

%W Week number of year, Monday as the 52


first day of week, 00-53

%c Local version of date and time Mon Dec 31 17:41:00 2018

%C Century 20

%x Local version of date 12/31/18

%X Local version of time 17:41:00

%% A % character %

%G ISO 8601 year 2018

%u ISO 8601 weekday (1-7) 1

%V ISO 8601 weeknumber (01-53) 01

You might also like