Login
📚 Python for Introductory Statistics
Chapters ▾

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

  1. Arithmetic Operators: + (add), - (subtract), * (multiply), / (divide), ** (exponent). (e.g. 700*20 see Arithmetic Operators)
  2. Assignment operator = (e.g. x = 100)
  3. Comments: comment start with # and lasts to end-of-line. (e.g. # this is a comment see Comments)
  4. Strings: string (text data) is declared by either single or double quotes. (e.g. x = 'red')
  5. Variable: A variable is created via initial assignments and can hold integer, float, string etc. (e.g. y = 10.5 see Variables)
  6. Data Types: int (integers), float (decimals), str (string), bool (True or False) (e.g. y = 5 y is integer data type int)
  7. 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.
  8. Comparison Operators: ==, != (not equal), <, <=, >, >=, in, not in, is, not is. (see Logical Comparisons)
  9. Logical Operators: and, or, not.
  10. if condition: if line ends with a colon followed by indented block (see if Statements)
  11. While loop: while line ends with a colon followed by indented block (see the while loop examples in Chapter 4)
  12. for loop: for item in sequence ends with a colon with indented block (see for Loop)
  13. List: lst = [v1, v2, …, vn] variable-size, mutable, dynamic array. (e.g. x = [22, 17, 50] see List)
  14. Tuple: tup = (v1, v2, v3,...) Immutable fix-sized array.(e.g. x = (22, 17, 50)
  15. Dictionary: dic = {k1:v1, k2:v2,...} mutable key-value pairs, associative array, map. (e.g. x = {'even': [2,4,6], 'odd': [1,3,5]})

Reference

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.