Friday, August 26, 2022

Understanding the Numeric and Sequence Data Types

Python provides three main numeric types for handling different kinds of numeric data:

• int. This data type is used for storing integer numbers — numbers that do not have a decimal component. For example, 0, 3, 42, and 4817 are all integers. Technically, the bool data type for storing Boolean values is a subtype of int.

• float. This data type is used for storing floating‐point numbers, those that have a decimal component. For example, 9876.54321 is a floating‐point number. 

• complex. This data type is used for storing complex numbers — numbers that consist of a real component and an imaginary component.

Sequence Data Types

In Python, a sequence is a set of data that is ordered — in other words, it has a specific order. Some sequence data types are immutable, or unchangeable, whereas others are mutable, or changeable.

The following list explains the main data types in the sequence category:

• list. This data type contains a sequence of similar items — for example, a list of integers might contain 1, 2, and 3, or a list of strings might contain dog, cat, and snake. Lists are mutable, so you can change their contents, their order, or both. 

• tuple. This data type is used to store an ordered sequence of values. The values do not need to be unique, so a tuple can contain multiple instances of the same value. A tuple is immutable, so you cannot change its contents or its order once you have created it. 

• range. This data type is used to contain an immutable sequence of integer values — for example, from 1 to 10. Ranges are often used to control the number of iterations in for loops.

• str. This data type is used for storing strings of text. Python considers a string to be an immutable —unchangeable — sequence of characters. 

Share:

Wednesday, August 24, 2022

Understanding Python’s Data Types

Python includes various built‐in data types designed for handling different types of data efficiently. For example, Python’s bool data type is designed for storing Boolean data, data that can be either True or False but no other possible value. Similarly, Python’s str data type is designed for storing strings of text.

Python’s built‐in data types mostly fall into six categories: numerics for numbers; sequences for data such as lists; mappings for dictionaries, where one item maps to another; classes for creating custom objects; instances for the objects created with those classes; and exceptions for handling errors.

The Python programming language is primarily implemented using C, a long‐standing and robust programming language that is still widely used across many industries. C is called a low‐level programming language, which means that it can interface directly with hardware features, lending itself to software and operating‐system development. C is relatively easy to understand but extremely hard to master.

Python is a high‐level programming language and includes many built‐in features that C does not natively support, giving you an easier way to harness some of the power of C to develop solutions rather than using C directly. Python’s extensive feature set and capability to run well on many platforms contributes to its great versatility.

Because Python is built on C, Python’s data types are constructed using combinations of C’s data types. For example, Python includes a data type called set that enables you to store multiple pieces of information in a single variable — a capability that C itself does not directly provide. Furthermore, some of Python’s more complex data types are constructed using simpler Python data types.


Share:

Monday, August 22, 2022

Creating a Variable and Assigning Data to It

In Python, you create a variable and assign data to it in a single statement. For example, consider the following line:

price = 125

This line (A) declares a variable called price and initializes it by assigning the value 125 to it. This  value is an integer, a number with no decimal component, so Python gives it the int data type.

You can then change the value if needed, as in the following line:

price = 250

This line (B) assigns the value 250 to the price variable.

You can also assign data of a different data type to the price variable. For example, the following line (C) assigns a string value:

price = "moderate"

Because the price variable does not have a static data type, it accepts the string value without comment. However, some IDEs display a warning when your code contains this kind of change, because it could represent an error, as a programmer would not normally change the data type contained in a variable.


To see what data a variable contains, you can use the print command to display the contents to the console. For example, the following line (A) displays the contents of the price variable:

print(price)

The print command works fine for values that are text or can easily be interpreted as text, but trying to print a variable containing binary data — for example, an image —will usually cause problems.

To see what data type the value assigned to a variable has, you can use the type command with the variable’s name. For example, the following line (B) displays the data type of the value assigned to the price variable:

type(price)

This command returns the value’s class, such as <class 'int'> for the int data type or <class 'str'> for the str data type.



Share:

Friday, August 19, 2022

