CHAPTER 3
Getting Started with Variables
In this chapter, you learn to work with variables, named areas of memory that you can use to store data as your apps run. You explore the different data types Python uses and learn how to use each data type effectively. Along the way, you create variables by assigning data to them, retrieve data from variables, change the contents of variables, and determine the data type of the values assigned to variables.
Understanding Variables and Their Usage
Understanding Python’s Data Types
Work with Floating-Point Values
Understanding Variables and Their Usage
In this section, you learn the essentials of variables, which are named areas of memory that you can create for storing data while your Python code runs.
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. See the following section, “Understanding Python’s Data Types,” for details on Python’s data types.
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.
A Variable Does Not Have a Data Type, But Its Value Does
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.
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.
Seeing What Data and Data Type a Variable Contains
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.
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.
Understanding How Python Builds on the C Programming Language
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.
Understanding the Numeric 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. The following section, “Work with Integers,” provides examples of working with the int
data type in Python. 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. The section “Work with Floating-Point Values,” later in this chapter, gives you examples of working with the float
data type in Python.complex
. This data type is used for storing complex numbers — numbers that consist of a real component and an imaginary component. Complex numbers have mostly specialized uses beyond the scope of this book.Understanding the 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. See the section “Start Working with Lists,” later in this chapter, for more about this data type.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. See the section “Work with Tuples,” later in this chapter, for more about this data type.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. The section “Start Working with Strings,” later in this chapter, gets you started with the str
data type, while Chapter 9, “Working with Text,” shows you the most useful moves with strings.In addition to the sequence data types — list
, tuple
, range
, and str
— discussed so far in this section, Python provides a set
data type for storing sets of data. A set
is not a sequence because it does not have a specific order.
Python also provides a single mapping data type, dict
, which is used for creating dictionaries. A dictionary in Python is not a dictionary in the everyday sense, although there are some similarities between the two: A key in the dictionary maps to a particular value, enabling you to look up that value.
Understanding the Set Data Type
In Python, the set
data type enables you to store multiple values in a single variable. The set
data type has the following characteristics:
The section “Work with Sets,” later in this chapter, gives you an example of creating and manipulating a set.
Understanding the Mapping Data Type
Python’s mapping category contains a single data type, dict
, which is used for dictionaries. A dictionary consists of key/value pairs, with the key in each pair giving you access to set, retrieve, or modify the associated collection of information in the value.
A dictionary is unordered; you access the data by supplying the appropriate key rather than an index value. A dictionary is mutable, so you can change its contents after creating it.
The section “Start Working with Dictionaries,” later in this chapter, introduces working with dictionaries. Chapter 11, “Working with Lists and Dictionaries,” goes into dictionaries in depth.
Understanding Python’s Classes
In Python, a class is a kind of template you use for creating a new object of a particular type. You can create a class object to organize the functions and other code in a particular project.
That sounds nebulous, but if you work with office productivity software, you are likely used to a similar paradigm. For example, if you need to create many memos of the same type in Microsoft Word, you may create a custom memo template containing the layout and formatting for the memo, and perhaps some VBA code for automation. That memo template is analogous to a Python class.
Chapter 12, “Working with Classes,” explains how classes work, tells you what classes are useful for, and shows you how to create a class and put it to use.
Understanding the Instance Data Type
In Python, an instance is an individual object created from a particular class. For example, say you create a class that contains the functions needed to run a particular data-aggregation and assessment task. When you want to work on that data, you create an instance of the class — or, to use the formal term, you instantiate the class.
Continuing the previous example, when you need to produce a memo, you create a new document based on your memo template rather than using the memo template itself. The document is analogous to an instance of the template class.
Chapter 12, “Working with Classes,” covers how to create and use instances of your custom classes.
Understanding the Exception Data Type
In Python, an exception is an object representing an error that occurred during code. Chapter 10, “Handling Errors,” shows you how to work with Python’s built-in exceptions to handle errors when they occur. This chapter also explains how to create custom exceptions.
Work with Integers
Python provides the int
data type for storing integer values. An integer is a whole number, one with no fractional component. For example, 1, 7, and 49 are integers, whereas 1½ and 7.25 are not.
In this section, you use the input()
command twice to prompt the user to enter two integers. Each input()
command returns a string that you convert to an integer by using the int()
command. You then use the addition operator, +
, to add the numbers; use the str()
command to create a string from the result; and use the print()
command to display that string.
Work with Integers
Create the Script
In Visual Studio Code, create a new script, and then save it.
For example, press + , click Select a Language, and then click Python. Press + , specify the filename and location, and then click Save.
Type the following statement, which uses the input()
command to prompt the user to enter an integer and assigns the result to a variable named strN1
:
strN1 = input("Enter an integer: ")
Press , and then type the following statement, which prompts the user to enter another integer and assigns it to a variable named strN2
:
strN2 = input("Enter another integer: ")
Press , and then type the following statement, which uses the int()
command to convert strN1
to an integer and assigns it to a variable named intN1
:
intN1 = int(strN1)
Press , and then repeat step 4, but this time convert strN2
to an integer and assign it to intN2
:
intN2 = int(strN2)
Press , and then type the following statement, which adds intN1
and intN2
, assigning the result to a variable named intTotal
:
intTotal = intN1 + intN2
Press , and then type the following statement, which uses the str()
command to convert intTotal
to a string:
strTotal = str(intTotal)
Press , and then type the following statement, which uses the strings to display the calculation and its result:
print(strN1 + " + " + strN2 + "=" + strTotal)
Run the Script
Click Run Python File in Terminal ().
The Terminal pane opens.
The Terminal pane displays the details of the code it is running.
The first prompt appears.
Type a value and press .
The second prompt appears.
Type another value and press .
The calculation and its result appear.
Work with Floating-Point Values
A floating-point value is a value that includes both an integer part and a decimal part, such as 6.155 or 0.1. In Python, floating-point values are often called floats.
A floating-point number’s value is represented in binary using two components, a mantissa and an exponent. The mantissa stores the binary value for the number, whereas the exponent specifies the position of the decimal point in the mantissa. This means that, while a float is an efficient means of storing a number that includes a decimal point, its accuracy can vary.
Work with Floating-Point Values
In Visual Studio Code, create a new script, and then save it.
For example, press + , click Select a Language, and then click Python. Press + , specify the filename and location, and then click Save.
Type the following statement, which prompts the user to enter the Fahrenheit temperature, assigning the result to the variable degF
:
degF = input("Enter the Fahrenheit temperature: ")
Press and type the following statement, which assigns the input()
command’s string and explanatory text to a variable named result
:
result = degF + "degrees Fahrenheit is "
Press and type the following statement, which converts the input()
command’s string to a float
data type:
degF = float(degF)
Press and type the following statement, which subtracts 32
from the float value in degF
and assigns the result to the variable named degC
.
degC = degF - 32
Press and type the following statement, which multiplies the value in degC
by 5
:
degC = degC * 5
Press and type the following statement, which divides the value in degC
by 9
:
degC = degC / 9
Press and type the following statement, which rounds the degC
value down to one decimal place:
degC = round(degC,1)
Type the following statement, which derives a string from the degC
value and adds that string and further explanatory text to the existing string in the result
variable:
result = result + str(degC) + " degrees Celsius."
Press and type the following statement, which uses the print()
command to display the contents of the result
variable:
print(result)
Click Run Python File in Terminal ().
The Terminal pane opens.
The Terminal pane displays the details of the code it is running.
The first prompt appears.
The input()
prompt appears.
Type a Fahrenheit temperature and press .
The result appears.
Work with Boolean Values
A Boolean value has only two possible states: True
and False
. The keywords True
and False
must use an initial capital followed by lowercase letters; other casing causes errors.
Boolean values are useful for checking status and making decisions in code. You can use the bool()
function to determine whether a particular value is True
or False
. For example, if a particular value is True
, the code takes certain actions; otherwise — since that value must be False
— the code takes other specific actions. You can use the logical operators and
, or
, and not
to create complex Boolean expressions.
Work with Boolean Values
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named number1
and assigns the value 10
to it, and then press :
number1 = 10
Type a similar statement to create a variable named number2
and assign the value 10
to it too, again pressing to complete the command:
number2 = 10
Type the following statement and press to display the result of testing whether number1
equals number2
:
print(number1==number2)
Note: Python uses ==
to compare equality. It uses =
for assigning values, as in step 3.
Python returns True
, the Boolean result for the comparison.
Type the following statement and press to display the result of testing whether number2
is greater than number1
:
print(number2>number1)
Python returns False
, the Boolean result for the comparison.
Type the following statement and press to create a variable named are_numbers_equal
and assign to it the result of testing whether number1
equals number2
:
are_numbers_equal = number1==number2
Type the following statement and press to display the type of the are_numbers_equal
variable:
type(are_numbers_equal)
The type appears.
Type the following statement and press to display the value of the are_numbers_equal
variable:
print(are_numbers_equal)
The value appears.
Type the following statement and press to toggle the value of the are_numbers_equal
variable:
are_numbers_equal = not are_numbers_equal
Type the following statement and press to display the value of the are_numbers_equal
variable:
print(are_numbers_equal)
The value appears.
Type the following statement and press to compare the are_numbers_equal
variable to False
; to quit Python if they match; and, if not, to display the value of are_numbers_equal
:
quit() if are_numbers_equal == False else print(are_numbers_equal)
Python quits.
The terminal’s standard prompt appears.
Work with Tuples
Python provides several data types that are sequences, including tuples, lists, strings, and sets. A tuple is a variable that stores an ordered sequence of values. Unlike a list, whose contents and order you can change, a tuple is immutable, so you cannot change its contents or its order. Unlike a set, a tuple can contain multiple instances of the same value. Tuples are useful for grouping related information that you want to be able to use as a single item.
In this section, you use a terminal window to create and manipulate tuples.
Work with Tuples
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named offices
and assigns to it a tuple of five cities, and press :
offices = ("Atlanta","Bridgeport",
"Chicago","Chicago","Denver")
Note: You can create an empty tuple by placing a pair of parentheses with no contents after the tuple’s name — for example, myEmptyTuple = ()
.
Type the following statement, which displays the tuple's contents, and press :
print(offices)
Note: When creating a tuple that contains only a single item, you must use a trailing comma, a comma placed after the item. For example, mySingleTuple = (1,)
creates a tuple containing only the value 1
.
The tuple's contents appear.
Type the following statement, which displays the first item in the tuple, and press :
print(offices[0])
The first item appears.
Type the following statement, which uses the len()
function to return the number of items in the tuple, and press :
print(len(offices))
The number of items, 5
, appears.
Type the following statement, which displays the number of instances of the item "Chicago"
in the tuple, and then press :
print(offices.count("Chicago"))
The number of instances of "Chicago"
, 2
, appears.
Type the following statement, which uses the del
command to delete the tuple, and then press :
del offices
To verify that the tuple is gone, type the following print
command, and then press :
print(offices)
Python returns an error because the tuple no longer exists.
Work with Sets
Python’s set data type enables you to store multiple values in a single variable. A set is a collection of objects, usually called elements or members. Each element must be unique in the set, without duplicates, unlike in a tuple, which can have duplicates. Also unlike a tuple, a set is unordered — that is, it has no specific order. A set is immutable: After creating a set, you cannot change its existing items, but you can add further items as needed. In this example, you use a set to remove duplicate values from a tuple.
Work with Sets
In Visual Studio Code, create a new script, and then save it.
For example, press + , click Select a Language, and then click Python. Press + , specify the filename and location, and then click Save.
Type the following statement to create a variable named mySet
and assign an empty set to it:
mySet = set()
Press , and then type the following statement to create a variable named myTuple
and assign to it various numbers, including duplicates:
myTuple = (1,1,1,1,1,2,2,2,2,3,
3,3,3,4,4,4,4,5,5,5,6,6,7)
Press , and then type the following statement, which uses the update
method to add the unique values from myTuple
to mySet
:
mySet.update(myTuple)
Press , and then type the following statement, which displays the text myTuple:
, a space, and a string containing the contents of myTuple
:
print("myTuple: " + str(myTuple))
Press , and then type the following statement, which displays a blank line in the output:
print()
Press , and then type the following statement, which displays the text mySet:
, a space, and a string containing the contents of mySet
:
print("mySet: " + str(mySet))
Note: The print()
statements for myTuple
and mySet
use the str()
function to cast the contents of myTuple
and mySet
to strings because the first item printed is a string. Using print("mySet: " + mySet)
causes an error from trying to concatenate a string and a set.
Click Run Python File in Terminal ().
Visual Studio Code runs the script.
The contents of myTuple
appear.
The contents of mySet
appear.
You can see that mySet
contains only the unique elements from myTuple
— all the duplicates are gone.
Start Working with Strings
To store and manipulate text in your scripts, you use strings. In Python, a string is an immutable sequence of characters, so once you have assigned a string to a value, you cannot change it. A string value has the str
data type, and you can use the str()
function to convert various other data types to strings.
Chapter 9, “Working with Text,” shows you how to take widely useful actions with strings. This section provides an introduction to strings. In it, you create and manipulate strings using a terminal window.
Start Working with Strings
Open a terminal window and launch Python.
The Python prompt appears.
Type the following statement, which creates a variable named str1
and assigns text to it, and then press :
str1 = "Industry"
Type the following statement, and then press , to display str1
:
print(str1)
The string appears.
Type the following statement, and then press , to create a second string:
str2 = "Assessment"
Type the following statement, and then press , to display str2
:
print(str2)
The string appears.
Type the following statement, which uses the +
operator to concatenate, or join, str1
and str2
, adding a space between them and assigning the result to str1
. Again, press .
str1 = str1 + " " + str2
Type the following statement, and then press , to display str1
:
print(str1)
The string appears.
Type the following statement, which uses the find
method to locate the position of the space in str1
, assigning the result to a variable called intSplit
. Press .
intSplit = str1.find(" ")
Type the following statement, and then press , to display the value of intSplit
:
print(intSplit)
The value appears.
Type the following statement, and then press , to create a variable named strWord1
and assign to it the leftmost characters in str1
, up to the space:
strWord1 = str1[0:intSplit]
Type the following statement, and then press , to display the string in strWord1
:
print(strWord1)
The string appears.
Start Working with Lists
A list is a variable that enables you to store multiple items of the same type or of different types. The list contains an index that enables you to set or retrieve the individual items. Technically, a list is a mutable sequence, so you can change the order of its items, add and remove items, sort the items, and so on.
Chapter 11, “Working with Lists and Dictionaries,” shows you how to work with lists. This section gives you a preview in which you create a list, add items to it, and return items from it.
Start Working with Lists
In Visual Studio Code, create a new script, and then save it.
For example, press + , click Select a Language, and then click Python. Press + , specify the filename and location, and then click Save.
Type the following statement, which creates a variable called names
and then assigns a list of four names to it:
names = ["Anna", "Bill", "Carly", "Dennis"]
Type the following statement, which displays the first item in the list:
print(names[0])
Click Run Python File in Terminal ().
The Terminal pane opens.
The first list item appears. See the tip for information about the numbering.
Click Kill Terminal ().
Visual Studio Code closes the Terminal pane.
Select the print(names[0])
statement and type the following statement over it, using the append
method to add an item to the names
list:
names.append("Frank")
Press and type the following statement, which displays the fifth item in the list:
print(names[4])
Click Run Python File in Terminal ().
The Terminal pane opens.
The fifth list item appears.
Click Kill Terminal ().
Visual Studio Code closes the Terminal pane.
Click at the end of line 2 and press to start a new line, moving the print(names[4])
line down from line 3 to line 4.
On the empty line 3, type the following statement, which uses the insert
method to insert an item at position 4
in the list:
names.insert(4, "Emily")
Click at the end of line 4 and press to start a new line.
Type the following statement, which uses the remove
method to remove the name Bill
from the list:
names.remove("Bill")
Finally, press and type another print(names[4])
statement:
print(names[4])
Click Run Python File in Terminal ().
The Terminal pane opens.
The first print
statement displays the fifth name, Emily
.
The second print
statement displays the fifth name after removing the Bill
item, Frank
.
Start Working with Dictionaries
In Python, a dictionary is a kind of super-list that allows you to assign collections of information to names called keys. You use a key to set, modify, or retrieve the associated collection of information.
Chapter 11, “Working with Lists and Dictionaries,” shows you how to work with dictionaries. This section gives you an introduction to dictionaries. Here, you create a dictionary that contains information about the dishes offered by a restaurant. The dishes fall into three categories: Starters, Main Courses, and Desserts. You then display the category of dishes you want to see.
Start Working with Dictionaries
In Visual Studio Code, create a new script, and then save it.
For example, press + , click Select a Language, and then click Python. Press + , specify the filename and location, and then click Save.
Type the following statement, which declares a dictionary named dishes
:
dishes = {}
Press and type the following statements, which add the category called Starters
and assign three items and their prices to it:
dishes["Starters"] = {
"Garlic Bread" : "$3.00",
"Spring Rolls" : "$4.50",
"Soup of the Day" : "$2.50"
}
Press and type the following statements, which add the category called Main Courses
and assign three items and their prices to it:
dishes["Main Courses"] = {
"Pizza" : "$7.50",
"Lasagne" : "$10.00",
"Bolognese" : "$5.50"
}
Press and type the following statements, which add the Desserts
category, again with three priced items:
dishes["Desserts"] = {
"Mousse" : "$4.00",
"Lemon Sorbet" : "$3.50",
"Ice Cream" : "$2.75"
}
Press and type the following statement, which displays the word Starters
and a colon:
print("Starters:")
Press and type the following statements, which use a for
loop to list each dish in the Starters
category:
for item in dishes["Starters"]:
print(" " + item + ":", dishes["Starters"][item])
Note: A for
loop is a loop that repeats once for each item in a collection — in this case, once for each item in the Starters
collection in the dishes
dictionary. Chapter 7, “Repeating Actions with Loops,” explains for
loops in detail.
Run the Script
Click Run Python File in Terminal ().
The Terminal pane opens.
The list of starters appears.
Convert Data from One Type to Another
In your Python programming, you will often need to convert data from one data type to another so that you can use it the way you want. Python converts some data automatically and provides functions for converting data manually. For example, you can use the str()
function to convert data to a string, use the int()
function to convert numeric data to an integer, or use the float()
function to convert numeric data to a float, as you have seen so far in this chapter.
This section summarizes the data-conversion functions Python provides and shows examples of using them.
Understanding Implicit Conversion and Explicit Conversion
Python performs two types of data conversion: implicit conversion and explicit conversion.
Implicit conversion occurs when Python automatically converts an existing value to a different data type to avoid losing data. For example, if you create a variable named intTest
and assign the integer value 1
, Python gives the value the int
data type. But if you add a float, such as 3.19
, to intTest
, Python changes the value’s data type to float
so as not to lose the data that could not be stored in the int
data type.
Explicit conversion occurs when you use a data-conversion function to convert data to a different type, as explained in this section. Explicit data conversion is also called type casting or simply casting. For example, you might cast an integer to a float.
Understanding What Kinds of Data You Can Convert
Python’s data-conversion functions are effective and easy to use, but they work only with suitable data. For example, if the variable strQuantity
contains the string data "20"
— including the double quotes, which delimit the string — you can use int(strQuantity)
to convert the string "20"
to the integer 20
. But if strQuantity
contains "Twenty"
, using int(strQuantity)
returns an error.
Meet Python’s Functions for Converting Data
Table 3-1 summarizes the functions that Python provides for converting data from one data type to another. You will notice that each function shares the name of the data type to which it converts data. For example, the bool()
function converts data to the bool
data type, the int()
function converts data to the int
data type, and the tuple()
function converts data to the tuple
data type.
Table 3-1 Python’s Functions for Converting Data
Function |
Converts |
To |
---|---|---|
|
Any data type |
A Boolean value, |
|
An integer |
The corresponding ASCII character |
|
A real number and an imaginary number |
A complex number |
|
Key/value pairs |
A dictionary |
|
Any data type |
A float |
|
An integer |
A hexadecimal string |
|
Any data type |
An integer |
|
A sequence, collection, or iterator object |
A list |
|
An integer |
An octal string |
|
A character |
The corresponding ASCII or Unicode code value |
|
A sequence, collection, or iterator object |
A set |
|
Any data type |
A string |
|
A sequence, collection, or iterator object |
A tuple |
Examples of Using Python’s Data-Conversion Functions
Here are brief examples of using Python’s data-conversion functions:
chr(76)
returns L
, the ASCII character represented by 76
; ord("L")
returns 76
, the ASCII character number.bool(1>2)
returns False
, because 1
is not greater than 2
.complex(4,7)
returns the complex number 4 + 7j
.dict_Subjects = {1: "History", 2: "Geography", 3: "Math"}
returns a dictionary with three subjects identified by integer keys.float(1 + 1.111)
returns a float containing 2.111
, rounded.hex(64000)
returns 0xfa00
, the hexadecimal value for 64000
.int(47.2536)
returns the integer 47
.list(("death","sickness","taxes"))
returns a list containing those three cheerless nouns.oct(64)
returns 0o100
, the octal value for 64
.set(myTuple)
returns a set containing the unique values from the myTuple
collection.str(45 + 99)
returns a string containing 144
.tuple(("shoes", "boots", "waders", "sandals"))
returns a tuple containing ill-assorted footwear.3.141.47.163