Python Syntax and Semantics
Python
Python was created by Guido van Rossum and first released in 1991
Python is an interpreted high-level programming language
Python is a multi-paradigm programming language
Python is dynamically typed – types of variables do not need to be declared
Python is strongly typed – types are not implicitly coerced
Elements of Programming
Every powerful programming language has mechanisms for combining simple ideas to form more complex ideas:
primitive expressions and statements which represent the simplest building blocks that the language provides.
means of combination, by which compound elements are built from simpler ones, and
means of abstraction, by which compound elements can be named an manipulated as units.
Expressions
In programming, we deal with two kinds of elements:
data: the stuff that we want to manipulate
functions: describe rules for manipulating data
Python programs are composed of expressions, which are evaluated by the Python interpreter.
There are two main kinds of expressions:
primitive expressions, for example the number 42
compound expressions, for example 3 * 4
Call Expressions
The most important kind of compound expression is a call expression, which applies function to some arguments.
A call expression has subexpressions:
the operator is an expression that precedes parentheses, and
a comma delimited list of operand expressions.
Example:
max(7.5, 9.5)
The operator specifies the function
When the call expression is evaluate, we say that the function
max
is called with arguments 7.5 and 9.5 and returns a value of 9.5.
Function Notation vs. Mathematical Notation
Functions can take an arbitrary number of arguments instead of only two
max(1, -2, 3, -4)
Function notation extends to nested expressions.
max(min(1,2), min(pow(3, 5), -4))
Function notation only requires a name instead of the various forms of mathematical notation.
Running Python Code
The Python interpreter is the most basic way to execute Python code.
The interpreter can be started by typing
python
at the command prompt.$ python >>>
The interpreter can be used to evaluate Python expressions.
>>> 1 + 1 2 >>> x = 5 >>> x * 3 15
Self-contained Python Scripts
Python programs (scripts) are saved in files with a
.py
extension.Example: file named
test.py
with the contents# file: test.py print("Running test.py") x = 5 print("Result is", 3 * x)
A python file is run with the
python
filename command.$ python test.py Running test.py Result is 15
Syntax and Semantics
The syntax of a programming language refers to structure of the language, that is, what constitutes a legal program.
The semantics of a programming language refers to the meaning of a legal program.
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
Comments are denoted by
#
.The example program starts with the comment:
# set the midpoint
Anything after the
#
is ignored by the interpreter.Python has no syntax for multi-line comments.
The End-of-Line Terminates a Statement
The next line in the script is:
midpoint = 5
This is an assignment operation which binds the name
midpoint
to the value 5.The statement is marked by the end of the line
A statement can span multiple lines by using the backslash:
x = 1 + 2 + 3 + 4 +\ 5 + 6 + 7 + 8
or by placing the expression in parentheses:
x = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8)
Semicolon Optionally Terminates a Statement
The next part of the script is
lower = []; upper = []
The semicolon can be used to put multiple statements on the same line.
This is equivalent to
lower = [] upper = []
The use of semicolons in this fashion is generally discouraged in Python programming.
Indentation: Whitespace Matters
The main block of code in the program is:
for i in range(10): if (i < midpoint): lower.append(i) else: upper.append(i)
This is a compound control-flow statement.
Python blocks of code are denoted by indentation.
Python blocks of code are always preceded by a colon (
:
) on the previous line.Most style guides recommend indenting blocks by four spaces.
Whitespace Within Lines Does Not Matter
The following expressions are equivalent:
x=1+2 x = 1 + 2 x = 1 + 2
Most style guides recommend using a single space around binary operators and no space around unary operators.
Parentheses
Parentheses can be used for grouping or calling
Grouping statements or mathematical operations:
2 * (3 + 4)
Calling a function:
print('first value:", 1)
Some functions can be called with no arguments; but the parentheses are still needed.
L = [4, 3, 2, 1] L.sort() print(L)
Syntax and Semantics
The syntax of a programming language refers to structure of the language, that is, what constitutes a legal program.
The semantics of a programming language refers to the meaning of a legal program.
Variables
A Python variable binds a name to a value.
New bindings are established using the assignment statement:
# assign 4 to the variable x x = 4
Variable naming rules:
A variable name may include only the characters a-z, A-Z, 0-9, and the underscore
A variable name must start with a letter or an underscore
Variable names are case sensitive
Python Objects
Every value in Python is an object
Objects have attributes (state) and methods (behavior)
Syntax for using a method:
object.method([parameters])
Example:
>>> x = 4.5 >>> x.is_integer() False
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 |