1.5: Number Basics
( \newcommand{\kernel}{\mathrm{null}\,}\)
By the end of this section you should be able to
- Use arithmetic operators to perform calculations.
- Explain the precedence of arithmetic operators.
Numeric data types
Python supports two basic number formats, integer and floating-point. An integer represents a whole number, and a floating-point format represents a decimal number. The format a language uses to represent data is called a data type. In addition to integer and floating-point types, programming languages typically have a string type for representing text.
Assume that x = 1
, y = 2.0
, and s = "32"
.
1.0 <class 'float'>
.1 <class 'int'>
.Basic arithmetic
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and division.
Four basic arithmetic operators exist in Python:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
Assume that x = 7
, y = 20
, and z = 2
.
5
6
Operator precedence
When a calculation has multiple operators, each operator is evaluated in order of precedence. Ex: 1 + 2 * 3
is 7
because multiplication takes precedence over addition. However, (1 + 2) * 3
is 9
because parentheses take precedence over multiplication.
Operator | Description | Example | Result |
---|---|---|---|
|
Parentheses |
|
|
|
Exponentiation |
|
|
|
Positive, negative |
|
|
|
Multiplication, division |
|
|
|
Addition, subtraction |
|
|
40
145
Write a Python computer program that:
- Defines an integer variable named
'int_a'
and assigns'int_a'
with the value10
. - Defines a floating-point variable named
'float_a'
and assigns'float_a'
with the value10.0
. - Defines a string variable named
'string_a'
and assigns'string_a'
with the string value"10"
. - Prints the value of each of the three variables along with their type.
Write a Python computer program that:
- Assigns the integer value
10
to a variable,meters
. - Assigns the floating-point value
3.28
to a variable,meter2feet
. - Calculates 10 meters in feet by multiplying
meter
bymeter2feet
. Store the result in a variable,feet
. - Prints the content of variable
feet
in the output.