Python - tutorial - 11/14

scope - modules - dates - math

Revision:


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 1: a variable created inside a function is available inside that function:

        def myfunc():
            x = 300
            print(x)
        myfunc()
    

Function inside fuction: the local variable can be accessed from a function within the function:

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.

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 2: 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. Also, use the "global" keyword if you want to make a change to a global variable inside a function.

Example 3: if you use the global keyword, the variable belongs to the global scope:

        def myfunc():
            global x
            x = 300
        myfunc()
        print(x)
    

Example 4: 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, i.e a file containing a set of functions you want to include in your application.

Toreate a module just save the code you want in a file with the file extension .py.

Use a module: we can use a module by using the import statement.

Example 5: import the module named mymodule, and call the greeting function:

        import mymodule
        mymodule.greeting("Jonathan")
    

When using a function from a module, use the syntax: module_name.function_name.

Variables in module: The module can contain functions, but also variables of all types (arrays, dictionaries, objects etc):

Naming a module: you can name the module file whatever you like, but it must have the file extension .py

Re-naming a module: you can create an alias when you import a module, by using the "as" keyword./p>

Example 6: create an alias for mymodule called mx:

        import mymodule as mx
        a = mx.person1["age"]
        print(a)
    

Built-in modules: there are several built-in modules in Python, which you can import whenever you like.

Example 7: import and use the platform module:

        import platform
        x = platform.system()
        print(x)
    

Using the dir() function: there is a built-in function to list all the function names (or variable names) in a module, i.e the dir() function. The dir() function can be used on all modules, also the ones you create yourself.

Example 8: list all the defined names belonging to the platform module:

        import platform
        x = dir(platform)
        print(x)
    

Import from module: you can choose to import only parts from a module, by using the "from" keyword. 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"]

Example 9: import only the person1 dictionary from the module:

        from mymodule import person1
        print (person1["age"])
    


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 10: import the datetime module and display the current date:

        import datetime
        x = datetime.datetime.now()
        print(x)
    

Date output: The date contains year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object.

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

Example 11: create a date object:

        import datetime
        x = datetime.datetime(2020, 5, 17)
        print(x)
    

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 12: 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 day of week, 00-53 - 52
%W - Week number of year, Monday as the first day of week, 00-53 - 52
%c - Local version of date and time Mon Dec 31 17:41:00 - 2018
%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


Python - math

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.

Built-in math functions: The min() and max() functions can be used to find the lowest or highest value in an iterable. The abs() function returns the absolute (positive) value of the specified number. The pow(x, y) function returns the value of x to the power of y (xy).

Example 13: min() max() functions

        x = min(5, 10, 25)
        y = max(5, 10, 25)
        print(x)
        print(y) 
    

Example 14: abs() function

        x = abs(-7.25)
        print(x)
    

Example 15: Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

        x = pow(4, 3)
        print(x)
    

The math module: Python has also a built-in module called "math", which extends the list of mathematical functions. To use it, you must import the math module. When you have imported the math module, you can start using methods and constants of the module.

Example 16: the math.sqrt() method

        import math
        x = math.sqrt(64)
        print(x)
    

Example 17: the math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:

        import math
        x = math.ceil(1.4)
        y = math.floor(1.4)
        print(x) # returns 2
        print(y) # returns 1
    

Example 18: the math.pi constant, returns the value of PI (3.14...):

        import math
        x = math.pi
        print(x)