Computer Science

Python Arithmetic Operators

Python arithmetic operators are symbols used to perform mathematical operations in Python. They include addition (+), subtraction (-), multiplication (*), division (/), modulus (%), exponentiation (**), and floor division (//). These operators are used to manipulate numerical values and perform calculations within Python programs.

Written by Perlego with AI-assistance

11 Key excerpts on "Python Arithmetic Operators"

  • Book cover image for: Python Internals for Developers
    eBook - ePub

    Python Internals for Developers

    Practice Python 3.x Fundamentals, Including Data Structures, Asymptotic Analysis, and Data Types

    operands . Python has the following type of operators:
    • Arithmetic operators
    • Comparison operators
    • Logical operators
    • Identity operators
    • Membership operators
    • Bitwise operators
    • Assignment operators

    Arithmetic operators

    Arithmetic operators perform mathematical operations on operands such as addition, subtraction, and so on. Arithmetic operators are binary operators. Binary operators operate on two operands. Table 1.3 describes the various Python Arithmetic Operators:
    Operator Name Description
    + Addition Adds values of two operands.
    - Subtraction Subtract the value of the right operand from the left operand.
    * Multiplication Multiplies values of two operands.
    / Division Divides the left operand with the right operand.
    % Modulus Divides the left operand with the right operand and displays the output (remainder of division).
    ** Exponentiation Raise left operand to the power of right operand.
    // Floor Division Divides left operand with right operand and display the output (the floor value).
    Table 1.3: Python Arithmetic Operators
    Example 1.4 shows few arithmetic operators and their output.
    Example 1.4: Arithmetic operators
    1. 2 +3
      //Output 5
    2. 3-2 //Output 1
    3. 2 *3
      //Output 6
    4. 5 /2
      //Output 2.5
    5. 23 %5
      //Output 3
    6. 2 **4
      //Output 16
    7. 5 //2
      //Output 2
    The preceding example shows different outputs obtained while using arithmetic operators. As shown in the preceding example, the modulus operator (%) is the same as the mathematical remainder operator which outputs the remainder when 23 is divided by 5 (which is 3 ). The exponentiation operator (**) is the same as the mathematical power operator which outputs the value of 24 (which is 16 ). The floor division operator (//) divides the operand’s and the output’s floor value of division like in the preceding example, 5/2=2.5 but 5//2 outputs floor value of 2.5 which is 2 .
    The addition and multiplication operators in Python can be used for strings too. Python addition operator adds two strings and merges them. Python multiplication operator can take one string and one integer as input. Example 1.5
  • Book cover image for: Data Analysis with Python
    eBook - ePub

    Data Analysis with Python

    Introducing NumPy, Pandas, Matplotlib, and Essential Elements of Python Programming (English Edition)

    To perform operations, we need operators, which are the function of the operation, and operands are the input to that operation. For example, 10+6 = 16; here, in this expression, 10 and 6 are the operands, and + is the operator.
    Various types of operators in Python are depicted with their implementation in Python as follows.

    Arithmetic operators

    Arithmetic operators are required to perform arithmetic operations like addition, subtraction, multiplication, division, and so on. The following table is the list of arithmetic operators in Python:
    Operator name Operator symbol Description Example
    addition + Add the two operands a+b
    subtraction - Subtract the right operands from the left operand a-b
    multiplication * Multiply the two operands a*b
    division or float division / Left operand divide by the right operand and gives the float value as a result a/b
    floor division // Left operand divide by the right operand and gives the floor value of division as a result a//b
    exponent ** Raised the left operand to the power of right a**b (3**2 means 3 to the power of 2)
    modules % Gives the remainder of the division of the left operand by the right operand a%b
    Table 3.1: Arithmetic operators in Python
    The following are some codes where we used arithmetic operators on the variables a and b:

    Coding example(s)

    a = 10 b = 8 # Addition (+) addition =  a + b print(‘addition       =>  a + b  =’,addition) # Subtraction (-) Subtraction =  a - b
  • Book cover image for: Basic Core Python Programming
    eBook - ePub

    Basic Core Python Programming

    A Complete Reference Book to Master Python with Practical Applications (English Edition)

    table 3.2 which describes the arithmetic operators and their purpose. Since you have already worked with most of them in your maths class it is idle to start with these set of operators first.
    Operator Purpose
    + Addition
    - Subtraction
    / Division
    // Floor or integer division as it always returns an integer
    * Multiplication
    ** Exponent or raise to power
    % Modulus(mod)
    Table 3.2: Arithmetic operators and their purpose
    Note: Unlike C++ and Java, Python does not have any ++ or – operators to increment or decrement values by 1.
    Example 3.2:
    The following box shows the usage of arithmetic operators. Two variables ‘a ’ and ‘b ’ are first assigned values, and then arithmetic operations are performed on these variables.
    >>> a = 1 >>> print('a = ',a) a = 1 >>> b = 2 print('b = ',b) b = 2 >>>#Addition >>> s = a + b >>> print('a + b = ',s) a + b = 3 >>> #Subtraction >>> d = a - b >>> print('a - b = ',d) a - b = -1
    >>> #Division
    >>> div = a / b >>> print('a / b = ',div) a / b = 0.5 >>>#Floor or integer division as it always returns an integer >>> fd = a // b >>> print('a // b = ',fd) a // b = 0 >>>#Multiplication >>> p = a * b >>> print('a * b = ',p) a * b = 2 >>> #Exponent or raise to power >>> e = a ** b >>> print('a ** b = ',e) a ** b = 1 >>> #Modulus(mod) >>> md = a % b >>> print('a % b = ',md) a % b = 1

    3.3.1.1 Arithmetic operators precedence in Python

    When more than one arithmetic operator appears in an expression, the operations will be executed in a specific order. In Python, the operation precedence follows as per the acronym PEMDAS .
    P - Parenthesis
    E - Exponent
    M - Multiplication
    D - Division
    A - Addition
    S - Subtraction
    (2 + 2) / 2 – 2 * 2 / (2 / 2) * 2
    = 4 / 2 – 4 / 1 * 2 = 2-8 = -6 Now, try this example on the shell, and see the result. >>> (2 + 2) / 2 – 2 * 2 / (2 / 2) * 2 -6.0

    3.3.2 Relational/Comparison/Conditional operator

    Relational operators are also known as conditional or comparison operators
  • Book cover image for: A Functional Start to Computing with Python
    Thus, 100+100 re-duces to 200. Computing long ago parted ways with calculations of numerical results. Most of what computers do is search, organize data, find patterns, and sense physical objects. Nevertheless, because most students have learned some algebra, it is reasonable to first introduce Python’s numeric operators, and then ease into the less familiar operations. Unlike low level machine language working with bits, the operators in Python will not work unless types of data are suitable: Python is a typed language. Python outputs a TypeError message when you try to use an operator on the wrong type of data. Operators are of two flavors, binary and unary. Binary operators, like * and / , take two arguments placed on the left and right sides of the operator. Unary operators have just one argument placed on the right side of the operator. This chapter starts with familiar numeric operators, then goes on to introduce new ones for boolean and sequence types. After these operators are presented, Chapter 7 shows how operations can be mixed in expressions, and how operator priority helps to resolve ambiguity. Notation used in this and later chapters is the “ ➜ ” symbol, which indicates how Python evaluates an operation or expression, reducing it to an output value. Example: 100+100 ➜ 200 . Numeric: Float and Integer Arithmetic Numeric operators take integer or floating point arguments and compute a result. Most often, both left and right arguments to an operator have the same numeric type (integer or floating point), but it is possible to mix these as well, putting an integer on the left side and a float (floating point) on the right side or the other way around. A few numeric operators are specialized to integers; the section following this one deals with these.
  • Book cover image for: An Introduction to Python Programming: A Practical Approach
    eBook - ePub

    An Introduction to Python Programming: A Practical Approach

    step-by-step approach to Python programming with machine learning fundamental and theoretical principles.

    • Dr. Krishna Kumar Mohbey; Dr. Brijesh Bakariya(Author)
    • 2021(Publication Date)
    • BPB Publications
      (Publisher)
    HAPTER 2

    Operators and Expressions

    O perator is a particular concept in Python that is carried out from the computational point of view. Here, there are two types of the terminology used - operator and operands. The operator is a symbol that is performed with operands' help, and the operand is the value that the operator operates.

    Structure

    In this chapter, we will cover the following topics:
    • Types of operators
    • Writing expression in Python
    • Use comments during a program
    • Working with function and modules

    Objective

    The objective of this chapter is to introduce Python operators, expressions, functions, and modules. After completing this chapter, you should be familiar with various Python operators and their working. Also, you will be able to write Python programs using operators and expressions.

    What is an operator?

    It is a particular type of symbol that performs some operations on operands and returns the result. Let us take an example for better understanding, 10+20 is an expression. Here, 10 and 20 are operands, and + is an operator. So, in this example, a simple arithmetic expression is evaluated, and the result will be the addition of the two values.
    There are various types of operators used in Python. The table 2.1 shows the hierarchy of the operators available in Python:
    Operators Symbols
    Arithmetic operators +,-, *,/, %, **,//
    Comparison operators >,>=,<,<=,==,! =
    Assignment and shortcut operators =, +=,-=,*=,/=,%=,**=,//=
    Unary operators +x, -x
    Bitwise operators &,|,^,~,<<,>>
    Logical operators and, or, not
    Membership Operators in, not
    Identity operators is, is not
    Table 2.1: Hierarchy of the operators

    Arithmetic operators

    It performs the basic mathematical operation on the numeric operands. The arithmetic operators return the result, and the outcome depends on which type of operands you are using in programming.
    • Addition (+) : The symbol + is used while using this operator. It uses between two operands and this operator adds the two value. For example, a=4, b=2 then a + b
  • Book cover image for: Key dynamics in computer programming
    • Adele Kuzmiakova(Author)
    • 2023(Publication Date)
    • Arcler Press
      (Publisher)
    By inputting any arithmetic phrase into the interpreter, we may quickly examine its value: >>> 3+4 7 >>> 17–6 11 >>> 2 + 3*4 14 >>> (2 + 3)*4 20 >>> 3 + 11/4 5.75 In a Python application, none of these expressions would ever be used as a full line. The samples provided here are solely for educational purposes. We will learn how to use arithmetic expressions in Python scripts very soon (Alzahrani et al., 2018; Schäfer, 2021). The four operators are given, multiplication (*), subtraction (–), and addition (+), all function in the same way they did in elementary school. Division and multiplication take precedence over subtraction and addition, as seen in the examples above, and parenthesis can be used to specify the order in which operations should be performed (Dubois et al., 1996; Tateosian, 2015). 4.4. VARIABLES IN PYTHON 4.4.1. The Idea of a Variable One of the reasons computers programmers are so effective is that they can do computations with a variety of numbers while still following a similar set Introduction to Python Programming 105 of instructions. The usage of variables is one method of accomplishing this. Instead of computing 5*5, if we could compute side*side for any value of side, we would be able to measure the area of any square rather than the area of a square with side 5. Variables are simple to utilize in Python. You may insert the name of the variable in your code whenever you wish to utilize it (Donat, 2014; Hunt, 2019). The one drawback is that when you initially make a variable, it lacks a well-defined value, so you cannot utilize it in a framework that requires one. The simplest approach to introduce a variable is to use an assignment statement, as seen below: >>> side = 5 The variable produced is called side, and the line above assigns the value 5 to it (Figure 4.4). The following is a representation of memory at this moment in time: If we go along with this statement: >>> area = side*side In memory, then our picture is as follows: Figure 4.4.
  • Book cover image for: Numerical Methods in Engineering with Python 3
    Recall that Python se- quences have zero offset, so that a[0] represents the first row, a[1] the second row, etc. With very few exceptions we do not use lists for numerical arrays. It is much more convenient to employ array objects provided by the numpy module. Array objects are discussed later. Arithmetic Operators Python supports the usual arithmetic operators: + Addition − Subtraction ∗ Multiplication / Division ∗∗ Exponentiation % Modular division Some of these operators are also defined for strings and sequences as follows: >>> s = ’Hello ’ >>> t = ’to you’ 7 1.2 Core Python >>> a = [1, 2, 3] >>> print(3*s) # Repetition Hello Hello Hello >>> print(3*a) # Repetition [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> print(a + [4, 5]) # Append elements [1, 2, 3, 4, 5] >>> print(s + t) # Concatenation Hello to you >>> print(3 + s) # This addition makes no sense Traceback (most recent call last): File "", line 1, in print(3 + s) TypeError: unsupported operand type(s) for +: ’int’ and ’str’ Python also has augmented assignment operators, such as a + = b, that are famil- iar to the users of C. The augmented operators and the equivalent arithmetic expres- sions are shown in following table. a += b a = a + b a -= b a = a - b a *= b a = a*b a /= b a = a/b a **= b a = a**b a %= b a = a%b Comparison Operators The comparison (relational) operators return True or False. These operators are < Less than > Greater than <= Less than or equal to >= Greater than or equal to == Equal to != Not equal to Numbers of different type (integer, floating point, and so on) are converted to a common type before the comparison is made. Otherwise, objects of different type are considered to be unequal. Here are a few examples: >>> a = 2 # Integer >>> b = 1.99 # Floating point >>> c = ’2’ # String >>> print(a > b) True
  • Book cover image for: Python for Beginners
    • Kuldeep Singh Kaswan, Jagjit Singh Dhatterwal, B Balamurugan(Authors)
    • 2023(Publication Date)
    To the right of the assignment operator is an arithmetic expression involving two variables and the addition operator [ 12 ]. The expression is evaluated by adding together the values bound to the two variables. Once the addition expression’s value has been determined, that value can be assigned to the sum variable. print(num1, '+', num2, '=', sum) All expressions have a value. The process of determining the expression’s value is called evaluation. Evaluating simple expressions is easy. The literal value 54 evaluates to 54. The value of a variable named x is the value stored in the memory location bound to x. The value of a more complex expression is found by evaluating the smaller expressions that make it up and combining them with operators to form potentially new values. The commonly used Python Arithmetic Operators are found in Table 3.1. These operations – addition, subtraction, multiplication, division and power – behave in the expected way. The // and % operators are not common arithmetic operators in everyday practice, but they are very useful in programming. The // operator is called integer division, and the % operator is the modulus or remainder operator. 25/3 is 8.3333. Three does not divide into 25 evenly. In fact, three goes into 25 eight times with a remainder of one. Here, eight is the quotient, and one is the remainder
  • Book cover image for: Introduction to Computing Using Python
    eBook - PDF

    Introduction to Computing Using Python

    An Application Development Focus

    • Ljubomir Perkovic(Author)
    • 2012(Publication Date)
    • Wiley
      (Publisher)
    34 Chapter 2 Python Data Types Small fractional values will also be approximated: >>> 2.0**-100 7.888609052210118e-31 and very small values are approximated by 0: >>> 2.0**-1075 0.0 Operators for Number Types Python provides operators and built-in mathematical functions like abs() and min() to construct algebraic expressions. Table 2.4 lists the arithmetic expression operators available in Python. Table 2.4 Number-type operators. Listed are the operators that can be used on number objects (e.g., bool, int, float). If one of the operands is a float, the result is always a float value; otherwise, the result is an int value, except for the division (/) operator, which always gives a float value. Operation Description Type (if x and y are integers) x + y Sum Integer x - y Difference Integer x * y Product Integer x / y Division Float x // y Integer division Integer x % y Remainder of x // y Integer -x Negative x Integer abs(x) Absolute value of x Integer x**y x to the power y Integer For every operation other than division (/), the following holds: If both operands x and y (or just x for unary operations - and abs()) are integers, the result is an integer. If one of the operands is a float value, the result is a float value. For division (/), the result is a float value, regardless of the operands. Comparison operators are used to compare values. There are six comparison opera- tions in Python, as shown in Table 2.5. Note that in Python, comparisons can be chained arbitrarily: >>> 3 <= 3 < 4 True When an expression contains more than one operator, evaluating the expression requires that an order is specified. For example, does the expression 2 * 3 + 1 evaluate to 7 or 8? >>> 2 * 3 + 1 7 Table 2.5 Comparison operators. Two numbers of the same or different type can be compared with the comparison operators. Operation Description < Less than <= Less than or equal > Greater than >= Greater than or equal == Equal != Not equal
  • Book cover image for: Python Programming for Biology
    eBook - PDF

    Python Programming for Biology

    Bioinformatics and Beyond

    3 Python basics Contents Introducing the fundamentals Getting started Whitespace matters Using variables Simple data types Arithmetic String manipulation Collection data types List and tuple manipulation Set manipulation Dictionary manipulation Importing modules Introducing the fundamentals Python is a powerful, general-purpose computing language. It can be used for large and complicated tasks or for small and simple ones. Naturally, to get people started with its use, we begin with relatively straightforward examples and then afterwards increase the complexity. Hence, in the next two chapters we cover most of the day-to-day fundamentals of the language. You will need to be, at least a little, familiar with these ideas to appreciate the subsequent chapters. Much of what we illustrate here is called scripting, although there is no hard and fast rule about what is deemed to be a program and what is ‘merely’ a script. We will use the terminology interchangeably. Here we describe most of the common operations and the basic types of data, but some aspects will be left to dedicated chapters. Initially the focus will be on the core data types handled by Python, which basically means numbers and text. With numbers we will of course describe doing arithmetic operations and how this can be moved from the specific into the abstract using variables. All the other kinds of data in Python can also be worked with in a similarly abstract manner, although the operations that are used to manipulate non-numeric data won’t be mathematical. Moving on from simple numbers and text we will describe some of the other standard types of Python data. Most notable of these are the collection types that act as containers for other data, so, for example, we could have a list of words or a set of numbers, and the list or set is a named entity in itself; just another item that we can give a label to in our programs.
  • Book cover image for: Machine Learning For Dummies
    • John Paul Mueller, Luca Massaron(Authors)
    • 2021(Publication Date)
    • For Dummies
      (Publisher)
    When making comparisons, always con-sider operator precedence; otherwise, the assumptions you make about a com-parison outcome will likely be wrong. Working with functions To manage information properly, you need to organize the tools used to perform the required tasks. Each line of code that you create performs a specific task, and you combine these lines of code to achieve a desired result. Sometimes you need TABLE 5-6 Python Operator Precedence Operator Description () You use parentheses to group expressions and to override the default precedence so that you can force an operation of lower precedence (such as addition) to take precedence over an operation of higher precedence (such as multiplication). ** Exponentiation raises the value of the left operand to the power of the right operand. ~ – Unary operators interact with a single variable or expression. * / % // Multiply, divide, modulo, and floor division. – Addition and subtraction. >> << Right and left bitwise shift. & Bitwise AND. ^ | Bitwise exclusive OR and standard OR. <= < > >= Comparison operators. == != Equality operators. = %= /= // = –= = *= **= Assignment operators. is is not Identity operators. in not in Membership operators. not or and Logical operators. CHAPTER 5 Beyond Basic Coding in Python 73 to repeat the instructions with different data, and in some cases your code becomes so long that keeping track of what each part does is hard. Functions serve as orga-nization tools that keep your code neat and tidy. In addition, functions let you easily reuse the instructions you’ve created as needed with different data. This section of the chapter tells you all about functions. More important, in this section you start defining how to create your first serious applications in the same way that professional developers do. Creating reusable functions You go to your closet, take out pants and shirt, remove the labels, and put them on.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.