Python Math and Augmented Assignment

PythonPythonBeginner
Practice Now

Introduction

In this lab, we'll dive into crucial aspects of Python programming: math operators and augmented assignment operators.

Math operators are essential for performing mathematical operations, including addition, subtraction, multiplication, and division.

Augmented assignment operators streamline code by combining an operation with an assignment. For instance, x += y is equivalent to x = x + y.

Achievements

  • Python Math Operators
  • Python Augmented Assignment Operators

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/build_in_functions -.-> lab-88{{"`Python Math and Augmented Assignment`"}} end

Python Math Operators

Python provides a variety of built-in operators to perform mathematical operations, making it versatile for various calculations. Let's explore some basic operations using the Python interpreter.

Open the terminal and Python interpreter:

python3

Addition

Use the + operator for addition:

>>> x = 2
>>> y = 3
>>> x + y
5

Subtraction

Use the - operator for subtraction:

>>> x = 5
>>> y = 2
>>> x - y
3

Multiplication

Use the * operator for multiplication:

>>> x = 2
>>> y = 3
>>> x * y
6

Division

Use the / operator for division:

>>> x = 6
>>> y = 3
>>> x / y
2

Python's math operators are fundamental for various calculations, offering simplicity and flexibility in your code.

Python Augmented Assignment Operators

In addition to basic math operators, Python features augmented assignment operators that combine an operation with assignment. These operators simplify code by allowing you to perform an operation and assign the result to a variable in a single step.

Addition Assignment

Use the += operator to add a number to a variable and assign the result to the same variable:

>>> x = 5
>>> x += 3
>>> x
8

Subtraction Assignment

Use the -= operator to subtract a number from a variable and assign the result to the same variable:

>>> x = 5
>>> x -= 2
>>> x
3

Multiplication Assignment

Use the *= operator to multiply a number from a variable and assign the result to the same variable:

>>> x = 5
>>> x *= 3
>>> x
15

Division Assignment

Use the /= operator to divide a number by a number and assign the result to the same variable:

>>> x = 10
>>> x /= 2
>>> x
5

Summary

In this lab, we learned how to use math operators and augmented assignment operators in Python. These operators are essential for performing mathematical operations and making assignments in Python programs.

Other Python Tutorials you may like