0% found this document useful (0 votes)
137 views17 pages

Data Types, Numbers and Characters

IS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views17 pages

Data Types, Numbers and Characters

IS
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

5/22/2024

Module Objectives (3 of 4)

• 3.3 Assignment Statements


• 3.3.1 Differentiate between undefined and defined variables.
• 3.3.2 Identify statements that declare variables.
• 3.3.3 Identify statements that initialize variables.
• 3.3.4 Explain how Python uses dynamic typing and determines data types.
Programming with Python • 3.3.5 Explain the meaning of type inference.
• 3.3.6 Explain the concept of a null variable.
• 3.3.7 Identify assignment statements that change the value of a variable.
Module 3: Literals, Variables, • 3.3.8 Differentiate declaring, initializing, and assigning variables.
and Constants

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Module Objectives (1 of 4) Module Objectives (4 of 4)

• 3.1 Literals • 3.4 Input and Output


• 3.1.1 Define the term “literal” in the context of programming. • 3.4.1 State the algorithm for collecting input from a user and placing it in a variable.
• 3.1.2 Identify numeric literals. • 3.4.2 Transform the user input algorithm into pseudocode.
• 3.1.3 Provide examples of integer literals and floating-point literals. • 3.4.3 Trace the pseudocode that outputs the value of a variable that is input by a user.
• 3.1.4 Identify character and string literals.
• 3.1.5 Provide use cases for string literals that look like numbers.
• 3.1.6 Identify Boolean literals.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Module Objectives (2 of 4) 3.1 Literals (1 of 5)

• 3.2 Variables and Constants • Numeric literals


• 3.2.1 List the characteristics of a program variable. • Literal: any element of data specified for a program
• 3.2.2 Create descriptive variable names using appropriate style conventions. • Numeric literal: one or more digits that can represent integers or floating-point numbers
• 3.2.3 Describe the purpose of a constant. containing a decimal point
• 3.2.4 Use standard naming conventions for constants.
• Sample numeric literals:
• 3.2.5 Explain the difference between a variable, a constant, and a literal.
dwarf_rings = 7
• 3.2.6 Explain the relationship between variables and memory. 1
ring_thickness = 2.7

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

1
5/22/2024

3.1 Literals (2 of 5) 3.1 Literals (5 of 5)

• Tricky literals
• Literals containing number characters can be either numbers or strings
• When working with numerals in a context where they are not manipulated
mathematically, you can enclose them in double or single quotes to designate them
as strings
• Example use cases: area codes, PINs, Social Security numbers
• Boolean literal: a literal with a value of either True or False that is not a string, and
Figure 3-2 Common numeric literals thus not enclosed in quote marks
• Example use case: setting a fact as true

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.1 Literals (3 of 5) 3.2 Variables and Constants (1 of 8)

• Character and string literals • Variables


• Character literal: a single letter or symbol • Variable: a named memory location that temporarily holds text or a numeric value
• Sample character literals: • Variables have three important characteristics:
'a' • A name
'@'
• A corresponding memory location where data can be stored
• Changeable (mutable) data
• String literal: value containing one or more characters; typically denoted with double
quotes
• Sample string literals:
"Mordor"
"Three rings for the elven kings..."
"bilbo@theshire.com"

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.1 Literals (4 of 5) 3.2 Variables and Constants (2 of 8)

Figure 3-3 Character literals and string Figure 3-4 A variable is a named
literals memory location that temporarily holds
data

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

2
5/22/2024

3.2 Variables and Constants (3 of 8) 3.2 Variables and Constants (6 of 8)

• Variables (continued) • Constants


• General variable naming conventions • Constant: a named memory location that holds data, which is used but not changed by
• In Python, you cannot use the name of one of the language's built-in functions, the statements in a program
such as print • Important characteristics of constants:
• Names should be descriptive • A name
• Python variable names must start with a letter or an underscore • A corresponding memory location where data can be stored
• Two most prevalent conventions for combining words for variable names: • Data that is not meant to be changed
• Camel case begins with a lowercase letter, but each subsequent word is capitalized • General constant naming conventions:
• Snake case uses all lowercase and separates words with an underscore • Should be descriptive
• Python typically uses camel case for variable names • Python convention is to name constants in all uppercase text with an underscore
separating words

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.2 Variables and Constants (4 of 8) 3.2 Variables and Constants (7 of 8)

