Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement an Instance Method to Update StateE02. Create a Class Method Constructor from a DictionaryE03. Write a Static Method Utility for ValidationE

Problem No 1

Implement an Instance Method to Update State

Easy

8 minute session

Summary

Practice writing an instance method that mutates an object's state and returns the updated value.

Problem statement

You are given a simple Counter class that keeps an integer value. Implement the instance method increment(self, amount) which adds the given amount to the counter's value, updates the instance state, and returns the updated value. The constructor accepts an optional starting value (default 0). The method should accept positive, zero, and negative integers.

Task

Implement the Counter.increment method so it updates the instance's value and returns the new value.

Examples

Basic increment

Input

Counter(5).increment(2)

Output

7

Explanation

Start at 5, add 2, new value is 7 and that is returned.

Input format

A call to Counter(start).increment(amount) where start is optional integer and amount is an integer.

Output format

An integer representing the updated counter value (returned by the increment method).

Constraints

- start and amount will be integers (may be negative or zero). - The increment method should mutate self.value and return the new integer value.

Samples

Sample input 0

Counter(0).increment(10)

Sample output 0

10

Explanation 0

0 + 10 => 10

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.