Python Syntax and Semantics

Python

Elements of Programming

Expressions

Call Expressions

Function Notation vs. Mathematical Notation

Running Python Code

Self-contained Python Scripts

Syntax and Semantics

Example Program

# set the midpoint
midpoint = 5

# make two empty lists
lower = []; upper = []

# split the numbers into lower and upper
for i in range(10):
    if (i < midpoint):
        lower.append(i)
    else:
        upper.append(i)

print("lower:", lower)
print("upper:", upper)

Comments

The End-of-Line Terminates a Statement

Semicolon Optionally Terminates a Statement

Indentation: Whitespace Matters

Whitespace Within Lines Does Not Matter

Parentheses

Syntax and Semantics

Variables

Python Objects

Arithmetic Operators

Expression Type Operator Description
Addition a + b Sum of a and b
Subtraction a - b Difference of a and b
Multiplication a * b Product of a and b
Division a / b Quotient of a and b
Floor Division a // b Quotient, removing fractional parts
Modulus a % b Remainder after division of a by b
Exponentiation a ** b a raised to the power of b

Bitwise Operators

Expression Type Operator Description
Bitwise AND a & b Bits defined in both a and b
Bitwise OR a | b Bits defined in a or b
Bitwise XOR a ^ b Bits defined in a or b, not both
Bit shift left a << b Shift bits of a left by b units
Bit shift right a >> b Shift bits of a right by b units
Bitwise NOT ~a Bitwise negation of a

Assignment Operators

Operator Equivalent to
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
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

Operator Description
a == b a equal to b
a != b a not equal to b
a < b a less than b
a > b a greater than b
a <= b a less than or equal to b
a >= b a greater than or equal to b

Logical Operators

Operator Description
a and b True if both a and b are true
a or b True if either a or b is true
not a True if a is False

Identity and Membership Operators

Operator Description
a is b True if a and b are identical objects
a is not b True if a and b are not identical objects
a in b True if a is a member of b
a not in b True if a is not a member of b