• Constants (continued)
Snake case Camel case • Sample Python constants:
MINUTES_IN_HOUR = 60
elven_rings elvenRings MAXIMUM_USERS = 1024
made_in_mordor madeInMordor OHIO_ABBREVIATION = "OH"
hobbit hobbit
multiples_of_2 multiplesOf2
• Using constants for formulas facilitates easier code changes/maintenance
• The memory connection
• Both variables and constants correspond to memory locations where data can be stored
• These memory locations have unique addresses, expressed in binary or hex numbers
• When you specify the name for a variable or constant, your programming language ties it
to a memory location (the address) where you can put data

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.2 Variables and Constants (5 of 8) 3.2 Variables and Constants (8 of 8)

Figure 3-6 A constant is a named


memory location that holds data that
does not change

Figure 3-7 Variable names correspond


to memory locations

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3
5/22/2024

Activity 3.1: Knowledge Check 3.3 Assignment Statements (2 of 3)

1. One example of a(n) _____ is "Thomas". • Initializing variables (continued)


• In a dynamically typed language, a variable can repeatedly be reassigned to a value of a
2. True or False: The statement healthyBreakfast = True sets a variable of the string different data type (e.g., changed from an integer to a string)
type. • Statically typed: describes a programming language that requires you to store only one
type of data in a variable
3. For a programming language using the camel case convention, a variable to represent • Roles of initialization in programming
"current balance" would be named _____. • Specifying starting values when known
• Specifying the initial value of a repetition counter (typically 0 or 1)
4. A(n) _____ is a named memory location that holds a data value that a program will use but • Creating a null variable (one that has no value), which is assigned to the keyword
not alter. None in Python

5. Three key characteristics of _____ are that they have names, have corresponding memory
locations, and contain changeable data.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Activity 3.1: Knowledge Check Answers Activity 3.2: Breakout Groups:


Assignment Statement Practice
1. One example of a(n) _____ is "Thomas". 1. Form small groups.
Answer: string literal
2. Choose a simple task that you might want to write a program to accomplish (e.g., calculate
2. True or False: The statement healthyBreakfast = True sets a variable of the string the sales tax on a purchase).
type.
3. Sketch out an algorithm for this task, identify any variables and constants that the program
Answer: False
would need to use, and write appropriate Python statements to initialize them.
3. For a programming language using the camel case convention, a variable to represent
"current balance" would be named _____.
Answer: currentBalance
4. A(n) _____ is a named memory location that holds a data value that a program will use but
not alter.
Answer: constant
5. Three key characteristics of _____ are that they have names, have corresponding memory
locations, and contain changeable data.
Answer: variables

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.3 Assignment Statements (1 of 3) 3.3 Assignment Statements (3 of 3)

• Declaring variables • Assigning variables


• Using an undefined variable produces a runtime error, so it is essential to define the • An assignment statement sets or changes the value that is stored in a variable
variables used in programs • Sample Python assignment statements demonstrating the general syntax:
• To declare a variable means specifying a name that is assigned, or bound, to a memory • Setting a numeric value: dwarf_rings = 7 – 1
location • Changing a numeric value: dwarf_rings = dwarf_rings – 1
• Python requires you to assign a value to all variables with an initialization statement while • Setting a numeric value: total_rings = 3 + 7 + 9 + 1
declaring them
• Setting a string value: ring_location = "Anduin River"
• Initializing variables • Changing a string value: ring_location = "Bilbo's pocket"
• To initialize a variable means specifying a name and a value
• Roles of variables in programs:
• Dynamically typed: describes a programming language (such as Python) that allows a
• Store literals that your programs use as input, manipulations, and output
variable to take on any type of data during program execution
• Hold intermediate data during multistep calculations
• Type inference: process in which a language deduces the data type based on the
presence or absence of a decimal point and quote marks • Act as repetition counters
• Can be used as the basis for sections of an algorithm that hinge on decisions

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4
5/22/2024

Activity 3.3: Discussion Activity 3.4: Breakout Groups:


Extending the Trivia Game
1. How would you explain the concepts of literals, variables, and constants and the 1. Form small groups.
relationships among them to a curious person who is not a software developer? Draw a
2. Plan your own simple trivia game similar to that featured in Section 3.4 of the module.
diagram (or describe a diagram you might draw) to clarify your explanation.
3. Describe what other steps you would need to add to your program’s algorithm to make it
function as you would expect.
2. Write Python assignment statements for the following variables/constants, using
appropriate naming conventions: deposit amount of $330, fixed interest rate of 5%, 4. Write pseudocode for your trivia game using the pattern shown in Figures 3-10 and 3-12.
acceleration due to gravity of 9.8 meters per second per second, and mass of an object of
12 kilograms.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.4 Input and Output (1 of 2) Activity 3.5: Knowledge Check

