PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Easy
Question 35
Q548 - Basics
What is the expected output of the following code?
- x = '\\\'
- print(len(x))
-
A
3 -
B
2 -
C
The code is erroneous.
-
D
1
Reveal correct answer
Correct answer: C
Explanation
Topics: escaping len()
Try it yourself:
- # print(len('\')) # SyntaxError: ...
- print(len('\\')) # 1
- # print(len('\\\')) # SyntaxError: ...
Explanation:
The backslash is the character to escape another character.
If you write '\' the backslash escapes
the ending single quote to a normal character.
It takes its syntactical meaning and the single quote becomes a normal character
and it looses its ability to end the string and therefore we get the syntax error.
If you write '\\' the one backslash escapes the other
and you end up with a string with one normal backslash.
If you write '\\\' you again have the same problem
than with one single backslash.
The first backslash escapes the second one,
but the third backslash escape the ending single quote,
the string does not get closed and you get a syntax error.
(There is another question about the same topic Q227.)
Q548 (Please refer to this number, if you want to write me about this question.)
A. The code will not produce an output of 3 as the length of the string cannot be determined due to the syntax error caused by the backslash "\" at the end of the string. The code will fail to execute, and the length of the string will not be calculated.
B. The code will not run to completion because of the syntax error introduced by the backslash "\" at the end of the string. As a result, the length of the string cannot be calculated, and the output will not be 2.
C. The code is erroneous because the backslash character "\" is used as an escape character in Python. In this case, the backslash "\" at the end of the string is not followed by another character to escape, which results in a syntax error.
D. The code will not execute successfully due to the syntax error caused by the backslash "\" at the end of the string. Therefore, the output of the code cannot be determined, and it will not return a value of 1.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