Understanding Variables and Their Usage

Python supports various different data types, such as integers for whole‐number values, Booleans for True/False values, and strings for words or other sequences of text characters. After creating a variable, you can assign any type of data to it that Python uses. 

So What Is a Variable?

A variable is an area of memory in which you can store data. When you create a variable, you give it a name that enables you to access it to retrieve or change its contents. When your code runs, Python allocates a space in memory for each variable.

For example, you might create a variable called name to store an employee’s name (A). The name would normally be a string of text characters, such as Anna Connor or Bill Ramirez, so the value would receive the str data type, which Python uses for strings. Similarly, you might create a variable called age to store the employee’s age in years as a whole number (B). That value would be an integer, so Python would assign the value the int data type that it uses for integers. Or you might create a variable called isOnProbation to store the employee’s probation status (C). This variable would store the value True or the value False, and Python would assign the value the bool data type that it uses for Boolean values.


In Python, variables themselves do not have data types, so you do not specify the data type when you
create a variable. Instead, the value assigned to the variable has a type. So instead of, say, creating a
variable and giving it the int data type, which is for integers, you would create a variable and assign data of the int data type to it.

This treatment of variables is called dynamic typing and is different from various other programming languages that enable — or require — you to give each variable a specific data type, a practice called  static typing. For example, Microsoft’s Visual Basic programming language encourages you to declare each variable explicitly and assign a data type. For instance, Dim intAge As Integer “dimensions” — creates — a variable called intAge that has the Integer data type and will accept only integer data. Such explicit declarations prevent you from putting the wrong type of data in a variable — trying to do so causes an error — and from overwriting the variable unintentionally by using the same name later in your code.

Share:

Wednesday, August 10, 2022

Import a Module or Object Under an Alias

The standard way of importing a module or an object adds it to Python’s mapping table, but Python also enables you to import a module or object under an alias of your choice. Using an alias can make your code more compact and easier to read.

Because you have not imported the module, you cannot refer to the object via the module. So if you have imported only the path object from the os module, you cannot use os.path to refer to it; you must use the unqualified path instead.

When you import a module or an object from a module, you can create an alias for the object. For example, the following statement imports the module acme_quants_derivatives and assigns the alias aqd:

import acme_quants_derivatives as aqd

You can then use the alias to refer to the module or object. For example, the following statement uses the aqd alias to refer to the ohlc() method in the acme_quants_derivatives module, assigning it to the variable n:

n = aqd.ohlc()

Similarly, you can use the from syntax to import an object from a module under an alias. The following example imports the version method from the platform module under the alias pv:

from platform import version as os_version

Likewise, you can then use the alias in your code. For example, the following statement uses the print() function to display the value of the method aliased as os_version:

print(os_version())

This statement returns information such as the following on a Mac:

Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021;

root:xnu-7195.141.6~3/RELEASE_X86_64

Using an alias can be useful when you import multiple modules or objects that have the same name or names similar enough to be confusing. Using a shorter alias can also tighten and streamline your code.

List the Methods and Variables in a Module or Object

After importing a module or object, you can use Python’s dir() function to list the methods and variables it contains. For example, if you have imported acme_quants_derivatives and assigned the alias aqd, you can list the contents of aqd like this:

dir(aqd)

Python returns a list of the contents, such as the following:

