PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium

Question 2

You are creating a simple calculator application using Tkinter in Python. The calculator has buttons for digits (0-9), basic arithmetic operations (+, -, *, /), and an "Equals" button to compute the result. The calculator displays the input and output in a Label widget. The code snippet below handles the arithmetic operations:



Which of the following statements is correct regarding this calculator implementation?

  • A

    The eval() function is a safe and efficient way to compute the result of the expression in the calculate() function.

  • B

    The command parameter in the button creation loop is incorrectly using lambda and will cause all buttons to behave the same.

  • C

    The click_button() function should use the append() method instead of concatenation to add the value to new_text.

  • D

    The label_var.get() in the calculate() function correctly retrieves the current expression as a string.

Reveal correct answer

Correct answer: D

A.

While eval() can evaluate the expression, it is not considered safe because it will execute any arbitrary code. In a real-world application, this could be exploited to run harmful commands. A safer approach would be to parse and evaluate the expression manually or use a specialized library like ast.literal_eval for safer evaluation.

B.

The lambda used in the button creation loop is correct. It ensures that each button passes its corresponding text value (t) to the click_button() function. Without lambda, all buttons would pass the same value (the last value in the loop), which is a common pitfall in Tkinter button creation.

C.

The append() method is not applicable here because current_text and new_text are strings, not lists. String concatenation is the correct method to append one string to another.

D.

The label_var.get() method is the correct way to retrieve the current string displayed in the Label widget. This string is then evaluated by the eval() function in the calculate() function.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need