Lecture #2 Python Data Type and Variables data data type ...

Lecture #2 Introduction

Over of Python data types

Python Data Type and Variables

In terms of programming, a "data" is an individual object that represents a qualitative or a quantitative value, such as a color or 23 units of a product. In order for the Python interpreter to implement an object to comply with the IPO (input, processing, and output) model of a computing, the object must be represented by an appropriate type of data.

A girl's first name, such as "Taylor", is an intangible object which is represented by a combination of English characters: T-a-y-l-o-r. Since a girl's first name can only consist of alphabets (no numerals, no symbols), it is necessary to define rules for picking only the proper characters to form a data that represents of a girl's first name. With the rules, no one can enter a combination of characters like 452 (obviously a numerical value) to a data field that stores data of a girl's first name. Similarly, a data field that holds girl's age should not be assigned a value like "Alicia".

The term "data type" (or simply "type") refers to the definition of nature settings of a Python object in order to properly represent the object and process it with Python's language core. In computing, a value that carries a meaning of some kind is known as a "literal". A string literal is a sequence of characters enclosed by either a pair of single quotes or a pair of double quotes. A string literal represents a string value. A number is a sequence of digits that are not enclosed by quotes. A number represents a numerical value in units. In Python, the most frequently used types are data of numbers and string values.

As discussed in a previous lecture, the "data type" is implicitly determined by the Python interpreter as the moment when a value is to assign to a variable. This lecture, thus, will start with the discussion of available Python data types.

Python's language core comes with a set pre-defined data types, known as "primitive data type". They are the built-in data types encapsulated in several "object classes" of Python. Each object class has a unique identifier, such as "int", "float", "str", "bool", and "NoneType". The term "to be encapsulated" in programming means "to be defined".

Similar types of data are grouped in categories. The following table provides an overview of available categories of Python's primitive data types.

Categories numbers

Description

Numbers are typically made of numerical characters and the decimal sign (.). Some numbers are expressed in scientific notation, such as 2.3e25 (which means 2.3?1025).

Python class int and float

string

A string is a combination of any Python recognizable

str

characters (even in other natural language like Chinese,

Japanese, and Farsi).

Boolean

Boolean value are strictly limited to two possible values: bool True and False. Sometime, True is represented by 1 while False is represented by 0.

container

The "container" type refers to a group of data types that collect Python objects in a "container" object.

tuple, list, dictionary

Python Programming ? Penniel P. Wu, PhD.

49

Concept of variables

set

A Python set is an unordered collection of elements. It is set

used for calculation based on the Set Theory of

mathematics.

special

The keyword None is a single value that signify "absence NoneType of a value".

The next several sections will start with the discussion about what a variable is in Python, and continue to discuss each of these categories in detail.

In programming, the term "variable" refers to a programmer-defined name that represents a group of registers in the physical memory (typically the DRAMs). These registers make up a fixed number of bits, as specified by the data type, to temporarily host the value that is assigned to the variable. Since the value stored in these registers can be modified, they are "variable" values. In the following statement, "x" is the identifier of a variable that is assigned 4265 as value. In other words, a Python value "x" is declared to hold an integer 4265.

>>> x = 4265

The following figure illustrates how a series of consecutive registers in a DRAM, from 21st to the 24th, are grouped to keep an integer 4265. In this scenario, "x" is the identifier of the variable and is also the temporarily name of the group of registers.

Register ... 21 22 23 24 ...

identifier x

The value it holds 4265

Python programmers can assign an identifier to a Python object through the declaration of a variable. The following illustrates how to: (a) designate an identifier to a variable; (b) assign a value to the variable; and (c) set the data type of the variable.

>>> x = 2.1 >>> type(x) >>> id(x) 20027688 >>> y = "orange" >>> type(y)

In the above example, the statement x = 2.1 reads "assign a number 2.1 to the variable x" and the statement y = "orange" reads " assign a string literal `orange' to y". The equal sign (=) represents the "assignment" operator which assign a value to a variable. A later lecture will discuss about Python operators in details. By the way, in terms of Python, the value 2.1 in the statement x = 2.1 and the value "orange" of the y = "orange" statements are referred to a "literal".

Variables are useful in problem solving, particularly when some mathematical calculation is required. In Physics, the concept of "uniform motion" is described as x = vt, where x is the distance traveled, v is the constant velocity, and t is the time the object is in motion. The equation, x = vt, uses three variables: x, v, and t. A Python programmer can write a program to solve the following problem.

Python Programming ? Penniel P. Wu, PhD.

50

"Jennifer drives along the freeway to Las Vegas. She sets the cruise on 80 mile per hour. After 30 minutes, how far has she travelled?"

The following is a sequential list of statements to solve this problem in Python. The answer is 40.0 miles.

>>> v = 80 >>> t = 0.5 >>> x = v*t >>> x 40.0

In terms of object-oriented programming, officially designate a meaningful identifier to a variable is known as "declaration". Declaring a variable provides a way to label and access data without the need to know exactly where in the physical memory the data is stored. However, unlike other language, Python does not require the programmer to specify the data type when creating a variable. Python interpreter will automatically regulate the data type of a variable according to the value it is assigned to host. In the following, the variable x is set to be "int" type first, then "str" and "tuple" accordingly.

>>> x = 2 >>> type(2) >>> x = "Python" >>> type(x) >>> x = (9, 8, 7, 6) >>> type(x)

The following is another example that demonstrates the feasibility to use one variable name to represent different kinds of objects at different times.

