深度阅读

How To Do Math in Python 3 with Operators

作者
作者
2023年08月22日
更新时间
11.23 分钟
阅读时间
0
阅读量

Python 3 supports a wide range of arithmetic operators that you can use for math operations. Here are some common operators:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulo (returns the remainder when one number is divided by another)
  • **: Exponentiation (raises one number to the power of another)
  • //: Floor Division (returns the result of division rounded down to the nearest integer)

Here are some examples:

x = 5
y = 2

# addition
print(x + y)  # output: 7

# subtraction
print(x - y)  # output: 3

# multiplication
print(x * y)  # output: 10

# division
print(x / y)  # output: 2.5

# modulo
print(x % y)  # output: 1

# exponentiation
print(x ** y)  # output: 25

# floor division
print(x // y)  # output: 2

In addition to these basic operators, Python also provides a number of mathematical functions in the math module that you can use to perform more complex mathematical operations, such as trigonometric functions, logarithmic functions, and more. To use these functions, you will need to import the math module at the beginning of your script.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。