3. Python Syntax
"The syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be correctly structured statements or expressions in that language." Wikipedia
Syntax Summary
- Arithmetic Operators:
+(add),-(subtract),*(multiply),/(divide),**(exponent). (e.g. 700*20 see Arithmetic Operators) - Assignment operator
=(e.g.x = 100) - Comments: comment start with # and lasts to end-of-line. (e.g.
# this is a commentsee Comments) - Strings: string (text data) is declared by either single or double quotes. (e.g.
x = 'red') - Variable: A variable is created via initial assignments and can hold integer, float, string etc. (e.g.
y = 10.5see Variables) - Data Types: int (integers), float (decimals), str (string), bool (True or False) (e.g.
y = 5y is integer data typeint) -
Statements: Statements start at the left end (column one) of a line and end with a newline.
- Block statements are indented.
- Python is case sensitive.
- Comparison Operators: ==, != (not equal), <, <=, >, >=, in, not in, is, not is. (see Logical Comparisons)
- Logical Operators: and, or, not.
ifcondition: if line ends with a colon followed by indented block (see if Statements)Whileloop: while line ends with a colon followed by indented block (see thewhileloop examples in Chapter 4)forloop: for item in sequence ends with a colon with indented block (seeforLoop)- List:
lst = [v1, v2, …, vn]variable-size, mutable, dynamic array. (e.g.x = [22, 17, 50]see List) - Tuple:
tup = (v1, v2, v3,...)Immutable fix-sized array.(e.g.x = (22, 17, 50) - Dictionary:
dic = {k1:v1, k2:v2,...}mutable key-value pairs, associative array, map. (e.g.x = {'even': [2,4,6], 'odd': [1,3,5]})
Adapted from Python for Introductory Statistics, by Simon Aman (Truman College, City Colleges of Chicago), licensed under CC BY 4.0. Changes were made: reformatted as an accessible XYZ web edition with live in-browser code cells. License: CC-BY-4.0.