>>> x = 0 >>> x = "Hello" >>> x = [1, 2, 3]

# x bound to an integer object # Now it's a string. # And now it's a list.

As illustrated in a previous lecture, another way to display the value stored in a variable is to use the print() function, as shown below.

>>> firstname = "Larry" >>> print(firstname) 'Larry'

The above statements create a variable called "firstname" and assign it with the value "Larry". The print() function then displays the value assigned to firstname on the screen.

Python recommends a naming convention for creating variable identifiers. Basically, a variable identifier (or variable name) must: (a) start with either an underscore (_) or a letter (such as "a" or "A"); (b) followed by a combination of alphanumerical characters (letters and digits), except the blank space; (c) use the underscore (_) to con; and (d) avoid using any Python reserved keywords. The following table lists some of the reserved keywords.

and assert break class

Table: Python reserved keywords

del

for

is

elif

from

lamda

else

global

not

except

if

or

raise return try while

Python Programming ? Penniel P. Wu, PhD.

51

Numerical types

continue def

exec finally

import in

pass print

yield

Under this naming convention, the following are examples of legal variable identifiers. However, class, 1_Spam, spam$, and my@#! are illegal variable names. Also, Python is casesensitive, SPAM, spam, SpAm, sPAm, and SpAM are different identifiers.

>>> first_name = "Taylor" >>> _last_name = "Swift" >>> _age = 24 >>> best_song = "You Belong With Me" >>> year = 2009

It is also necessary to note that identifiers that have two leading and trailing underscores, such as __main__, are system-defined names. They have special meanings to the interpreter; therefore, programmers should avoid using two leading or trailing underscore (__) to name Python variables. A later lecture will discuss about such identifiers in detail.

In the "numbers" category, Python 2 data could be one of the four types: int, long, float, and complex. Interestingly, Python 3 drop the long type and preserves only three distinct numeric types: integers, floating point numbers, and complex numbers.

Numerical data are values that represent a number of units. A numerical literal consists of digits only (no letters, not symbols) and is used to express a number of units. They should not be enclosed by quotes. Python 3 provide three object class to define numerical data: "int" (short for integer), "float" (short for floating-point), and "complex" (short for complex numbers). The following is a complete list of numerical types supported by Python 3.

Type int

Table: Numeric literals

Mathematic name

Examples

Integers

>>>1234 1234

>>> -24

-24

>>> 0

0

float

Floating-point

>>> 1.23 >>> 3.14e-10 >>> 5.07E210 >>> 5.07e+210

complex Complex number

3+4j, 3.0+4.0j, 3J

Integers are whole number that can be positive, negative, or 0 and is written in a form without comma(s). In Python, the int type can be expressed in decimal format (the base is 10), which is the default format. The following prints out a negative integer expressed in the decimal format.

>>> print(-25) -25

In Python, an integer can also be expressed in binary (the base is 2), octal (the base is 8), or hexadecimal (the best is 16) formats. Except the decimal format, all other formats required a prefix to specify their formats. The following table lists the formats and their prefixes with examples. By the way, prefixes are not case-sensitive.

Format

Prefix

Example

Python Programming ? Penniel P. Wu, PhD.

52

Decimal Binary Octal hexadecimal

N/A 0b (or 0B) 0o (or 0O) 0x (or 0X)

>>> 124 124 >>> 0b1111100 124 >>> 0o174 124 >>> 0x7c 124

Binary literals start with a leading prefix zero-b, "0b" (or "0B"), followed by a series of 0's and 1's. The following demonstrates how to specify a value in binary format. The value 124 in decimal format is equivalent to 1111100 in binary, 174 in octal, and 7c in hexadecimal.

>>> 0b1111100 124

The following demonstrates how Python interpreter automatically convert non-decimal literals

to their decimal equivalents and display only the decimal values as results. Apparently, the

conversion is based on the formula: ? -1 =a1?b0 + a2?b1 + a3?b2 + ... + an?bn-1,

where an is the n-th digit (counting from the right to left) and b is the base.

>>> 1, 10, 100 (1, 10, 100) >>> 0b1 , 0b10, 0b100 (1, 2, 4) >>> 0o1, 0o10, 0o100 (1, 8, 64) >>> 0x01, 0x10, 0xFF (1, 16, 255)

# decimal literals # binary literals # Octal literals # Hex literals

The binary literal, 0b1010, is calculated by the Python interpreter with the base being 2 to find its decimal equivalent: 1?23 + 0?22 + 1?21 +1?20 = 11.

>>> 0b1011 11

Octal literals start with a leading prefix zero-o, 0o (or 0O), followed by a series of octal digits 0-7; hexadecimals start with a leading prefix 0x (or 0X), followed by hexadecimal digits 0~9, and A~F. In hexadecimal, "A", "B", "C", "D", "E", and "F" (or "a", "b", "c", "d", "e", and "f"), as digits that represent 10, 11, 12, 13, 14, and 15 respectively. Hexadecimal digits are not case sensitive.

>>> 0XFF == 0Xff == 0XFf == 0XfF True

A number express in 0o37 = 3 ? 81 + 7 ? 80 = 31.

>>> y = 0o37 31

The octal literal, 0o177, is calculated with the base being 8: 1?82 + 7?81 + 7?80 = 127

>>> 0o177 127

The hexadecimal literal, 0x9ff, is calculated with the base being 16: 9?162 + f?161 + f?160 = 9?162 + 15?161 + 15?160 = 2559.

>>> 0x9ff

Python Programming ? Penniel P. Wu, PhD.

53

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download