Module 2. Data Types and Data Structures
Module 2. Data Types and Data Structures
x = 5
print(type(x))
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
A string is a sequence of characters enclosed by matching single (') or double (") quotes. Ex: "Happy
birthday!" and '21' are both strings.
To include a single quote (') in a string, enclose the string with matching double quotes ("). Ex: "Won't this work?" To include a
double quote ("), enclose the string with matching single quotes ('). Ex: 'They said "Try it!", so I did'.
len() function
A common operation on a string object is to get the string length, or the number of characters in the string.
The len() function, when called on a string value, returns the string length.
Concatenation
Concatenation is an operation that combines two or more strings sequentially with the concatenation operator
(+). Ex: "A" + "part" produces the string "Apart".
Exercise 1: Write a program that asks the user to input their first and last name separately.
The program should then output the length of each name. Based on the example input above, the
output would be:
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Operator precedence
When a calculation has multiple operators, each operator is evaluated in order of precedence. Ex: 1 + 2 * 3
is 7 because multiplication takes precedence over addition. However, (1 + 2) * 3 is 9 because parentheses
take precedence over multiplication.
() Parenthesis (1 + 2) * 3 9
** Exponentiation 2 ** 4 16
1. Defines an integer variable named 'int_a' and assigns 'int_a' with the value 10.
2. Defines a floating-point variable named 'float_a' and assigns 'float_a' with the value 10.0.
3. Defines a string variable named 'string_a' and assigns 'string_a' with the string value "10".
4. Prints the value of each of the three variables along with their type.
Exercise 4: Write a Python computer program that:
print(values) Outputs one or more values, each separated by a space, to the user.
If present, prompt is output to the user. The function then reads a line of input from the
input(prompt)
user.
Operator Description
= Assigns (or updates) the value of a variable. In Python, variables begin to exist when
(Assignment) assigned for the first time.
+
Appends the contents of two strings, resulting in a new string.
(Concatenation
+
Adds the values of two numbers
(Addition)
-
Subtracts the value of one number to another
(Subtraction)
*
Multiplies the values of two numbers
(Multiplication)
/
Divides the value of one number by another
(Division)
**
Raises a number to a power. Ex: 3**2 is three squared.
(Exponentiation)
Function Description
#
All text is ignored from the # symbol to the end of the line.
(Comment)
' or “ Strings may be written using either kind of quote. Ex: 'A' and "A" represent the same
(String) string. By convention, this book uses double quotes (") for most strings.
""" Used for documentation, often in multi-line strings, to summarize a program's purpose
(Docstring) or usage.
Exercise 5: Write a program that assigns a variable named number to any integer of your choice.
Ex: number = 74. Then, use this variable to calculate and output the following results:
74 squared is 5476
74 cubed is 405224
One tenth of 74 is 7.4
74 plus 123 is 197
74 minus 456 is -382
74 times 2 is 148
Run the program multiple times, using a different integer each time. Your output should be
mathematically correct for any integer that you choose.
A computer program is a sequence of statements that run one after the other. In Python, many statements
consist of one or more expressions.
Expressions are often a combination of literals, variables, and operators. In the previous example, 3 and 5 are
literals, x is a variable, and * and - are operators.
1. Implicit type conversion
Common operations update a variable such that the variable's data type needs to be changed.
Example: A GPS first assigns distance with 250, an integer. After a wrong turn, the GPS assigns distance with 252.5, a float.
The Python interpreter uses implicit type conversion to automatically convert one data type to another. Once
distance is assigned with 252.5, the interpreter will convert distance from an integer to a float without the
programmer needing to specify the conversion.
Example: A program should read in two values using input() and sum the values. Remember input() reads in values as
strings. A programmer can use explicit type conversion to convert one data type to another.
• int() converts a data type to an integer. Any fractional part is removed. Example: int(5.9) produces 5.
• float() converts a data type to a float. Example: float(2) produces 2.0.
• str() converts a data type to a string. Example: str(3.14) produces "3.14".
Exercise 6: The following program computes the average of three predefined exam grades and prints
the average twice. Improve the program to read the three grades from input and print the average first
as a float, and then as an integer, using explicit type conversion. Ignore any differences that occur due
to rounding.
exam_1 = 93.0
exam_2 = 84.0
exam_3 = 85.5
Input:
87.8
98.2
91.3
Exercise 7: The following program should read in the ounces of water the user drank today and
compute the number of cups drank and the number of cups left to drink based on a daily goal. Assume
a cup contains 8 ounces. Fix the code to calculate cups_drank and cups_left and match the following:
quantity = int(input())
price = float(input())
total = quantity * price
print(total)
quantity is an integer, and price is a float. So, what is the data type of total? For input 3 and 5.0, total is a float, and the
program prints 15.0.
Combining an integer and a float produces a float. A float is by default printed with at least one figure after the
decimal point and has as many figures as needed to represent the value.
Example: Noor's program reads in a number from input and uses the number in a calculation. This results in an error in the
program because the input() function by default stores the number as a string.
Strings and numeric data types are incompatible for addition, subtraction, and division. One of the operands needs to be
explicitly converted depending on the goal of arithmetic or string concatenation.
The * operator also serves as the repetition operator, which accepts a string operand and an integer operand
and repeats the string.
Example:
• round(2.451, 2) = 2.45
• round(2.451) = 2
r = round(a, 2)
Rounding to two decimal places 2.15
print(r)
Rounding to the nearest integer (floating- r = round(a, 0)
2.0
point output) print(r)
Rounding to the nearest integer (integer r = round(a)
2
output) print(r)
r = round(b, 1)
Rounding to one decimal place 5.0
print(r)
If an integer is passed to the round() function, the output is a floating-point equivalent with the given decimal places as
zeros.
Division and modulo
Note: The % operator is traditionally pronounced "mod" (short for "modulo"). Ex: When reading 7 % 4 out loud,
a programmer would say "seven mod four."
Division is useful for converting one unit of measure to another. To convert centimeters to meters, a variable is
divided by 100. Example: 300 centimeters divided by 100 is 3 meters.
Amounts often do not divide evenly as integers. 193 centimeters is 1.93 meters, or 1 meter and 93
centimeters. A program can use floor division and modulo to separate the units:
In this example, the current time is 13:25 (1:25pm). The trip time is 340 minutes (5 hours and 40 minutes).
340 minutes after 13:25 is 19:05 (7:05pm). Your program should output the result in this format:
Arrival hour is 19
Arrival minute is 5
The arrival hour must be between 0 and 23. Ex: Adding 120 minutes to 23:00 should be 1:00, not 25:00. The arrival minute
must be between 0 and 59. Ex: Adding 20 minutes to 8:55 should be 9:15, not 8:75.
Hint: Multiply the current hour by 60 to convert hours to minutes. Then, calculate the arrival time, in total
minutes, as an integer.