Python Strings, Input, and Decisions
- 86Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What does an object’s type tell Python?
86 questions
- 1
What does an object’s type tell Python?
Model answer
An object is a value in Python memory, and its type tells Python what operations are allowed for that value.
Explanation
An object’s type determines which operations Python permits on it.
- 2
What is the relationship between a variable name and an object in memory?
Model answer
A variable binds a name to an object in memory, allowing the program to refer to that object by name.
Explanation
A variable is a name bound to an object, rather than a container that necessarily changes the object itself.
- 3
What is an expression in Python?
Model answer
An expression is code Python evaluates to produce a value; it may combine objects with operators or request an operation.
Explanation
Expressions combine objects or request an operation and evaluate to a value.
- 4
How does Python evaluate an expression such as
pi * radius**2whenpiandradiusare variables?Model answer
Python retrieves the values bound to the names, applies the operation according to its rules, and produces a result.
Explanation
When Python evaluates an expression using variable names, it looks up the objects those names refer to before carrying out the operation.
- 5
In an assignment statement, what does Python do first: evaluate the right-hand side or bind the left-hand variable?
Model answer
Python evaluates the right-hand expression first, then binds its resulting value to the variable on the left.
Explanation
Assignment evaluates its right-hand side first and then binds the resulting object to the left-hand name.
- 6
What happens when Python executes
radius = radius + 1?Model answer
Python evaluates
radius + 1using the current value, creates the result, and rebindsradiusto it; the original object is not modified.Explanation
An assignment like
radius = radius + 1is not a mathematical equality; it replaces the name’s binding with a newly evaluated value. - 7
What value is bound to
varinvar = type(5 * 4)?Model answer
5 * 4evaluates to the integer20, andtype(20)evaluates to the typeint, which is bound tovar.Explanation
An expression can evaluate to a type object, which can then be bound to a variable.
- 8
Can a Python variable refer only to numbers? Explain briefly.
Model answer
A variable can be bound to any kind of object, including a type object such as
int.Explanation
Python variables can refer to objects other than numeric values.
- 9
How does evaluating an expression in the interactive shell differ from putting that expression in a Python file?
Model answer
In the shell, Python displays the value of an entered expression; in a program file, an expression alone does not print its value.
Explanation
The interactive shell displays the value of an expression entered directly, but a program file requires an explicit output command.
- 10
Define a string in Python and state how it is written.
Model answer
A string is a sequence of case-sensitive characters enclosed in quotation marks.
Explanation
A string is a sequence of characters, and quotation marks indicate to Python that the characters form a string.
- 11
What kinds of characters can a Python string contain?
Model answer
Strings can contain lowercase and uppercase letters, digits, keyboard symbols, and special characters such as newline and tab characters.
Explanation
String characters are not limited to letters; the content can include many keyboard characters and special characters.
- 12
Are uppercase and lowercase letters treated as the same character in strings?
Model answer
Yes. For example, lowercase
aand uppercaseAare different string characters.Explanation
Because strings are case-sensitive, uppercase and lowercase versions of a letter are different characters.
- 13
What does the
+operator do when applied to two strings, and does it add a space automatically?Model answer
String concatenation joins the characters in order to form a new string; it inserts no space unless a space is included explicitly.
Explanation
The plus operator joins the characters of two strings into a new string and does not insert a separator by itself.
- 14
How would you concatenate
"me"and"myself"with a space between them?Model answer
Concatenate an explicit string containing a space between the two strings.
Explanation
To create a visible gap during concatenation, a space must be included as a character in one of the strings.
- 15
What does
"me" * 3produce?Model answer
It repeats the string’s sequence three times, producing
"mememe".Explanation
Multiplying a string by an integer repeats its character sequence.
- 16
What types of operands can be used for string repetition?
Model answer
A string can be multiplied by an integer, in either order; multiplying it by a non-integer or another string is not supported.
Explanation
String repetition requires an integer count, not another string or a non-integer value.
- 17
What does
len(s)return, and what does it return ifsis"abc"?Model answer
len(s)returns the number of characters ins; fors = "abc", it returns3.Explanation
lencounts the characters in the string, including characters such as spaces. - 18
What is the difference between the string
"3"and the result ofint("3")?Model answer
int("3")produces the integer3, whereas the original"3"is a string character.Explanation
intconverts a suitable numeric string into an integer, allowing arithmetic instead of string repetition. - 19
How many characters are in
"a b", and why?Model answer
"a b"has three characters:a, a space, andb.Explanation
The string
"a b"has three characters because the space is part of the string. - 20
Why does concatenating a string directly with an integer cause an error, and how can it be fixed?
Model answer
Python raises a type error because concatenation requires strings; convert the integer with
strbefore concatenating.Explanation
Adding a string to an integer is a type mismatch; converting the integer to a string makes string concatenation possible.
- 21
What indices identify the characters in the string
"abc"?Model answer
The characters
a,b, andcare at indices0,1, and2, respectively.Explanation
Python string indices begin at zero, so the first character is at index
0. - 22
If
s = "abc", what doess[1]evaluate to?Model answer
s[1]evaluates to the single-character string"b".Explanation
Square brackets with one index select one character from the string.
- 23
What happens when you evaluate
"abc"[3], and why?Model answer
It raises an index error because
"abc"has no character at index3.Explanation
An index must refer to a position that exists in the string.
- 24
What does a negative index of
-1select in a string?Model answer
s[-1]returns the last character, which is"c"fors = "abc".Explanation
Negative indexing counts from the right end of a string, with
-1denoting the last character. - 25
What happens when
s[-4]is evaluated fors = "abc"?Model answer
s[-4]raises an index error fors = "abc"because it is beyond the string’s left end.Explanation
Negative indices can also go too far; an index outside the string’s positions causes an index error.
- 26
For
s = "abc", what doess[len(s) - 1]return?Model answer
len(s) - 1evaluates to2, sos[len(s) - 1]selects"c".Explanation
An expression can be calculated first and then used as an index.
- 27
If
s = "abcdefgh", what doess[3:6]return, and why is the character at index6excluded?Model answer
It returns
"def": indices3,4, and5are included, while the character at stop index6is not.Explanation
A slice starts at its start index and stops before its stop index.
- 28
If
s = "abcdefgh", what doess[3:6:2]return?Model answer
s[3:6:2]returns"df": it selects index3, skips index4, then selects index5.Explanation
A positive step moves from left to right, and a step of
2selects every other character. - 29
What step does Python use when a slice specifies a start and stop but omits the step?
Model answer
The default step is
1, sos[3:6]takes every character from index3up to, but not including, index6.Explanation
When the step is omitted, Python uses a step of
1, selecting each character between the bounds. - 30
What does
s[4:1:-2]return fors = "abcdefgh"?Model answer
For
s = "abcdefgh",s[4:1:-2]returns"ec": it selects index4, skips index3, and selects index2before stopping before index1.Explanation
A negative step traverses the string from right to left, selecting positions according to that step.
- 31
What does
s[::-1]do?Model answer
s[::-1]returns the characters ofsin reverse order.Explanation
An empty slice with omitted bounds and step
-1traverses the string backward. - 32
What does
s[6:3]return, and why?Model answer
It returns the empty string because a positive step moves rightward from index
6, while the stop index3is behind it.Explanation
If the direction set by the step cannot reach the stop from the start, the slice contains no characters.
- 33
Can you change the first character of a string using an assignment such as
s[0] = "b"? Explain.Model answer
It is not allowed because strings are immutable; their characters cannot be modified after the string is created.
Explanation
Strings are immutable, so indexed assignment cannot change a character in an existing string.
- 34
How can a program obtain a changed version of an immutable string?
Model answer
Create a new string with the desired characters and reassign the variable to it; the original string object is not modified.
Explanation
A changed string must be constructed as a new object, after which a variable can be rebound to it.
- 35
How can a Python program file explicitly show the result of an expression to the user?
Model answer
Wrap the expression in
print, which tells Python to display its resulting value when the file runs.Explanation
A program file must use
printto explicitly display selected values; expressions alone do not display their results. - 36
What happens to the output line after a
printstatement finishes?Model answer
Each
printcall outputs its value and then moves to a new line.Explanation
Each call to
printends its output with a newline by default. - 37
How does
printdisplay multiple comma-separated objects?Model answer
They are printed on one line, with a space separating each object.
Explanation
Comma-separated items in one
printcall are displayed on the same line with spaces between them. - 38
Compare printing an integer alongside strings with concatenating the integer directly into those strings.
Model answer
printcan display objects of different types, separating them with spaces; concatenation requires the operands to be strings.Explanation
Comma-separated printing can display different object types, while string concatenation requires string operands.
- 39
How can you concatenate an integer between two strings without using comma-separated printing?
Model answer
Convert the integer with
str, then concatenate the resulting string with the other strings.Explanation
Casting a non-string object with
strallows it to be concatenated with strings without the automatic comma spacing. - 40
What happens when Python executes an
inputstatement with a prompt string?Model answer
inputdisplays its prompt, pauses for the user to type something and press Enter, and returns what the user typed.Explanation
The string inside
inputacts as the prompt, and Python waits for the user to enter text and press Enter. - 41
What type of value does
inputreturn when the user types a number?Model answer
The entered text is returned as a string; for example, typing
3produces the string"3".Explanation
The value returned by
inputis a string, even when the user enters digits. - 42
If the user enters
3, how do the results of5 * num1differ depending on whethernum1is a string or an integer?Model answer
If the user types
3,5 * num1produces"33333"whennum1is the input string; converting it to an integer makes the result15.Explanation
Repeating the input string repeats its character sequence, whereas converting it first permits numeric multiplication.
- 43
How do you read a user-entered number as an integer rather than a string?
Model answer
Use
num = int(input(...)); the input text is converted to an integer before being bound tonum.Explanation
Casting the result of
inputtointchanges suitable numeric text into an integer before it is stored. - 44
How does an f-string distinguish expressions from literal text?
Model answer
An f-string begins with
f; expressions inside curly braces are evaluated, while text outside the braces is printed literally.Explanation
An f-string evaluates expressions inside braces and prints other characters in the string literally.
- 45
How can an f-string display the result of an expression alongside literal text without explicit string casting?
Model answer
Place each expression in curly braces within the f-string; Python evaluates and inserts its result into the output.
Explanation
Expressions in f-strings can be displayed without manually converting each result to a string or concatenating it.
- 46
Why might comma-separated
printarguments be unsuitable when a percent sign must appear immediately after a number?Model answer
A comma inserts a space before the next printed object; use string concatenation after casting or use an f-string to place the punctuation directly beside the value.
Explanation
Comma-separated printing inserts a space, which can be undesirable when punctuation should touch a value; concatenation or an f-string can avoid that spacing.
- 47
Give two places, other than the right-hand side of a simple assignment, where Python can evaluate an expression.
Model answer
Expressions can appear in many contexts, including an index, a
printargument, or an f-string; Python evaluates them before using or displaying their results.Explanation
Python evaluates expressions wherever they appear, including within indices, print calls, and f-string braces.
- 48
What is the Newton’s method formula for producing a next guess from a current guess?
Model answer
The next guess is the current guess minus the function value at that guess divided by the derivative at that guess: gextnext=g−f′(g)f(g).
Explanation
Newton’s method updates an estimate using the function value and derivative at the current guess.
- 49
For the Newton’s method cube-root example, what function and derivative are used at guess
g?Model answer
For the cube-root example, the function is f(g)=g3−x and its derivative is f′(g)=3g2.
Explanation
In the cube-root example, solving for the cube root of
xuses the function g3−x and its derivative 3g2. - 50
What two values does the cube-root example program obtain from the user?
Model answer
It asks the user for the number whose cube root is wanted and for an initial guess.
Explanation
The program uses user-provided input for the target and the starting estimate.
- 51
What does the demonstrated Newton’s method program calculate, and what does it not yet do?
Model answer
It calculates the current guess cubed and one next guess; it does not use that next guess to continue iterating.
Explanation
The example computes one update from the initial estimate but does not yet repeat the process.
- 52
How does the cube-root program obtain the derivative needed for its update?
Model answer
The programmer manually writes the function formula and its derivative into the code; the program does not derive the derivative automatically.
Explanation
The function and derivative are written explicitly in the program rather than automatically calculated by Python.
- 53
What is the difference between
=and==in Python?Model answer
=assigns the right-hand value to the left-hand variable;==evaluates to a Boolean indicating whether its operands are equivalent.Explanation
A single equals sign assigns a value, while a double equals sign tests whether two expressions are equivalent.
- 54
What kind of value does a comparison such as
2 < 3produce?Model answer
A comparison evaluates to either
TrueorFalse; for example,2 < 3evaluates toTrue.Explanation
Comparisons produce Boolean values rather than necessarily producing numbers.
- 55
Name the Python comparison operators covered for equality, inequality, and ordering.
Model answer
Python provides
==,!=,<,<=,>, and>=to test equality, inequality, and relative ordering.Explanation
The comparison operators test equality, inequality, and ordering relationships.
- 56
When is the expression
i != jtrue?Model answer
i != jevaluates toTruewheniandjare not equivalent and toFalsewhen they are equivalent.Explanation
The not-equal comparison is true precisely when the operands are not equivalent.
- 57
Does Python consider lowercase
aequal to uppercaseAin a string comparison?Model answer
No. Lowercase
aand uppercaseAare different characters, so they are not equivalent.Explanation
String comparisons are sensitive to character case.
- 58
What does the Boolean operator
notdo?Model answer
notchangesTruetoFalseandFalsetoTrue; therefore,not (2 < 3)isFalse.Explanation
The
notoperator reverses a Boolean result. - 59
When does a Boolean expression using
andevaluate to true?Model answer
A and Bis true only if bothAandBare true.Explanation
A conjunction is true only when both of its Boolean expressions are true.
- 60
When does a Boolean expression using
orevaluate to false?Model answer
A or Bis true if at least one operand is true and is false only when both are false.Explanation
A disjunction is false only when both of its Boolean expressions are false.
- 61
What does
2 < 3 and 3 < 4evaluate to, and why?Model answer
2 < 3 and 3 < 4evaluates toTruebecause both comparisons are true.Explanation
Combining two true comparisons with
andyields true. - 62
What does
2 < 3 and 3 > 4evaluate to, and why?Model answer
2 < 3 and 3 > 4evaluates toFalsebecause the second comparison is false.Explanation
A false operand makes an
andexpression false, even if the other operand is true. - 63
If
deriveisTrueanddrinkisFalse, what is the value ofdrink and derive?Model answer
If
deriveisTrueanddrinkisFalse, thendrink and deriveisFalse.Explanation
Boolean variables can be combined with Boolean operators to create another Boolean result.
- 64
Why should a numeric guess from
inputbe cast before it is compared with a numeric secret?Model answer
Convert the guess to an integer before comparing it with the numeric secret; otherwise, the guess remains a string.
Explanation
Input text must be converted when a numeric comparison is intended; otherwise, a numeric value and a string are being compared.
- 65
What does a basic
ifstatement do?Model answer
An
ifchecks a condition and executes its indented code block when the condition is true; otherwise, that block is skipped.Explanation
An
ifstatement introduces a decision point based on whether its condition is true. - 66
How does Python determine which lines belong to an
ifblock?Model answer
Statements indented beneath the
ifbelong to its code block and are controlled by its condition.Explanation
Python uses indentation to determine which statements belong to a conditional block.
- 67
How do the
ifandelseblocks divide execution?Model answer
If the
ifcondition is true, its block runs; otherwise, theelseblock runs. Only one of these blocks runs.Explanation
An
elseblock supplies the alternative when the precedingifcondition is false. - 68
What role does
elifplay in a conditional chain?Model answer
elifchecks another condition after earlier conditions fail, and its block runs if that condition is the first one found true.Explanation
An
elifcondition is checked when the preceding condition or conditions were false. - 69
If several conditions in an
if/elifchain are true, which block runs?Model answer
Only the first branch whose condition is true runs; later
elifandelseblocks are skipped.Explanation
In an
if/elifchain, Python runs the first true branch and skips the remaining branches. - 70
Can an
if/elifchain skip all its blocks?Model answer
Yes. If every
ifandelifcondition is false and there is noelse, none of their blocks runs.Explanation
Without a final
else, execution can continue without running any branch if every condition is false. - 71
What is the purpose of a final
elsein a conditional chain?Model answer
A final
elseruns when all precedingifandelifconditions are false.Explanation
A final
elsehandles the case where none of the preceding conditions is true. - 72
Where does execution continue after a selected conditional block finishes?
Model answer
Execution rejoins the rest of the program at the same indentation level as the original conditional.
Explanation
Once the selected conditional block finishes, execution resumes with statements at the surrounding indentation level.
- 73
How should a
printstatement be placed if it should run only when anifcondition is true?Model answer
Indent the statement so it is part of the
ifblock; otherwise, it runs after the conditional regardless of whether the condition was true.Explanation
A statement intended to run only when a condition is true must be indented within that condition’s block.
- 74
How does an inner conditional relate to the outer conditional that contains it?
Model answer
A nested conditional runs only when execution enters the outer block, and its own condition then determines whether its block runs.
Explanation
Nested conditionals are conditionals placed inside another conditional’s indented block.
- 75
Compare the behavior of two independent
ifstatements with aniffollowed by anelif.Model answer
Separate
ifstatements are each evaluated and multiple blocks can run, while anif/elifchain runs only its first true branch.Explanation
Separate
ifstatements are independent, so more than one may run; anif/elifchain selects at most one branch. - 76
How can an
if/elif/elsechain classify a numeric guess as too high, equal, or too low?Model answer
Use
if guess > secretfor too high,elif guess == secretfor equal, andelsefor too low.Explanation
The guess needs to be compared for greater-than, equality, and the remaining lower-than case.
- 77
Why should the too-high condition use
guess > secretrather thanguess >= secret?Model answer
Use
>rather than>=; otherwise, a guess equal to the secret is classified as too high.Explanation
An inclusive greater-than test would catch equality before the equality branch is reached.
- 78
Describe the conditional direction rule used for navigating the maze.
Model answer
Keep the right hand against a wall: go right if clear; otherwise go forward if clear, then left if clear, and otherwise go backward.
Explanation
The maze rule chooses a direction based on whether neighboring routes are blocked or clear.
- 79
How do conditional decisions apply the wall-following maze algorithm at each step?
Model answer
At each position, check the available directions in order and choose according to the right-hand wall rule; this can lead through a regular maze toward its exit or destination.
Explanation
A sequence of conditional choices can guide movement through a maze without turning away from the wall-following rule.
- 80
What limitation or assumption about the maze was stated for the wall-following algorithm?
Model answer
The method was described as eventually reaching the destination if the maze has no islands, meaning the target is not isolated in the middle of an enclosed region.
Explanation
The described wall-following method was qualified: it was expected to work for a regular maze without isolated islands.
- 81
How can a program print whether a user’s numeric guess matches a stored secret number?
Model answer
Store the secret number, read and convert the guess, then print the result of
guess == secret.Explanation
A program can use a Boolean comparison to report whether a user’s guess matches a stored number.
- 82
What value is stored if a variable is assigned the result of
secret == guess?Model answer
Assign the comparison, such as
secret == guess, to a variable; the variable then holdsTrueorFalse.Explanation
The Boolean result of a comparison can be stored in a variable and used later.
- 83
How does the schedule example interpret sums greater than, equal to, or less than 24?
Model answer
A sum greater than 24 is treated as impossible, a sum equal to 24 as a full schedule, and a smaller sum as having time left.
Explanation
The schedule example’s branches distinguish a total over 24, a total equal to 24, and a total below 24.
- 84
What does the catch-all branch in the schedule example calculate?
Model answer
When neither earlier condition applies, it computes the absolute value of 24−pset_time−sleep_time to determine the time left.
Explanation
The catch-all branch computes the difference between 24 and the combined time values to find remaining time.
- 85
How can testing several input cases help debug a program with conditional branches?
Model answer
Run the program with representative cases—too high, equal, and too low—and check that each produces the intended result.
Explanation
Testing multiple inputs can expose errors in branch boundaries, as with incorrectly including equality in the too-high condition.
- 86
How does Python’s indentation structure help when tracing or debugging conditional code?
Model answer
Indentation makes code-block membership visible, helping a reader trace which statements run under each condition and debug the program.
Explanation
Python’s visible indentation structure helps show which statements are controlled by each conditional.

Ask anything
We've read this whole study set, so questions about it get the best answers.