1. Home
  2. Explore
  3. Computer Science
  4. Python Strings, Input, and Decisions

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Python Strings, Input, and Decisions

  • 86Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Objects and Expressions

What does an object’s type tell Python?

86 questions

  1. 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. 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. 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. 4

    How does Python evaluate an expression such as pi * radius**2 when pi and radius are 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. 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. 6

    What happens when Python executes radius = radius + 1?

    Model answer

    Python evaluates radius + 1 using the current value, creates the result, and rebinds radius to it; the original object is not modified.

    Explanation

    An assignment like radius = radius + 1 is not a mathematical equality; it replaces the name’s binding with a newly evaluated value.

  7. 7

    What value is bound to var in var = type(5 * 4)?

    Model answer

    5 * 4 evaluates to the integer 20, and type(20) evaluates to the type int, which is bound to var.

    Explanation

    An expression can evaluate to a type object, which can then be bound to a variable.

  8. 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. 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. 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. 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. 12

    Are uppercase and lowercase letters treated as the same character in strings?

    Model answer

    Yes. For example, lowercase a and uppercase A are different string characters.

    Explanation

    Because strings are case-sensitive, uppercase and lowercase versions of a letter are different characters.

  13. 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. 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. 15

    What does "me" * 3 produce?

    Model answer

    It repeats the string’s sequence three times, producing "mememe".

    Explanation

    Multiplying a string by an integer repeats its character sequence.

  16. 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. 17

    What does len(s) return, and what does it return if s is "abc"?

    Model answer

    len(s) returns the number of characters in s; for s = "abc", it returns 3.

    Explanation

    len counts the characters in the string, including characters such as spaces.

  18. 18

    What is the difference between the string "3" and the result of int("3")?

    Model answer

    int("3") produces the integer 3, whereas the original "3" is a string character.

    Explanation

    int converts a suitable numeric string into an integer, allowing arithmetic instead of string repetition.

  19. 19

    How many characters are in "a b", and why?

    Model answer

    "a b" has three characters: a, a space, and b.

    Explanation

    The string "a b" has three characters because the space is part of the string.

  20. 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 str before concatenating.

    Explanation

    Adding a string to an integer is a type mismatch; converting the integer to a string makes string concatenation possible.

  21. 21

    What indices identify the characters in the string "abc"?

    Model answer

    The characters a, b, and c are at indices 0, 1, and 2, respectively.

    Explanation

    Python string indices begin at zero, so the first character is at index 0.

  22. 22

    If s = "abc", what does s[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. 23

    What happens when you evaluate "abc"[3], and why?

    Model answer

    It raises an index error because "abc" has no character at index 3.

    Explanation

    An index must refer to a position that exists in the string.

  24. 24

    What does a negative index of -1 select in a string?

    Model answer

    s[-1] returns the last character, which is "c" for s = "abc".

    Explanation

    Negative indexing counts from the right end of a string, with -1 denoting the last character.

  25. 25

    What happens when s[-4] is evaluated for s = "abc"?

    Model answer

    s[-4] raises an index error for s = "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. 26

    For s = "abc", what does s[len(s) - 1] return?

    Model answer

    len(s) - 1 evaluates to 2, so s[len(s) - 1] selects "c".

    Explanation

    An expression can be calculated first and then used as an index.

  27. 27

    If s = "abcdefgh", what does s[3:6] return, and why is the character at index 6 excluded?

    Model answer

    It returns "def": indices 3, 4, and 5 are included, while the character at stop index 6 is not.

    Explanation

    A slice starts at its start index and stops before its stop index.

  28. 28

    If s = "abcdefgh", what does s[3:6:2] return?

    Model answer

    s[3:6:2] returns "df": it selects index 3, skips index 4, then selects index 5.

    Explanation

    A positive step moves from left to right, and a step of 2 selects every other character.

  29. 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, so s[3:6] takes every character from index 3 up to, but not including, index 6.

    Explanation

    When the step is omitted, Python uses a step of 1, selecting each character between the bounds.

  30. 30

    What does s[4:1:-2] return for s = "abcdefgh"?

    Model answer

    For s = "abcdefgh", s[4:1:-2] returns "ec": it selects index 4, skips index 3, and selects index 2 before stopping before index 1.

    Explanation

    A negative step traverses the string from right to left, selecting positions according to that step.

  31. 31

    What does s[::-1] do?

    Model answer

    s[::-1] returns the characters of s in reverse order.

    Explanation

    An empty slice with omitted bounds and step -1 traverses the string backward.

  32. 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 index 3 is behind it.

    Explanation

    If the direction set by the step cannot reach the stop from the start, the slice contains no characters.

  33. 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. 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. 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 print to explicitly display selected values; expressions alone do not display their results.

  36. 36

    What happens to the output line after a print statement finishes?

    Model answer

    Each print call outputs its value and then moves to a new line.

    Explanation

    Each call to print ends its output with a newline by default.

  37. 37

    How does print display multiple comma-separated objects?

    Model answer

    They are printed on one line, with a space separating each object.

    Explanation

    Comma-separated items in one print call are displayed on the same line with spaces between them.

  38. 38

    Compare printing an integer alongside strings with concatenating the integer directly into those strings.

    Model answer

    print can 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. 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 str allows it to be concatenated with strings without the automatic comma spacing.

  40. 40

    What happens when Python executes an input statement with a prompt string?

    Model answer

    input displays its prompt, pauses for the user to type something and press Enter, and returns what the user typed.

    Explanation

    The string inside input acts as the prompt, and Python waits for the user to enter text and press Enter.

  41. 41

    What type of value does input return when the user types a number?

    Model answer

    The entered text is returned as a string; for example, typing 3 produces the string "3".

    Explanation

    The value returned by input is a string, even when the user enters digits.

  42. 42

    If the user enters 3, how do the results of 5 * num1 differ depending on whether num1 is a string or an integer?

    Model answer

    If the user types 3, 5 * num1 produces "33333" when num1 is the input string; converting it to an integer makes the result 15.

    Explanation

    Repeating the input string repeats its character sequence, whereas converting it first permits numeric multiplication.

  43. 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 to num.

    Explanation

    Casting the result of input to int changes suitable numeric text into an integer before it is stored.

  44. 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. 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. 46

    Why might comma-separated print arguments 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. 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 print argument, 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. 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)g_{ ext{next}} = g - \frac{f(g)}{f'(g)}gextnext​=g−f′(g)f(g)​.

    Explanation

    Newton’s method updates an estimate using the function value and derivative at the current guess.

  49. 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−xf(g)=g^3-xf(g)=g3−x and its derivative is f′(g)=3g2f'(g)=3g^2f′(g)=3g2.

    Explanation

    In the cube-root example, solving for the cube root of x uses the function g3−xg^3-xg3−x and its derivative 3g23g^23g2.

  50. 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. 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. 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. 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. 54

    What kind of value does a comparison such as 2 < 3 produce?

    Model answer

    A comparison evaluates to either True or False; for example, 2 < 3 evaluates to True.

    Explanation

    Comparisons produce Boolean values rather than necessarily producing numbers.

  55. 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. 56

    When is the expression i != j true?

    Model answer

    i != j evaluates to True when i and j are not equivalent and to False when they are equivalent.

    Explanation

    The not-equal comparison is true precisely when the operands are not equivalent.

  57. 57

    Does Python consider lowercase a equal to uppercase A in a string comparison?

    Model answer

    No. Lowercase a and uppercase A are different characters, so they are not equivalent.

    Explanation

    String comparisons are sensitive to character case.

  58. 58

    What does the Boolean operator not do?

    Model answer

    not changes True to False and False to True; therefore, not (2 < 3) is False.

    Explanation

    The not operator reverses a Boolean result.

  59. 59

    When does a Boolean expression using and evaluate to true?

    Model answer

    A and B is true only if both A and B are true.

    Explanation

    A conjunction is true only when both of its Boolean expressions are true.

  60. 60

    When does a Boolean expression using or evaluate to false?

    Model answer

    A or B is 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. 61

    What does 2 < 3 and 3 < 4 evaluate to, and why?

    Model answer

    2 < 3 and 3 < 4 evaluates to True because both comparisons are true.

    Explanation

    Combining two true comparisons with and yields true.

  62. 62

    What does 2 < 3 and 3 > 4 evaluate to, and why?

    Model answer

    2 < 3 and 3 > 4 evaluates to False because the second comparison is false.

    Explanation

    A false operand makes an and expression false, even if the other operand is true.

  63. 63

    If derive is True and drink is False, what is the value of drink and derive?

    Model answer

    If derive is True and drink is False, then drink and derive is False.

    Explanation

    Boolean variables can be combined with Boolean operators to create another Boolean result.

  64. 64

    Why should a numeric guess from input be 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. 65

    What does a basic if statement do?

    Model answer

    An if checks a condition and executes its indented code block when the condition is true; otherwise, that block is skipped.

    Explanation

    An if statement introduces a decision point based on whether its condition is true.

  66. 66

    How does Python determine which lines belong to an if block?

    Model answer

    Statements indented beneath the if belong to its code block and are controlled by its condition.

    Explanation

    Python uses indentation to determine which statements belong to a conditional block.

  67. 67

    How do the if and else blocks divide execution?

    Model answer

    If the if condition is true, its block runs; otherwise, the else block runs. Only one of these blocks runs.

    Explanation

    An else block supplies the alternative when the preceding if condition is false.

  68. 68

    What role does elif play in a conditional chain?

    Model answer

    elif checks another condition after earlier conditions fail, and its block runs if that condition is the first one found true.

    Explanation

    An elif condition is checked when the preceding condition or conditions were false.

  69. 69

    If several conditions in an if/elif chain are true, which block runs?

    Model answer

    Only the first branch whose condition is true runs; later elif and else blocks are skipped.

    Explanation

    In an if/elif chain, Python runs the first true branch and skips the remaining branches.

  70. 70

    Can an if/elif chain skip all its blocks?

    Model answer

    Yes. If every if and elif condition is false and there is no else, none of their blocks runs.

    Explanation

    Without a final else, execution can continue without running any branch if every condition is false.

  71. 71

    What is the purpose of a final else in a conditional chain?

    Model answer

    A final else runs when all preceding if and elif conditions are false.

    Explanation

    A final else handles the case where none of the preceding conditions is true.

  72. 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. 73

    How should a print statement be placed if it should run only when an if condition is true?

    Model answer

    Indent the statement so it is part of the if block; 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. 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. 75

    Compare the behavior of two independent if statements with an if followed by an elif.

    Model answer

    Separate if statements are each evaluated and multiple blocks can run, while an if/elif chain runs only its first true branch.

    Explanation

    Separate if statements are independent, so more than one may run; an if/elif chain selects at most one branch.

  76. 76

    How can an if/elif/else chain classify a numeric guess as too high, equal, or too low?

    Model answer

    Use if guess > secret for too high, elif guess == secret for equal, and else for too low.

    Explanation

    The guess needs to be compared for greater-than, equality, and the remaining lower-than case.

  77. 77

    Why should the too-high condition use guess > secret rather than guess >= 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. 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. 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. 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. 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. 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 holds True or False.

    Explanation

    The Boolean result of a comparison can be stored in a variable and used later.

  83. 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. 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_time24 - \text{pset\_time} - \text{sleep\_time}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. 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. 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.

1 of 86
Question 1 of 86

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent