CompTIA PenTest+ Exam: Python Expressions for Increasing Variables

Increase Variable Val in Python: Two Expressions

Question

Which of the following expressions in Python increase a variable val by one (Choose two.)

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E. F.

DF.

https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python

The correct answers are C and F: val=(val+1) and val+=1.

A. The expression val++ is not valid in Python. This is a syntax used in some other programming languages (e.g., C, C++) to increment a variable by one, but it is not supported in Python.

B. The expression +val is used to get the positive value of a number. For example, +(-5) would evaluate to -5. It does not increment the variable.

C. The expression val=(val+1) increments the value of the variable val by one. This expression assigns the value of val+1 back to the variable val.

D. The expression ++val is not valid in Python. Similar to val++, it is used in other programming languages to increment a variable by one.

E. The expression val=val++ is not valid in Python. This expression assigns the current value of val to val, and then increments val, but it is not supported in Python.

F. The expression val+=1 increments the value of the variable val by one. This expression is a shorthand notation for val=val+1.

In summary, the correct answers are C and F: val=(val+1) and val+=1.