Decrement by ...

Introduction:

  • To decrement the value of a variable by one in Python, you can use the Subtraction Assignment operator (-=). This is a shorthand way to subtract a value from a variable and update the variable with the new value.

Syntax:

  • The syntax to decrement the value of x by one is:

    python
    x -= 1
    
  • This is equivalent to:

    python
    x = x - 1
    

Example:

  • In this example, we will read a number into x from the user and decrement the value in x by one using the Subtraction Assignment operator.

Python Program:

python
# Read a number from user
x = int(input('Enter a number: '))

# Decrement the value of x by one
x -= 1

# Print the decremented value
print('After decrement:', x)

Output:

Enter a number: 4
After decrement: 3

Exercises:

  1. Decrement a User-Provided Number:
    • Write a program to read a number from the user and decrement it by one.

      python
      y = int(input("Enter a number: "))
      y -= 1
      print("New value after decrement:", y)
      

Summary:

  • In this tutorial, we learned how to decrement the value of a variable by one using the Subtraction Assignment operator in Python. This is a fundamental operation in programming, and mastering it will help you in various coding tasks!