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
xby one is:pythonx -= 1This is equivalent to:
pythonx = x - 1
Example:
- In this example, we will read a number into
xfrom the user and decrement the value inxby 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:
- Decrement a User-Provided Number:
Write a program to read a number from the user and decrement it by one.
pythony = 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!