nerdexam
Python_Institute

PCEP-30-02 · Question #249

Consider the following code. 1 start = input('How old were you at the time of joining?') 2 now = input('How old are you today?') Which of the following statements will print the right output?

The correct answer is A. print( 'Congratulations on ' + str(int(now) - int(start)) + ' years of service!'). Option A is correct because input() always returns a string in Python, so both start and now are strings - you must convert them to int before subtracting (int(now) - int(start)), and then convert the resulting integer back to a str before concatenating it with the surrounding…

Question

Consider the following code. 1 start = input('How old were you at the time of joining?') 2 now = input('How old are you today?') Which of the following statements will print the right output?

Options

  • Aprint( 'Congratulations on '
    • str(int(now) - int(start))
    • ' years of service!')
  • Bprint( 'Congratulations on '
    • (int(now) - int(start))
    • ' years of service!')
  • Cprint( 'Congratulations on '
    • str(now - start)
    • ' years of service!')
  • Dprint( 'Congratulations on '
    • int(now - start)
    • ' years of service!')

How the community answered

(46 responses)
  • A
    74% (34)
  • B
    7% (3)
  • C
    15% (7)
  • D
    4% (2)

Explanation

Option A is correct because input() always returns a string in Python, so both start and now are strings - you must convert them to int before subtracting (int(now) - int(start)), and then convert the resulting integer back to a str before concatenating it with the surrounding string literals using +.

Option B fails because it omits str() around the arithmetic result - Python raises a TypeError when you try to concatenate an int directly with a string using +.

Option C fails because it tries to subtract two raw strings (now - start), which Python cannot do - subtraction is not defined for strings and raises a TypeError.

Option D fails for the same reason as C (now - start errors on strings), and even if that were fixed, int(...) on the result still can't be concatenated with string literals without str().

Memory tip: Think of it as a round trip - input() gives you a string, you convert in with int() to do math, then convert out with str() to join it back into a sentence.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice