Expressions

Related image

Expressions: a way to perform operations on data values to produce other data values

When entered at the Python shell prompt, an expression and operands are evaluated, and its operator is then applied to these values to compute the value of the expression.

Arithmetic Expressions

An arithmetic expression consists of operands and operators combined in a manner that is familiar to the algebra you learn in math classes.

The precedence rules (AKA PEMDAS) apply in Python arithmetic expressions.

  • Operations within parentheses get simplified first
  • Exponents
  • Multiplication
  • Division (remainders are also evaluated)
  • Addition
  • Subtraction

There are two exceptions. Operations of equal precedence are left associative, meaning that they are evaluated from left to right. Exponentiation and assignment operations are right associative, so they are read from right to left. Utilizing parentheses would change the order of operations.

Mixed-Mode Arithmetic and Type Conversions

Performing calculations involving both integers and floating-point numbers is called mixed-mode arithmetic.

3//2 * 5.0 yields 1 * 5.0 which yields 5.0

3/2 * 5 yields 1.5 * 5 which yields 7.5

You must use a type conversion function when working with the input of numbers. A type conversion function is a function with the same name as the data type to which it converts. Because the input function returns a string as its value, you must use the function int or float to convert the string to a number before performing arithmetic.

It is important to note that the int function converts a float to an int by excluding the decimal, not by rounding to the nearest whole number. Python is a strongly typed programming language. The interpreter checks data types of all operands before operators are applied to those operands. If the type of operand is not appropriate, the interpreter halts execution with an error message. This error checking prevents a program from attempting to do something that it cannot do.

Leave a comment