• Input to a variable 1. True or False: Runtime errors can be caused by a program's attempt to use an undefined
• To collect data from a user, you typically: variable.
• Initialize a variable to hold the user's input
• Supply a prompt that explains what you want the user to enter 2. To _____ a variable means to specify both its name and its value.
• Collect the data entered by the user in the initialized variable
• Python allows you to include an initialization, a display, and an input instruction on the 3. Because Python is a _____ language, you can initialize a variable with a value of one data
same line type, then use an assignment statement to store a value of a different data type in that
same variable.
• Output from a variable
• When variables are sent as output to a display or printer, the output is the value of the
4. In a Python program, you can collect input from a user in a variable called
variable, not the variable name
favoriteColor with the statement favoriteColor = _____ ("What is your
• E.g., if dwarf_rings is assigned the value 5, then when the statement print("Is", favorite color? ").
dwarf_rings, "your final answer?") executes, the text displayed is: Is 5
your final answer?

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

3.4 Input and Output (2 of 2) Activity 3.5: Knowledge Check Answers

1. True or False: Runtime errors can be caused by a program's attempt to use an undefined
variable.
Answer: True
2. To _____ a variable means to specify both its name and its value.
Answer: initialize
3. Because Python is a _____ language, you can initialize a variable with a value of one data
type, then use an assignment statement to store a value of a different data type in that
same variable.
Answer: dynamically typed
4. In a Python program, you can collect input from a user in a variable called
Figure 3-11 Loading a variable with
favoriteColor with the statement favoriteColor = _____ ("What is your
data entered by a user
favorite color? ").
Answer: input

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5
5/22/2024

Self-Assessment Module Objectives (1 of 3)

1. Do you expect to find making a distinction between constants and other variables useful as • 4.1 Primitive Data Types
you write programs? Why or why not? • 4.1.1 Define the term “data type.”
• 4.1.2 List four common primitive data types.
2. Module 3 presents a basic algorithm for collecting input from a program's user. Briefly • 4.1.3 Explain the purpose of primitive data types.
describe a program of interest to you that would require input from the user, and critique
• 4.1.4 Distinguish between primitive data types and composite data types.
this algorithm based on how you imagine using user-supplied input in that program.
• 4.2 Numeric Data Types
• 4.2.1 List the characteristics of integer data.
• 4.2.2 Provide examples of integer data that might be incorporated in a computer
program.
• 4.2.3 Explain the difference between a signed and an unsigned integer.
• 4.2.4 State the memory requirements for signed and unsigned integers.
• 4.2.5 List the characteristics of floating-point data.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Summary Module Objectives (2 of 3)

Click the link to review the objectives for this presentation. • 4.2 Numeric Data Types (continued)
Link to Objectives • 4.2.6 Provide examples of floating-point data that might be incorporated in a computer
program.
• 4.2.7 Recall that floating-point data is not stored in conventional binary format.
• 4.2.8 Compare and contrast the use of integer data with floating-point data.
• 4.3 Mathematical Expressions
• 4.3.1 List the symbols used for the following mathematical operations: addition,
subtraction, multiplication, division, exponentiation, and modulo division.
• 4.3.2 Provide examples of program statements in which the result of a mathematical
operation is stored in a variable.
• 4.3.3 Describe the mathematical order of operations.
• 4.3.4 Provide examples illustrating the use of parentheses to change the order of
operations.
• 4.3.5 Explain the use of compound operators such as += -= *= /= and %=.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Module Objectives (3 of 3)

• 4.4 Numeric Data Type Conversion


• 4.4.1 Provide examples of when a programmer might convert integer or floating-point
data to a different data type.
• 4.4.2 Explain the disadvantage of converting floating-point data to integer data.
• 4.4.3 Explain the significance of rounding for floating-point calculations.
Programming with Python • 4.5 Formatting Output
• 4.5.1 Explain the advantage of formatting output.
• 4.5.2 List the elements that can be specified when formatting numeric output.
Module 4: Numeric Data Types • 4.5.3 Use formatting parameters to specify the output format of numeric data.
and Expressions

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

6
5/22/2024

4.1 Primitive Data Types (1 of 3) Activity 4.1: Breakout Groups:


Primitive Data Types “20 Guesses” Game
• Data types 1. Work in pairs or small groups.
• Data type: a way of categorizing data
• Primitive data types 2. One person should choose a primitive data type from Figure 4-2, and then the other(s) can
• Primitive data types are built into a programming language ask “Yes”-or-“No” questions until they correctly guess which data type the first has in mind.
• Programming language knows how to allocate memory for storing these data types
• Programming language knows how to manipulate that type of data
3. Swap roles and repeat the game. Who in the class can guess correctly after the fewest
• Function: a named procedure that performs a specific task, such as manipulating number of questions?
data

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4.1 Primitive Data Types (2 of 3) 4.2 Numeric Data Types (1 of 4)

Primitive Data Type Python Code Description Examples


• Integer data types
• Whole numbers are classified as integer data types
Integer var = 5 Whole number without any 1
decimal places 128 • Must be whole numbers without decimal places or fractions
3,056 • Can be positive or negative
-2 • Unsigned integers don't have a plus or minus symbol and are assumed to be
Floating point var = 5.0 Number that includes decimal 12.99 positive
places 0.26 • Signed integers begin with a plus or minus symbol
-3.56 • Can be a decimal, binary, or hexadecimal number
Boolean var = False Logical value of True or False True • Examples:
False
• 23 is an unsigned integer
Valueless var = None No value No real-world equivalent • -40 is a negative signed integer
examples
• 0b00000101 is an unsigned integer (binary 5)
Figure 4-2 Primitive data types • 0x6C is an unsigned integer (hexadecimal 108)

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4.1 Primitive Data Types (3 of 3) 4.2 Numeric Data Types (2 of 4)

• Composite data types


• Composite data types are not built into programming language, but can be constructed
from primitive data types
• Programmer defined or available in add-on libraries of program code

Figure 4-4 Integer storage allocation

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

7
5/22/2024

4.2 Numeric Data Types (3 of 4) Activity 4.2: Knowledge Check Answers

• Floating-point data types 1. Python knows how to allocate memory for and manipulate _____ data types.
• Numbers with decimal places (i.e., a decimal point and values to the right of it) are Answer: primitive
classified as floating-point data types
• Can be positive or negative 2. True or False: Add-on libraries of program code are often sources of useful primitive data types.
• Can be expressed in decimal notation or E notation
Answer: False
• Examples:
• 19.99 is an unsigned floating-point number 3. Floating-point numbers are stored in either 4 or 8 bytes of memory in _____, which resembles
• -4.5967E2 is a signed floating-point number in E notation scientific notation.
• Single precision: refers to four-byte floating-point numbers Answer: E notation
• Double precision: refers to eight-byte floating-point numbers
• All floating-point numbers in Python are double precision, inferred from the decimal 4. True or False: The most appropriate data type for variables that hold values representing
point in the assignment statement, e.g., price = 5.99 money and that will be used in financial transaction calculations is the integer type.
Answer: False

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4.2 Numeric Data Types (4 of 4) 4.3 Mathematical Expressions (1 of 5)

• Arithmetic operators
• Expression: a programming statement that has a value and usually includes one or
more arithmetic operators and one or more operands
• Python arithmetic operators include + (addition), - (subtraction), * (multiplication), /
(division), // (integer division), and % (modulo division)
• Sample statement that stores the result of a calculation in a variable:
discount_price = album_price – 2.99
• Remember that:
• When integer division (with //) produces a fractional part, it may not be included in
the result
Figure 4-6 Floating-point storage
• Modulo division (with %) produces the remainder of a division operation
allocation

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Activity 4.2: Knowledge Check 4.3 Mathematical Expressions (2 of 5)

1. Python knows how to allocate memory for and manipulate _____ data types.

2. True or False: Add-on libraries of program code are often sources of useful primitive data types.

3. Floating-point numbers are stored in either 4 or 8 bytes of memory in _____, which resembles Figure 4-8 Checking whether a number
scientific notation. is even or odd

4. True or False: The most appropriate data type for variables that hold values representing
money and that will be used in financial transaction calculations is the integer type.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

8
5/22/2024

4.3 Mathematical Expressions (3 of 5) Activity 4.3: Knowledge Check Answers

• Order of operations 1. A programming statement with a value that includes one or more arithmetic operators and
• The order of operations specifies the sequence in which to perform arithmetic one or more operands is a(n) _____.
operations
Answer: expression
• Do the math in parentheses first
• Carry out exponentiation and roots
2. True or False: The expression 10 - 8 / 2 * 4 + 5 has the value -1.
• Perform multiplication, floating-point division, integer division, and modulo division
from left to right
Answer: True
• Execute addition and subtraction from left to right
• Parentheses can be added around the operation you wish to perform first to alter the
order of operations

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4.3 Mathematical Expressions (4 of 5) 4.3 Mathematical Expressions (5 of 5)

• Compound operators
• Compound operators provide handy shortcuts for some common arithmetic operations
• Sample Python expressions using compound operators (counter is initialized to 10):
• counter += 1 # Result is 11
• counter -= 1 # Result is 9
• counter *= 2 # Result is 20
Figure 4-9 Changing the order of • counter /= 2 # Result is 5
operations • counter %= 2 # Result is 0

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Activity 4.3: Knowledge Check Activity 4.4: Breakout Groups:


Mathematical Expressions Practice
1. A programming statement with a value that includes one or more arithmetic operators and 1. Form pairs or small groups of students.
one or more operands is a(n) _____.
2. To gain experience writing Python code to store various calculations (expressions) in
variables, practice translating parts of some common algebraic formulas into Python.

2. True or False: The expression 10 - 8 / 2 * 4 + 5 has the value -1.


3. To identify some common formulas to try, refer to an algebra text or an online reference
(e.g., review Algebraic Formula Sheet (web pdf), or search for “common algebraic
formulas” using a search engine) if necessary.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

9
5/22/2024

4.4 Numeric Data Type Conversion (1 of 3) 4.5 Formatting Output (1 of 4)

• Convert integers and floating-point numbers • Formatted output


• Sometimes mathematical expressions contain different data types, such as an integer • Converting floating-point data to integers risks significant data loss
and a floating-point number • You can format output to eliminate trailing zeros or decimal places without changing the
• Coercion automatically decides which data type to use for a calculation actual data in a variable
• Doesn't change the data type of the variable • E.g., the value 4.43050 can be displayed as 4, 4.4, 4.305000, or 4.431 while storing
• Python always uses coercion during normal division with the / symbol the original value of 4.43050 in a variable
• Type casting is the process of manually converting a value to a different data type • Formatting parameters
• Python's int() function converts a floating-point value into an integer • Python's unique syntax allows you to control several formatting parameters
• The int() function simply truncates the number—it doesn't round it • Type: integer, floating point, decimal, binary, hexadecimal, character, or E notation
• Python's float() function converts numbers to floating point • Precision: places displayed after the decimal point
• Width: number of spaces allocated to the output (e.g., for outputting table columns)
• Alignment: left or right within a specified width

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4.4 Numeric Data Type Conversion (2 of 3) 4.5 Formatting Output (2 of 4)

• Formatting parameters (continued)


• Syntax for the Python format() method
• Sample statement:
"Your lucky numbers are {:d} and {:d}.".format(42, 7.3)
• Data inside parentheses in format() method are placed in the empty spots
represented by the pairs of curly braces
• Formatting parameters are inserted inside the curly braces
Figure 4-13 Converting a floating-point
• Formatting parameters can be used in combination
number to an integer

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

4.4 Numeric Data Type Conversion (3 of 3) 4.5 Formatting Output (3 of 4)

• Rounding quirks
Parameter Letter or Symbol Example Code Output
• Programming languages have some quirks when it comes to numeric data
Type d for decimal integers "{:d}".format(100) 100
• E.g., dividing 1 // 2 using Python's integer division operator results in the value 0 f for floating-point "{:f}".format(15.3) 15.300000
• Odd results may stem from a rounding quirk related to the computer’s reliance on binary
Precision Decimal point followed by the "{:.3}".format(15.3) 15.3
numbers
precision; only works for float
• Binary representation of a floating-point number is an approximation because binary numbers
numbers don’t yield the same fractions as decimals
Width A number representing the "{:10}".format(2) _________2
• Math functions can be used to truncate or round numbers number of characters for the total
width
Left-aligned < "{:<10}".format(2) 2_________
Centered ^ "{:^10}".format(2) ____2_____
Right-aligned > "{:>10}".format(2) _________2

Figure 4-16 Formatting parameters

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

10
5/22/2024

4.5 Formatting Output (4 of 4) Activity 4.6: Discussion

1. Imagine you are examining two Python programs: one for building (with ingredient choices)
and purchasing a sub-shop sandwich and another for processing data on planets and other
celestial objects. What integer and floating-point data type variables might be used in these
programs?

2. Compare type casting with using formatting parameters. Name some coding situations
where each should be preferred and explain why.
Figure 4-17 Formatting
numeric output

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Activity 4.5: Knowledge Check Self-Assessment

1. A programmer who writes code that performs calculations combining variables with different numeric data 1. What is your attitude toward writing mathematical expressions for your programs—that is,
types without including code to make these types consistent is relying on _____.
do you find it interesting, challenging, enjoyable, a chore, et cetera? Would you like, or are
you planning, to strengthen your skills in this area to improve your school or work
performance?
2. True or False: Because computers rely on binary numbers, which yield different fractions from decimal
numbers during calculations, the results of expressions using floating-point numbers may be different than
expected.
2. Critique Python's approach to formatting numbers that appear in string output. If you are
familiar with similar functions in another programming language, how do they compare?
3. True or False: The best way to display the results of calculations without trailing zeros or with a reduced
number of decimal places is to type cast them to integers.

4. To format a number in Python, you use the _____, which is applied to a series of letters inside double
quotes with empty spots represented by pairs of curly braces.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Activity 4.5: Knowledge Check Answers Summary

1. A programmer who writes code that performs calculations combining variables with different numeric data Click the link to review the objectives for this presentation.
types without including code to make these types consistent is relying on _____.
Answer: coercion Link to Objectives

2. True or False: Because computers rely on binary numbers, which yield different fractions from decimal
numbers during calculations, the results of expressions using floating-point numbers may be different than
expected.
Answer: True

3. True or False: The best way to display the results of calculations without trailing zeros or with a reduced
number of decimal places is to type cast them to integers.
Answer: False

4. To format a number in Python, you use the _____, which is applied to a series of letters inside double
quotes with empty spots represented by pairs of curly braces.
Answer: format() method

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

11
5/22/2024

Module Objectives (3 of 3)

• 5.4 Concatenation and Typecasting


• 5.4.1 Explain the meaning of concatenation, and identify the concatenation operator.
• 5.4.2 Provide an example of when a programmer would concatenate a string.
• 5.4.3 Concatenate a string during output.
• 5.4.4 Concatenate the contents of multiple variables.
Programming with Python • 5.4.5 State which data types can be successfully concatenated.
• 5.4.6 Explain the meanings of coercion and typecasting in the context of data types.

Module 5: Character and


String Data Types

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Module Objectives (1 of 3) 5.1 Characters (1 of 7)

• 5.1 Characters • Working with character data


• 5.1.1 List the variety of data that is classified as a character. • Character: classification used for variables that hold a single letter of the alphabet, a
• 5.1.2 Initialize data as a character. numeral from 0 to 9, or a symbol
• 5.1.3 Describe the punctuation conventions used for character data. • Sample assignment of a character literal to a variable:
first_letter = "a"
• 5.1.4 State the storage required for ASCII character data.
• 5.1.5 Explain the difference between numbers and digits.
• 5.1.6 Format character output separated by spaces or on separate lines.
• 5.1.7 List some common functions or methods available for manipulating character data.
• 5.2 String Data Type
• 5.2.1 Explain that characters combine to form strings.
• 5.2.2 State that Python characters are strings of length 1.
• 5.2.3 Describe the punctuation conventions used for string literals.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Module Objectives (2 of 3) 5.1 Characters (2 of 7)

• 5.2 String Data Type (continued)


• 5.2.4 Specify when an escape sequence is necessary.
• 5.2.5 Describe the memory allocation for strings.
• 5.2.6 Identify the index values for characters in a string.
• 5.3 String Functions
• 5.3.1 List commonly used functions and methods that programming languages provide to
manipulate strings. Figure 5-2 Character
• 5.3.2 Identify code that produces the length of a string. data initialization and
• 5.3.3 Identify code that changes the case of a string. storage
• 5.3.4 Explain the significance of case sensitivity.
• 5.3.5 Provide use cases for finding a character in a string.
• 5.3.6 Explain the general approach to retrieving substrings.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

12
5/22/2024

5.1 Characters (3 of 7) 5.1 Characters (6 of 7)

• Character memory allocation


• ASCII (American Standard Code for Information Interchange): encoding method that
assigns a unique sequence of 8 bits to each character
• Each of the uppercase letters, lowercase letters, numerals, and symbols on your
computer keyboard has a unique ASCII value
• E.g., uppercase A is ASCII code 01000001, lowercase a is 01100001
• Digits
• The double quotes around strings composed of the digits 0 to 9 indicate they are strings,
not integers Figure 5-8
Changing the case
• The 5 in a_digit = "5" is stored as an ASCII value
of a character
• The 5 in an_integer = 5 is stored as a binary number
• Character output format
• Digits can be separated by including white space in the print statement

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.1 Characters (4 of 7) 5.1 Characters (7 of 7)

Character Example Data Result


Function/Method
Check if the character is a initial.isalpha() initial = "a" True
letter of the alphabet choice.isalpha() choice = "2" False
Check if the character is a initial.isdigit() initial = "a" False
digit choice.isdigit() choice = "2" True
Figure 5-6 Inserting a space in the
output stream Change to uppercase initial.upper() initial = "a" A
Change to lowercase initial.lower() initial = "A" a

Figure 5-8 Changing the case of a character

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.1 Characters (5 of 7) 5.2 String Data Type (1 of 3)

• Working with string data


• String: a sequence of alphanumeric characters
• The string data type is used for working with variables containing words, phrases,
sentences, and other text
• Sample code for working with strings:
your_name = "" (initializing an empty string)
message = "likes alphabet soup." (initializing a string variable)
print("What is your name? ") (displaying a prompt)
your_name = input(). (collecting user input)
print(your_name, message). (displaying two strings)

What is your name?


Figure 5-7 Output to separate lines Gaius Julius Caesar
Gaius Julius Caesar likes alphabet soup.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

13
5/22/2024

5.2 String Data Type (2 of 3) Activity 5.1: Knowledge Check Answers

• Escape characters 1. Character data is stored in _____ format.


• An escape sequence embeds a command within a string and begins with a backslash Answer: ASCII (American Standard Code for Information Interchange)
• Escape sequences allow punctuation such as double quotation marks to appear within
text strings without causing errors 2. True or False: If the variable my_three is assigned the value of "3", the method
• Include \" (quotation mark), \\ (backslash), \n (newline), and \t (tab) my_three.isdigit() returns the Boolean True.
• String indexes Answer: True
• Index: a number that indicates a character's position in a string
• The first character in the string is referenced by index 0, the next character is index 1, et 3. To include a double quotation mark, backslash, or blank line within a string, you use a(n) _____.
cetera Answer: escape sequence
• Sample code for returning the value at a given index of a string (output is C):
company_name = "Campbell's" 4. Within the string "apple", the character e is located at index _____.
letter = company_name[0]
print(letter) Answer: 4

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.2 String Data Type (3 of 3) 5.3 String Functions (1 of 5)

• String manipulation
• Common ways to manipulate strings:
• Find the length of a string
• Change the case of a string
• Check if a string contains a specific character
• Retrieve a substring from a longer string
• String length
• Strength length is useful for reversing strings, ensuring they are not too long, et cetera
• Python's len() function returns a string's length as an integer
Figure 5-13 Each character in a string
is stored in a memory location
referenced by an index

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Activity 5.1: Knowledge Check 5.3 String Functions (2 of 5)

1. Character data is stored in _____ format.

2. True or False: If the variable my_three is assigned the value of "3", the method
my_three.isdigit() returns the Boolean True.

3. To include a double quotation mark, backslash, or blank line within a string, you use a(n) _____.

4. Within the string "apple", the character e is located at index _____. Figure 5-15 Finding the length of a
string

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

14
5/22/2024

5.3 String Functions (3 of 5) Activity 5.2: Discussion


Method Description Code Output
count() Returns the number of times a "banana".count("a") 3 1. Examine a list of the 8-bit codes for ASCII characters and their decimal equivalents (e.g., at
specified value occurs in a ASCII Table). How might this assignment of characters to codes affect how computer
string. programs compare or sort characters and strings?
endswith() Returns True if the string ends "alphabet".endswith("bet") True
with the specified value.
find() Returns the first index of the "apple".find("p") 1
specified value or –1 if it can’t
be found.

startswith() Returns True if the string "caterpillar".startswith("cat") True


starts with the specified value.
title() Capitalizes the first letter of "hello world!".title() Hello
each word in the string. World!
Figure 5-16 Some string methods

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.3 String Functions (4 of 5) 5.4 Concatenation and Typecasting (1 of 4)

• Change case • Concatenated output


• Case can be significant when searching and sorting data • Concatenation: the process of chaining two or more values in sequence
• Case sensitivity: the concept that uppercase letters are different from lowercase letters • The + sign is the concatenation operator
• Result of the different ASCII codes for uppercase and lowercase letters • Sample code that concatenates strings:
• The lower() method can be called on two strings prior to comparing them first_name = input("What is your first name? ")
last_name = input("What is your last name? ")
• Find the location of a character print("Hello,", first_name)
• The find() method produces the index position of the first occurrence of the specified print("You are filed as", last_name + ", " + first_name)
character
• Retrieve a substring Hello, Philip
You are filed as Parker, Philip
• Working with substrings is a component of search engines and several text-processing
algorithms • Concatenated variables
• You can concatenate one or more variables and store the combined string in a new
variable

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.3 String Functions (5 of 5) Activity 5.3: Breakout Groups:


Silly Strings
1. Form student pairs or groups.
2. To practice storing strings as variables and concatenating strings, write a Python program
that:
a. Asks the user to input three words of specified parts of speech (e.g., noun, adjective)
and then
b. Outputs them within a silly sentence, as a silly band name, or in some other silly form.
Figure 5-17
Collecting a
substring

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

15
5/22/2024

5.4 Concatenation and Typecasting (2 of 4) Activity 5.4: Knowledge Check

• Coercion and typecasting 1. The Python _____ returns the number of characters in a string stored within a variable that is
passed in to it as a parameter.
• With most programming languages, strings can be concatenated with other strings and
character data, but not with integer or floating-point data
• To fix an integer-string type mismatch, use typecasting to convert the integer to a string
2. The two values you supply when writing a Python statement to retrieve a substring are the
or vice-versa starting index and _____ of the substring.
• You can use the str() and int() functions to perform these typecasting operations

3. To combine the strings in two or more variables together to produce a new string that is either
output or stored in a variable, you use the process of _____.

4. In Python, when the letters variable has the string value of "26", you can use the statement
number = _____(letters) to assign the numeric value of 26 to number.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.4 Concatenation and Typecasting (3 of 4) Activity 5.4: Knowledge Check Answers

1. The Python _____ returns the number of characters in a string stored within a variable that is
passed in to it as a parameter.
Answer: len() function

2. The two values you supply when writing a Python statement to retrieve a substring are the
starting index and _____ of the substring.
Answer: ending index
Figure 5-19 3. To combine the strings in two or more variables together to produce a new string that is either
Typecasting: output or stored in a variable, you use the process of _____.
Integer to string
Answer: concatenation

4. In Python, when the letters variable has the string value of "26", you can use the statement
number = _____(letters) to assign the numeric value of 26 to number.
Answer: int

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

5.4 Concatenation and Typecasting (4 of 4) Activity 5.5: Breakout Groups:


Quick Name Trivia
1. Form pairs or groups of students.
2. To practice working with characters, strings, and type casting, write a Python program that
a. Asks for the user’s name and then
b. Tells the user what letter that name begins with,
c. Tells the user how many letters are in the name, and
d. Tells the user how many letters it would take to write the name five times in a row.
Figure 5-20
Typecasting:
String to integer

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

16
5/22/2024

Activity 5.6: Discussion

1. Imagine you would like to write a program that mixes up either the words in a sentence or
the characters in a single word and returns the mixed-up version. Which string operations
and manipulation techniques described in Module 5 could you use to accomplish this task?

2. Write an algorithm for the program option you chose for the previous question in either
narrative or pseudocode form.

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Self-Assessment

1. How are strings used in some of the computer applications you use regularly? Can you
identify use cases for the string manipulation methods and functions you learned in this
module within that context?

2. Some programming languages have a separate data type just for single characters (strings
of length 1). As a software developer, do you think you would prefer using two separate
data types for characters and strings, or simply using string data as you do in Python?

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

Summary

Click the link to review the objectives for this presentation.


Link to Objectives

McMullen/Matthews/Parsons, Programming with Python, 1st Edition. © 2023 Cengage. All Rights Reserved. May
not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part.

17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy