Sub topic 2
Arithmetic, Numbers, and String Slices
This chapter assumes you can run Python code, use print(), and read simple statements.
Arithmetic Operators and Precedence
Python supports these common operators:
+addition-subtraction*multiplication/true division//floor division%remainder, or modulo**exponentiation
Multiplication, division, floor division, modulo, and exponentiation are evaluated before addition and subtraction. Use parentheses when you want the order to be obvious.
total = 2 + 3 * 4
grouped = (2 + 3) * 4
print(total) # 14
print(grouped) # 20
print(7 / 2) # 3.5
print(7 // 2) # 3
print(-7 // 2) # -4
print(7 % 2) # 1
print(2 ** 10) # 1024Multiple Assignment and Augmented Assignment
Python can assign several names in one statement. Unpacking assigns items from an iterable, such as a tuple or list, to separate names.
width, height = 800, 600
first, *middle, last = [1, 2, 3, 4]
width += 100 # equivalent to width = width + 100
height *= 2 # equivalent to height = height * 2
print(width, height)
print(first, middle, last)Floating-Point Precision and Decimal
A float stores an approximation in binary. Therefore, direct comparisons can surprise you.
import math
from decimal import Decimal
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # TrueUse math.isclose() for approximate float comparisons. Use Decimal for exact decimal-style calculations, such as currency, and construct it from strings.
Converting and Rounding Numbers
int() truncates toward zero. round() uses nearest-even behavior for exact halves.
print(int(3.9)) # 3
print(round(2.5)) # 2
print(round(3.5)) # 4
print(float("3.5"))Writing String Literals
Strings are Unicode text enclosed in single or double quotes. Escape sequences represent special characters. Raw strings disable most escape processing.
message = "He said, \"Hi!\""
path = r"C:\new\test"
multiline = """Line one
Line two"""Indexing and Slicing Strings
Indexing selects one character. Slicing selects a range using start:stop:step; the stop position is excluded. Negative indexes count from the end.
text = "Python"
print(text[0]) # P
print(text[-1]) # n
print(text[1:4]) # yth
print(text[::-1]) # nohtyPStrings are immutable, so indexing cannot replace a character. Build a new string instead:
updated = "J" + text[1:]
print(updated) # JythonExercise
What do 7 // 2, 7 % 2, and "Python"[::-1] produce?
Show answer
They produce 3, 1, and "nohtyP".