['__builtins__', '__cached__', '__doc__', '__file__', '__init__', '__loader__',

'__name__', '__package__', '__spec__', 'export_weekly_stats', 'five_minute_

chart', 'import_daily_stats', 'ohlc', 'statbank', 'two_minute_chart']

The items whose names start and end with two underscores are built‐in Python methods. These are called dunder methods after the double underscore characters that precede and follow their names.

The items whose names do not use the double underscores, such as import_daily_stats and ohlc, are the methods and variables in the module or object.

You access the methods and variables through the alias of the imported object. For example, the following statement creates a variable named my_two_minute_chart and assigns to it the result of the two_minute_chart() method, which it accesses via the aqd alias:

my_two_minute_chart = aqd.two_minute_chart()

Reload a Module

Normally, you do not need to reload a module, because the Python interpreter does not unload modules. This means the only reason to reload a module is if it has changed since you first loaded it. While possible, such change in a loaded module is relatively rare.

To reload a module, first use the import command to import the importlib package:

import importlib

You can then use the reload() method of importlib to reload the module. For example, the following statement reloads the module named cust1:

importlib.reload(cust1)

Share:

Monday, August 8, 2022

Importing Modules and Objects

When you load Python using the python or python3 command, depending on the operating system, Python loads its core modules, which provide essential functionality. When you need further functionality, you can import one or more additional modules, files containing Python code.

For example, when you need to work with directories, such as creating or deleting them, you can import the os module, which contains methods for interacting with the operating system.

You can either import an entire module by using an import statement or import an individual object from a package by using a from... import statement.

Understanding What Modules Are and Why Python Uses Them

In Python, a module is a stand‐alone file that contains code. Python breaks down code into modules so as to have multiple smaller files rather than one gargantuan file. These smaller files have various advantages, such as helping the organization of code by functionality, streamlining the updating of code, and making code run better on less‐powerful systems by avoiding loading items that are not needed.

The main disadvantage of having code in separate modules is that your code must load any modules it needs. But as you will see, loading the modules is quick and easy.

Import a Module

To import a module, use the import keyword and specify the module name. For example, the following statement imports Python’s os module, which provides operating system–related commands:

import os

Similarly, if you have created a custom module named acme_calculations.py, you can import it by using the following command:

import acme_calculations

Note that you omit the .py file extension from the custom module’s filename in the import statement. When you import a module of your own like this, navigate to the directory that contains the module first, and then launch Python from there. Alternatively, you can import the module from a subdirectory of the directory from which you launched Python. For example, if the acme_calculations module is stored in the final subdirectory, specify the subdirectory like this:

from final import acme_calculations

Access the Contents of an Imported Module

When you import a module like this, you specify the module’s name to access its contents. For example, the os module’s contents include the path module, which provides methods for working with file‐system path names. After importing the os module, you access the path module like this:

os.path

Similarly, if you have imported the acme_calculations module, and it contains a method named ave_product, you access it through the module like this:

acme_calculations.ave_product()

Import an Object from a Module

Instead of importing an entire module, you can import a single object from a module. You might do this if that object is the only part of the module you will need and you want to be able to refer directly to the object rather than having to refer to it via the module. Counterintuitively, importing only an object does not reduce resource usage, as Python imports the whole module into its mapping table; the difference is in how you refer to the object.

To import an object from a module, begin the statement with the from keyword; then supply the module name, then the import keyword, and finally the object name. For example, the following statement imports the path module from the os module:

from os import path

After importing a single object like this, you refer to it by its unqualified name, such as path in this case, rather than via its parent module, such as os.path. Here is an example:

print(path)

If the object you import contains other objects or methods, you can access those objects or methods by using the name of the imported object followed by a period and the name of the item you want to use. For example, the path object contains many methods, including os.path.basename(), which returns the base name of the specified path. After importing the path object, you can access the basename() method via the path object like this:

path.basename()

You can also import a nested object on its own. For example, the following statement imports basename() from os.path:

from os.path import basename

Share:

Saturday, August 6, 2022

Understanding Comments in Python

Python enables you to add comments to your code. A comment is text that appears in a script but that is marked as not to be executed. You can add comments to your code at any point. For example, as you develop a script, you might use comments to describe the tasks the code needs to perform and possible approaches for them. After finishing the script’s commands, you might rework the comments so that they explain what the script does. Such comments will help others understand and maintain the code.

Formally, Python supports only single‐line comments, but you can also use multiline strings to create informal multiline comments.

Create Formal Comments Using the # Character

Python uses the # character to mark the start of a single‐line comment. You can place the # character at the start of the line to make the entire line into a comment, as in the following example:

# display the value of y

print(y)

Alternatively, you can place the # character after some code, as in the following example. This method works better for short comments and for comments you intend to remove once you get the code  working.

t = "Placeholder 1" # replace this placeholder text

You cannot use the continuation character, \, to continue a single‐line comment to the next line. Instead, type # at the beginning of the next line if you need to continue the comment, as in the following  example:

# prompt the user for the company name

# compare the company name to an approved list

Using Multiline Strings to Create Informal Comments

Another way to create a multiline comment in a script is to create a multiline string but not assign it to a variable. To create a multiline string, you place three double quotes at the beginning and at the end, or three single quotes at the beginning and at the end. The following example uses three double quotes:

"""

Run an external check with the chem_verify() method

to confirm the formula is correct.

Log the formula in the standard file.

"""

This method of creating informal comments works but has no real advantage over using the # character on each line. You should know about this method not because you should use it in your own code but because you may encounter it in other people’s code.

Using Comments to Prevent Code from Executing

Apart from adding textual commentary to your code, comments have a secondary use: You can use the # character to prevent a specific line of code from executing. This is called commenting out the code —turning a statement into a comment prevents the code from running without you having to remove it  from the script, but you can restore the code by removing the comment character.

For example, the # character comments out the first of the following statements:

# u = input("Type your name: ")

u = "Bob" # default name for testing

print("You are " + u + ".")

Share:

Wednesday, August 3, 2022

Understanding the main() Function

Many Python scripts include a function called main() that contains the main set of actions the script performs. In this post, you learn the purpose of the main() function and when and how to create one.

You also learn about the two ways to run code using the Python interpreter. How you run a script affects how Python sets the built‐in __name__ parameter, which you can use to control whether the main() function runs.

As its name suggests, the main() function typically forms the core part of a Python script. You would normally use the main() function in conjunction with an if statement that checks the value of the __name__ parameter. Doing so enables your script to determine whether it was launched from the command line or whether it was imported into the interpreter or into another script or module.

Here is pseudocode showing a main() function and its if statement, with italics indicating a placeholder:

def main():

statements

if __name__ == "__main__":

main()

Here is how this works:

• def. This keyword starts the definition of the function.

• main():. This is the name of the function, followed by a colon to end the line. This line is called the function header.

• statements. This is where you place statements that specify the actions the main()function is to take. The statements are indented by four spaces to indicate that they belong to the function’s block of code.

• if. This keyword begins the condition, which compares the value of the __name__ parameter to the string "__main__". Two equal signs, ==, denote equality. The double quotes, ", mark the beginning and end of a literal string of text. The colon ends the line.

• main(). This statement tells Python to execute the main() function if the condition evaluates to True.

This statement is indented by four spaces to show it belongs to the if statement’s block of code.

When to Create a main() Function?

Create a main() function in any script that you want to have execute in a different way when it is run from the command line than when it has been imported into the interactive interpreter or into another script or module.

Understanding the Two Ways to Run Python Code

You can run a Python script either by launching it from the command line or by importing it into the interactive interpreter or another Python file.

Launch a Script via the Command Line

The first way to launch a script is by using the command line. You start by opening a terminal window, such as a Command Prompt window on Windows or a window in the Terminal app on macOS or Linux. You then navigate to the appropriate folder, type the Python app’s name and the script’s name, and press enter.

For example, to run the script called my_script.py from the current folder, you might use this command on Windows:

python myscript.py

Or you could use this command on macOS or Linux:

python3 my_script.py

When you launch a script from the command line, Python sets the script’s __name__ parameter to __main__.

Import a Script into the Interactive Interpreter or into Another Script or Module

To import a script, you use the import keyword followed by the script’s name without its extension. For example, if the script’s name is acme_calcs.py, you can import it using the following statement:

import acme_calcs

When you import a script into the interactive interpreter, into another script, or into another module, Python sets the script’s __name__ parameter to the script’s name without the extension. Continuing the previous example of importing, Python sets the __name__ parameter to acme_calcs.

Share: