0% found this document useful (0 votes)
10 views10 pages

Python Math Operators and Data Types

The document explains basic mathematical operations in Python, including exponentiation, modular arithmetic, and integer division, along with the order of operations. It also covers data types such as integers, floating-point numbers, and strings, highlighting how operators behave differently based on data types. Additionally, it introduces variables, assignment statements, and naming conventions for variables in Python programming.

Uploaded by

hemar4ever
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

Python Math Operators and Data Types

The document explains basic mathematical operations in Python, including exponentiation, modular arithmetic, and integer division, along with the order of operations. It also covers data types such as integers, floating-point numbers, and strings, highlighting how operators behave differently based on data types. Additionally, it introduces variables, assignment statements, and naming conventions for variables in Python programming.

Uploaded by

hemar4ever
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming involves some math opera ons you might not be familiar with: Exponen a on (or to

the power of) is mul plying a number by itself repeatedly, just like mul plica on is adding a number
to itself repeatedly. For example, two to the power of four (or two to the fourth power), wri en as or
24 or 2 ** 4, is the number two mul plied

by itself four mes: 24 = 2 × 2 × 2 × 2 = 16.

Modular arithme c is similar to the remainder result of division. For example, 14 % 4

evaluates to 2 because 14 divided by 4 is 3 with remainder 2. Even though Python’s

modulo operator is %, modular arithme c has nothing to do with percentages.

Integer division is the same as regular division except the result is rounded down. For

example, 25 / 8 is 3.125 but 25 // 8 is 3, and 29 / 10 is 2.9 but 29 // 10 is 2.

You can use plenty of other operators in Python expressions too. For example, Table 1-1 lists all

the math operators in Python.

Table 1-1: Math Operators

OPERATOR OPERATION EXAMPLE EVALUATES TO ...

** Exponen a on 2 ** 3 8

% Modulus/remainder 22 % 8 6

// Integer division 22 // 8 2

/ Division 22 / 8 2.75

* Mul plica on 3 * 5 15-Subtrac on 5 - 2 3

+ Addi on 2 + 2 4

The order of opera ons (also called precedence) of Python math operators is similar to that of

mathema cs. The ** operator is evaluated first; the *, /, //, and % operators are evaluated

next, from le to right; and the + and - operators are evaluated last (also from le to right).

You can use parentheses to override the usual precedence if you need to. Whitespace in

between the operators and values doesn’t ma er in Python, except for the indenta on at the

beginning of the line. But the conven on, or unofficial rule, is to have a single space in between

operators and values. Enter the following expressions into the interac ve shell:

>>> 2 + 3 * 6

20
>>> (2 + 3) * 6

30

>>> 48565878 * 578453

28093077826734

>>> 2 ** 8

256

>>> 23 / 7

3.2857142857142856

>>> 23 // 7

>>> 23 % 7

>>> 2 + 2

>>> (5 - 1) * ((7 + 1) / (3 - 1))

16.0

In each case, you as the programmer must enter the expression, but Python does the hard part

of evalua ng it. Python will keep evalua ng parts of the expression un l it becomes a single

value:

These rules for gether to form expressions are a fundamental part of Python as a programming

language, just like the grammar rules that help us communicate. Here’s an example:

This is a gramma cally correct English sentence.

This gramma cally is sentence not English correct a.

The second line is difficult to parse because it doesn’t follow the rules of English. Similarly, if

you enter a bad Python instruc on, Python won’t be able to understand it and will display a

SyntaxError error message, as shown here:

>>> 5 +
File "<python-input-0>", line 1

5+

SyntaxError: invalid syntax

>>> 42 + 5 + * 2

File "<python-input-0>", line 1

42 + 5 + * 2

SyntaxError: invalid syntax

You can always test whether an instruc on works by entering it into the interac ve shell. Don’t

worry about breaking the computer; the worst that could happen is that Python responds with

an error message. Professional so ware developers get error messages all the me while

wri ng code.

The Integer, Floa ng-Point, and String Data Types

Remember that expressions are just values combined with operators, and they

always evaluate to a single value. A

data type

(h ps://[Link]/3/library/[Link]) is a category for values, and

every value belongs to exactly one data type. The most common data types in

Python are listed in Table 1-2. The values -2 and 30, for example, are said to be

integer

(h ps://[Link]/3/library/[Link]#numeric-types-int

float-complex) values. The integer (or int) data type indicates values that are

whole numbers. Numbers with a decimal point, such as 3.14, are called

floa ng-point numbers

(h ps://[Link]/3/library/[Link]#numeric-types-int-float

complex) (or floats). Note that even though the value 42 is an integer, the
value 42.0 would be a floa ng-point number. Programmers o en use number

to refer to ints and floats collec vely, although number itself is not a Python

data type.

One subtle detail about Python is that any math performed using an int and a float results in a

float, not an int. While 3 + 4 evaluates to the integer 7, the expression 3 + 4.0 evaluates to the

floa ng-point number 7.0. Any division between two integers with the / division operator

results in a float as well. For example, 16 / 4 evaluates to 4.0 and not 4. Most of the me, this

informa on doesn’t ma er for your program, but knowing it will explain why your numbers

may suddenly gain a decimal point.

Table 1-2: Common Data Types

DATA TYPE

Integer (int)

EXAMPLES-2, -1, 0, 1, 2, 3, 4, 5

Floa ng-point number (float)

String (str)-1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25

'a', 'aa', 'aaa', 'Hello!', '11 cats', '5'

Python programs can also have text values called

strings

(h ps://[Link]/3/library/[Link]#text-sequence-type-str), or strs (pronounced

“s rs”). Always surround your string in single-quote (') characters (as in 'Hello' or 'Goodbye

cruel world!') so that Python knows where the string begins and ends. You can even have a

string with no characters in it, '', called a blank string or an empty string. Strings are explained

in greater detail in Chapter 8.

You may see the error message SyntaxError: unterminated string literal, as in this

example:

>>> 'Hello, world!

SyntaxError: unterminated string literal (detected at line 1)


This error means you probably forgot the final single-quote character at the end of the string.

String Concatena on and Replica on

The meaning of an operator may change based on the data types of the values

next to it. For example, + is the addi on operator when it operates on two

integers or floa ng-point values. However, when + is used to combine two

string values, it joins the strings as the string concatena on operator. Enter the

following into the interac ve shell:

>>> 'Alice' + 'Bob'

'AliceBob'

The expression evaluates down to a single, new string value that combines the text of the two

strings. However, if you try to use the + operator on a string and an integer value, Python won’t

know how to handle this and will display an error message:

>>> 'Alice' + 42

Traceback (most recent call last):

File "<python-input-0>", line 1, in <module>

'Alice' + 42

TypeError: can only concatenate str (not "int") to str

The error message can only concatenate str (not "int") to str means that Python

thought you were trying to concatenate an integer to the string 'Alice'. Your code will have

to explicitly convert the integer to a string because Python cannot do this automa cally. (I’ll

explain how to convert between data types in “Dissec ng the Program” on page 14, where we

talk about the

str()

(h ps://[Link]/3/library/func [Link]#func

str),

int()

(h ps://[Link]/3/library/func [Link]#int), and


float()

(h ps://[Link]/3/library/func [Link]#float) func ons.)

The * operator mul plies two integer or floa ng-point values. But when the * operator is used

on one string value and one integer value, it becomes the string replica on operator. Enter a

string mul plied by a number into the interac ve shell to see this in ac on:

>>> 'Alice' * 5

'AliceAliceAliceAliceAlice'

The expression evaluates down to a single string value that repeats the original string a

number of mes equal to the integer value. String replica on is a useful trick, but it’s not used

as o en as string concatena on.

The * operator can only be used with two numeric values (for mul plica on), or one string

value and one integer value (for string replica on). Otherwise, Python will just display an error

message, such as the following:

>>> 'Alice' * 'Bob'

Traceback (most recent call last):

File "<python-input-0>", line 1, in <module>

'Alice' * 'Bob'

TypeError: can't mul ply sequence by non-int of type 'str'

>>> 'Alice' * 5.0

Traceback (most recent call last):

File "<python-input-0>", line 1, in <module>

'Alice' * 5.0

TypeError: can't mul ply sequence by non-int of type 'float'

It makes sense that Python wouldn’t understand these expressions: you can’t mul ply two

words, and it’s hard to replicate an arbitrary string a frac onal number of mes.

Expressions, data types, and operators may seem abstract to you right now, but as you learn

more about these concepts, you’ll be able to create increasingly sophis cated programs that
do math on data pulled from spreadsheets, websites, the output of other programs, and other

places.

Storing Values in Variables

A variable is like a box in the computer’s memory where you can store a single

value. If you want to use the result of an evaluated expression later in your

program, you can save it inside a variable.

Assignment Statements

You’ll store values in variables with an assignment statement. An assignment statement consists

of a variable name, an equal sign (called the assignment operator), and the value to be stored.

If you enter the assignment statement spam = 42, a variable named spam will have the integer

value 42 stored in it.

You can think of a variable as a labeled box that a value is placed in, but Chapter 6 explains

how a name tag a ached to the value might be a be er metaphor. Both are shown in Figure

1-1.

Figure 1-1: The code spam = 42 is like telling the program, “The variable spam now has the integer

value 42 in it.”

For example, enter the following into the interac ve shell:

❶ >>> spam = 40

>>> spam

40

>>> eggs = 2

❷ >>> spam + eggs

42

>>> spam + eggs + spam

82

❸ >>> spam = spam + 2

>>> spam
42

A variable is ini alized (or created) the first me a value is stored in it ❶. A er that, you can

use it in expressions with other variables and values ❷. When a variable is assigned a new

value ❸, the old value is forgo en, which is why spam evaluated to 42 instead of 40 at the

end of the example. This is called overwri ng the variable. Enter the following code into the

interac ve shell to try overwri ng a string:

>>> spam = 'Hello'

>>> spam

'Hello'

>>> spam = 'Goodbye'

>>> spam

'Goodbye'

Just like the box in Figure 1-1, the spam variable in Figure 1-2 stores 'Hello' un l you replace

the string with 'Goodbye'.

Figure 1-2: When a new value is assigned to a variable, the old one is forgo en.

You can also think of overwri ng a variable as reassigning the name tag to a new value.

Variable Names

A good variable name describes the data it contains. Imagine that you moved to a new house

and labeled all of your moving boxes as Stuff. You’d never find anything! Most of this book’s

examples (and Python’s documenta on) use generic variable names like spam, eggs, and

bacon, which come from the Monty Python “Spam” sketch. But in your programs, descrip ve

names will help make your code more readable.

Though you can name your variables almost anything, Python does have some naming

restric ons. Your variable name must obey the following four rules:

It can’t have spaces.

It can use only le ers, numbers, and the underscore (_) character.

It can’t begin with a number.


It can’t be a Python

keyword

(h ps://[Link]/3/reference/lexical_analysis.html#keywords), such as if, for,

return, or other keywords you’ll learn in this book.

Table 1-3 shows examples of legal variable names.

Table 1-3: Valid and Invalid Variable Names

VALID VARIABLE NAMES INVALID VARIABLE NAMES

current_balance current-balance (hyphens are not allowed)

currentBalance current balance (spaces are not allowed)

account4 4account (can’t begin with a number)

_42 42 (can begin with an underscore but not a number)

TOTAL_SUM TOTAL_$UM (special characters like $ are not allowed)

hello 'hello' (special characters like ' are not allowed)

Variable names are case-sensi ve, meaning that spam, SPAM, Spam, and sPaM are four different

variables. It is a Python conven on to start your variables with a lowercase le er: spam instead

of Spam.

CODE STYLE OPINIONS AND PEP 8

Previous edi ons of this book used camelCase instead of underscores to separate words

in variable names; that is, variables lookedLikeThis instead of looking_like_this. The

la er form is called snake_case because the underscores between words look like li le

snakes (while the uppercase le ers in camelCase look like the humps on a camel). Some

experienced programmers may point out that the official Python code style document,

PEP 8 (h ps://[Link]/pep-0008/), says that underscores should be used. I

unapologe cally prefer camelCase and point to the “A Foolish Consistency Is the

Hobgoblin of Li le Minds” sec on in PEP 8 itself as my defense:

Consistency with the style guide is important. But most importantly: know when to be

inconsistent—some mes the style guide just doesn’t apply. When in doubt, use your best
judgment.

The computer doesn’t care which style you use, and PEP 8 is not a stone tablet of

irrefutable commandments. It doesn’t ma er which style you use as long as you use the

same style consistently. To prove this, I’ve rewri en the code in this book to use

snake_case because it truly doesn’t ma er either way.

You might also like