0% found this document useful (0 votes)
7 views

Module 2. Data Types and Data Structures

The document provides an overview of Python's built-in data types, including text, numeric, sequence, mapping, set, boolean, binary, and none types. It explains string operations, numeric data types, arithmetic operators, operator precedence, and type conversion, along with several exercises for practical application. Additionally, it covers functions for input/output, rounding, division, and modulo operations, emphasizing the importance of data types in programming.

Uploaded by

Astrid Stavros
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Module 2. Data Types and Data Structures

The document provides an overview of Python's built-in data types, including text, numeric, sequence, mapping, set, boolean, binary, and none types. It explains string operations, numeric data types, arithmetic operators, operator precedence, and type conversion, along with several exercises for practical application. Additionally, it covers functions for input/output, rounding, division, and modulo operations, emphasizing the importance of data types in programming.

Uploaded by

Astrid Stavros
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Python has the following data types built-in by default, in these categories:

Text type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
Example:
Print the data type of the variable x

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.

What is your first name? Alan


What is your last name? Turing

The program should then output the length of each name. Based on the example input above, the
output would be:

Your first name is 4 letters long


Your last name is 6 letters long
Exercise 2: Write a Python computer program that:

• Assigns the string “Jonah” to a variable, name


• Assigns the string "happy" to a variable, feel.
• Prints the string "Hi Jonah!" with a single print() function using the variable name.
• Prints the string "I'm glad you feel happy." with a single print() function using the variable feel.
Numeric data types
Python supports two basic number formats, integer and floating-point. An integer represents a whole number,
and a floating-point format represents a decimal number. The format a language uses to represent data is
called a data type.

In addition to integer and floating-point types, programming languages typically have a


string type for representing text.

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.

Four basic arithmetic operators exist in Python:

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.

Operator Description Example Result

() Parenthesis (1 + 2) * 3 9

** Exponentiation 2 ** 4 16

+, - Positive, Negative -math.pi -3.14159

*, / Multiplication, Division 2*4 8

+, - Addition, Subtraction 1+2 3


Exercise 3: Write a Python computer program that:

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:

1. Assigns the integer value 10 to a variable, meters.


2. Assigns the floating-point value 3.28 to a variable, meter2feet.
3. Calculates 10 meters in feet by multiplying meter by meter2feet. Store the result in a variable, feet.
4. Prints the content of variable feet in the output.
Function Description

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.

len(string) Returns the length (the number of characters) of a string.

type(value) Returns the type (or class) of a value. Ex: type(123) is .

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.

An expression represents a single value to be computed.


Ex: The expression 3 * x - 5 evaluates to 7 when x is 4.

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.

2. Explicit type conversion


A programmer often needs to change data types to perform an operation.

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

average = (exam_1 + exam_2 + exam_3) / 3


print(average)
print(average)

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:

• ounces is an integer representing the ounces the user drank


• cups_drank is a float representing the number of cups of water drank.
• cups_left is an integer representing the number of cups of water left to drink (rounded down) out of
the daily goal of 8 cups.
Exercise 8: The following program reads two integers in as strings. Calculate the product of the two
integers, and print the result as a float.

• ounces is an integer representing the ounces the user drank


• cups_drank is a float representing the number of cups of water drank.
• cups_left is an integer representing the number of cups of water left to drink (rounded down) out of
the daily goal of 8 cups.
Programmers often need to combine numbers of different data types. Ex: A program computes the total for an
online shopping order:

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.

Note: Division using the / operator always produces a float.


Easy type conversion in Python can lead a programmer to assume that any data type can be combined with
another.

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: "banjo" * 3 produces "banjobanjobanjo".


Python's round() function is used to round a floating-point number to a given number of decimal places. The function
requires two arguments. The first argument is the number to be rounded. The second argument decides the number of
decimal places to which the number is rounded. If the second argument is not provided, the number will be rounded to the
closest integer. The round() function can be used to mitigate floating-point errors.

Example:
• round(2.451, 2) = 2.45
• round(2.451) = 2

Examples of a round() function: assuming a = 2.153, b = 5

Operation Python Code Output

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

Python provides two ways to divide numbers:


• True division (/) converts numbers to floats before dividing. Example: 7 / 4 becomes 7.0 / 4.0, resulting in1.75.
• Floor division (//) computes the quotient, or the number of times divided. Ex: 7 // 4 is 1 because 4 goes into 7 one time,
remainder 3. The modulo operator (%) computes the remainder. Ex: 7 % 4 is 3.

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:

• The quotient, 1 meter, is 193 // 100.


• The remainder, 93 centimeters, is 193 % 100.
Programs often use floor division and modulo together. If one line of code floor divides by m, the next line will
likely modulo by m. The unit m by which an amount is divided is called the modulus.

Example: When converting centimeters to meters, the modulus is 100.


Exercise 9: Write a program that inputs the current time and estimated length of trip, (2) calculates the
time of arrival, and (3) output the results in hours and minutes. Your program should use the following
prompts:
Enter the current hour: 13
Enter the current minutes: 25
Trip time (in minutes): 340

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.

You might also like