Syntax#

In this section we’ll learn the basic Python syntax.

Table of Contents

Introduction#

Syntax is set of grammar and punctuation rules that define how to put words and symbols together to properly form a particular language.

In the English language for example, we know a sentence is made up of a subject and predicate, that the first letter should be capitalized, and that it should end in a period, question mark, or exclamation point.

Python is a programming language, intended to read by a computer. In order to write code that the computer can understand, we need to understand the syntax.

Structure#

A program is made up of a series of instructions which are read and executed in order from top to bottom.

To get a better idea of what is involved, lets consider the following simple example:

"""My first program"""

import time

width = 80
today = time.localtime()

greeting = "Hello"

if today.tm_hour < 11:
  greeting = "Good morning"  # before 12pm

# put together the message and make it centered
message = (greeting + " world!").center(width)

print(message)
                                  Hello world!                                  

Docstrings#

When the first line of a program or function is enclosed in triple single (''') or triple double (""") quotes, it is a special kind of string intended for documentation called a docstring.

1"""My first program"""

Comments#

You can leave notes for future reference starting with a #. This tells Python to ignore everything that follows until the end of the line.

1# put together the message and make it centered
2message = (greeting + " world!").center(size.columns)

A comment doesn’t have to be at the start of the line.

11if today.tm_hour < 11:
12  greeting = "Good morning"  # before 12pm

Keywords#

Keywords are reserved words that have a special meaning in Python. A keyword cannot be used as a function or variable.

1import time
2import shutil
11if today.tm_hour < 11:

A list of all keywords is available in the keyword module kwlist.

Show Keywords
  • False

  • None

  • True

  • and

  • as

  • assert

  • async

  • await

  • break

  • class

  • continue

  • def

  • del

  • elif

  • else

  • except

  • finally

  • for

  • from

  • global

  • if

  • import

  • in

  • is

  • lambda

  • nonlocal

  • not

  • or

  • pass

  • raise

  • return

  • try

  • while

  • with

  • yield

Statements#

Code is made up of a series of instructions to the computer called statements.

Listing 28 all statements#
 1"""My first program"""
 2
 3import time
 4
 5width = 80
 6today = time.localtime()
 7
 8greeting = "Hello"
 9
10if today.tm_hour < 11:
11  greeting = "Good morning"  # before 12pm
12
13# put together the message and make it centered
14message = (greeting + " world!").center(width)
15
16print(message)

The simple form is a single line of code, kind of like a sentence that says what to do.

Listing 29 a simple statement#
1"""My first program"""
2
3import time
See more
Listing 30 all simple statements#
 4width = 80
 5today = time.localtime()
 6
 7greeting = "Hello"
 8
 9if today.tm_hour < 11:
10  greeting = "Good morning"  # before 12pm
11
12# put together the message and make it centered
13message = (greeting + " world!").center(width)
14
15print(message)

Various kinds of compound statements are used to group together and control part of a program.

Syntax:
HEADER:
    BODY

HEADER

statement that dictates how or when BODY statements are to be executed

BODY

one or more indented statements controlled by HEADER

While the full header syntax depends on the statement, they all begin with a keyword and end with a colon (:).

Listing 31 header line#
11if today.tm_hour < 11:
12  greeting = "Good morning "  # before 12pm

Its body of statements are indented under the header.

Listing 32 indented body line#
11if today.tm_hour < 11:
12  greeting = "Good morning"  # before 12pm

Expressions#

A statement may contain one or more expressions, which is any piece of code that resolves to a value.

9greeting = "Hello"
See more
Listing 33 all expressions#
 1"""My first program"""
 2
 3import time
 4import shutil
 5
 6width = 80
 7today = time.localtime()
 8
 9greeting = "Hello"
10
11if today.tm_hour < 11:
12  greeting = "Good morning"  # before 12pm
13
14# put together the message and make it centered
15message = (greeting + "world!").center(width)
16
17print(message)

Parentheses can be used around part of an expression to control order of operation or grouping.

15message = (greeting + "world!").center(width)

Often more than one expression is needed to make a value.

One expression is then made up of two or more other expressions, each of which must be evaluated to produce a value, before being combined together into the final result.

They are evaluated in the order of inside outward then left to right.

Listing 34 step #1 innermost variables and literal values:
message = ("Hello" + "world!").center(80)
#
message = (greeting + "world!").center(width)
Listing 35 step #2 remaining inner expression:
message = ("Hello world!").center(80)
#
message = (greeting + "world!").center(width)
Listing 36 step #3 leftmost expression:
message = "Hello world!".center(80)
#
message = (greeting + "world!").center(width)
Listing 37 step #4 next expression to the right:
message = "                                  Hello world!                                  "
#
message = (greeting + "world!").center(width)

Values#

Every value has a type and each type has its own syntax. Let’s take a look at the following example with a summary of the simple types and how variables are saved.

greeting = "Hello." # string         (str)
health = 100        # integer        (int)
delay = 0.1         # floating point (float)
verbose = True      # boolean        (bool)
winner = None       # NoneType

# list (list)
letters = ["a", "b", "c", "d", "e", "f"]

# dictionary (dict)
numbers = {
  "I": 1,
  "II": 2,
  "III": 3,
  "IV": 4,
  "V": 5,
}

print(greeting)
Hello.

Variables#

Save a value to be easily used later in the code by giving it a name. To create a variable simply assign a value to it it using the equals sign (=).

Syntax: NAME = VALUE

1greeting = "Hello." # string         (str)
2health = 100        # integer        (int)
3delay = 0.1         # floating point (float)
4verbose = True      # boolean        (bool)
5winner = None       # NoneType

To reference a variable, or retrieve the data you stored, use the variable name.

7print(greeting)

Assign multiple variables at once by putting the same number of variables on the left of the equals sign as values on the right, separated by commas.

Syntax:
NAME1, NAME2... = VAL1, VAL2...

red, green, blue = 0, 255, 125

Or the same number of variables on the left of the equals sign as elements in a sequence such as a list.

Syntax: NAME1, NAME2... = SEQUENCE

x, y = [-10, 10]

Bracket notation#

Many container types (like lists and dictionaries) support the use of subscription or bracket notation to select elements from the collection. Add square brackets ([ ]) after a value enclosing a selector expression.

Syntax: VALUE[EXPRESSION]

Depending on the type, a selector expression may be a negative or positive index number

letters[0]
letters[-1]

… a key

numbers["IV"]

…or a slice.

letters[2:4]

As with any expression, variables can be used in selector expressions.

idx = 2
letters[idx]
letters[idx:]

Bracket notation is most often used on a variable, but in fact it can be used on any expression that results in a type that supports it.

"hello"[2]
list("abc")[-1]
{"a": 1}["a"]

Dot notation#

Use dot notation to access members of a given value by adding a period (.) after a value followed by the member name.

Syntax: VALUE.MEMBER

letters.sort()

While dot notation is most often used on a variable, it can actually be used on any expression.

"hello".upper()

This means it is possible to chain or string together multiple attribute references, as long as each consecutive member returns a value.

name = input("Full Name: ").title().strip()

Calls#

Call a function by adding a set of parenthesis after the name.

Syntax: NAME()

print()

Put arguments inside the parenthesis.

Syntax: NAME(ARG)

print("Welcome!")
Welcome!

Separate multiple arguments with commas.

Syntax: NAME(ARG1, ARG2...)

name = "Mario"
print("Welcome", name)
Welcome Mario

Types#

Lets take a closer look at the standard built in types.

Name

Type

Description

Examples

A single value None with the first letter capitalized. Used to indicate that the value has not been set.

None

bool

Either True or False with the first letter capitalized.

True
False

int

Whole numbers.

10
0
-55

float

Numbers with a decimal point.

.1
1.5
-0.25

str

Text data enclosed in either single or double quotes.

"Hello"
'Goodbye'

list

An ordered collection of arbitrary objects seperated by commas and enclosed in square brackets ([ ]).

[]
[1, 2, 3]

dict

A collection of key: value pairs seperated by commas and enclosed in curly braces ({ }).

{}
{"a": 1, "b": 2, "c": 3}

tuple

An ordered, immutable collection of arbitrary objects seperated by commas and enclosed in parenthesis (( ))

()
(1,)
(1, 2, 3)
1, 2, 3

set

An unordered collection of unique elements seperated by commas and enclosed in curly braces ({ }).

set()
{1, 2, 3}

Strings#

Strings store text data and can be enclosed in either single or double quotes.

""
"Hello."
'Farewell.'
"It's a lovely day."
'"Well hello!", he said.'
'"Well hello!", he said.'

For a string that spans multiple lines, enclose it in triple double (""") or triple single (''') quotes.

rhyme = """Roses are red,
Violets are blue,
Sugar is sweet,
And so are you."""

print(rhyme)
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.

To break long text into multiple lines of code, put strings on consecutive lines (without separating commas) and enclose the whole expression in parentheses ( ).

text = (
  "Lorem ipsum dolor sit amet, consectetur "
  "adipiscing elit, sed do eiusmod tempor "
  "incididunt ut labore et dolore magna "
  "aliqua. Ut enim ad minim veniam, quis "
  "nostrud exercitation ullamco laboris "
  "nisi ut aliquip ex ea commodo consequat."
)

print(text)
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Backslashes (\) are used to escape quotes or to indicate special characters, like \n for a new line.

print('It\'s a nice day.')
print("line one\nline two")
It's a nice day.
line one
line two

For strings that contain backslashes use a double backslash (\\) or prefix the string with the letter r for a raw string.

print('"\\n" is used to add a newline')
print(r"C:\Documents\nodes")
"\n" is used to add a newline
C:\Documents\nodes

Strings can be concatenated (joined together) by using the + operator.

String literals (the ones in quotes) next to each other are automatically concatenated.

name = "coding class"
print("Welcome to " + name + ".")

text = "Today we're talking about" 'strings.'
print(text)
Welcome to coding class.
Today we're talking aboutstrings.

Use an f-string for string interpolation by prefixing the string with the letter f then enclose the variable or other evaluated code curly braces ({ }).

price = 1.25
count = 5

print(f"I am buying {count} apples for ${price} each.")
print(f"The total is ${price*count}.")
I am buying 5 apples for $1.25 each.
The total is $6.25.

Lists#

A list is an ordered collection of arbitrary objects.

To create one, enclose comma-separated values in square brackets
([ ]), or an empty pair of square brackets for an empty list.

[]
[1, 2, 3]
[1, 2, 3]

Long lists can be split onto multiple lines after the commas.

rainbow = [
  "red",
  "orange",
  "yellow",
  "green",
  "blue",
  "indigo",
  "purple",
]

List elements are primarily accessed, changed, or removed using subscription via either index numbers or slices.

# changing
rainbow[-1] = "violet"

# removing
del rainbow[-2]

# accessing
print(rainbow[0])
print(rainbow[-1])
print(rainbow[0:3])
red
violet
['red', 'orange', 'yellow']

Dictionaries#

A dictionary is a collection of key value pairs.

To create one, enclose comma-separated key value pairs in curly braces ({ }) with a colon (:) between each key and value. Or use an empty pair of curly brackets to make an empty dictionary.

pet = {}

garfield = {"name": "garfield", "kind": "cat", "color": "orange"}

Long dictionaries can be split onto multiple lines after the commas.

toothless = {
  "name": "Toothless",
  "kind": "dragon",
  "color": "black",
  "pic": "/|\\{O_O}/|\\",
  "age": 24,
}

List elements are primarily accessed, added, changed, or removed using subscription via keys.

# changing
garfield["name"] = "Garfield"

# adding
garfield["pic"] = "(=^o.o^=)__"

# removing
del toothless["age"]

# accessing
print(toothless["name"], ":", toothless["pic"])
print(garfield["name"], ":", garfield["pic"])
Toothless : /|\{O_O}/|\
Garfield : (=^o.o^=)__

Tuples#

A tuple is an immutable collection of arbitrary objects.

To create one, enclose comma-separated values in parenthesis
(( )), or an empty pair of parenthesis for an empty tuple.

()
(1, 2, 3)
(1, 2, 3)

A tuple can also be created using comma separated values without the parenthesis.

1, 2, 3
(1, 2, 3)

Though parenthesis are required when splitting tuples onto multiple lines.

words = (
  "target",
  "specify",
  "incline",
  "college",
  "forget",
  "recent",
)

Creating a tuple with only one item is a bit tricky, since parenthesis are used for both expression grouping and tuples.

Use a trailing comma to create a tuple with one item.

# parens are interpreted as grouping
# so this is an int instead of a tuple
(1)
1
# use a trailing comma to create a tuple
# with one item
nums = (1,)
print(nums)

# with or without the parenthesis
nums = 1,
print(nums)
(1,)
(1,)

Tuple elements are accessed using subscription via index numbers or slices.

print(words[0])
print(words[-1])
print(words[0:3])
target
recent
('target', 'specify', 'incline')

Tuples are immutable, so items cannot be modified or removed.

Sets#

A set is an unordered collection with no duplicate elements.

To create one, enclose comma-separated values in curly braces
({ }).

{1, 2, 3, 3, 2, 1}
{1, 2, 3}

Since curly braces are also used for dictionaries, use set() to create an empty set.

set()
set()

Sets are unordered, so subscription is not supported.

Flow Control#

if statements#

If statements are used to only execute code under certain conditions.

If statements always start with an if clause.

Syntax:
if CONDITION:
    BODY

CONDITION

an expression evaluated in a boolean context

BODY

statements to execute if CONDITION evaluates to True

In this example, "Would you like a beer?" will only be printed if age >= 21.

 1import random
 2
 3age = random.randint(1, 99)
 4
 5if age >= 21:
 6  print("Would you like a beer?")
 7elif age >= 12:
 8  print("Would you like a soda?")
 9elif age >= 5:
10  print("Would you like a juice?")
11else:
12  print("Hello.")
13

An if statement may contain zero or more elif clauses.

Syntax:
elif CONDITION:
    BODY

This example contains two elif clauses.

 1import random
 2
 3age = random.randint(1, 99)
 4
 5if age >= 21:
 6  print("Would you like a beer?")
 7elif age >= 12:
 8  print("Would you like a soda?")
 9elif age >= 5:
10  print("Would you like a juice?")
11else:
12  print("Hello.")
13

And an if statement may optionally end with an else clause. These body statements will be executed if none of the previous conditions are met.

Syntax:
else:
    BODY

BODY

statements to execute if all previous CONDITIONs are False

In this example, "Hello." is printed if all preceding conditions evaluated to False.

 1import random
 2
 3age = random.randint(1, 99)
 4
 5if age >= 21:
 6  print("Would you like a beer?")
 7elif age >= 12:
 8  print("Would you like a soda?")
 9elif age >= 5:
10  print("Would you like a juice?")
11else:
12  print("Hello.")
13

for loops#

For loops are used to iterate over every element in a sequence and repeat a block of code each time.

Syntax:
for VAR in ITERABLE:
    BODY

VAR

variable name (or comma-separated list of names) to assign each item to

ITERABLE

object to iterate over.

BODY

statements to execute where VAR will be used

1for word in ["apple", "banana", "cherry"]:
2    letter = word[0].upper()
3    print(f"{letter} is for: {word}.")

while loops#

A while loop is used to repeat a block of code as long as an expression evaluates to True.

Syntax:
while CONDITION:
    BODY

CONDITION

an expression evaluated in a boolean context that determines if the loop keeps going

BODY

statements to execute each iteration

1name = ""
2
3while not name:
4  name = input("What is your name? ")
5
6print(f"Hello there {name}!")
7

Functions#

A function is a set of Python instructions or statements that can be executed, or called, later.

Syntax:
def NAME(PARAMS):
    BODY

NAME

name of the function

PARAMS

zero or more comma separated names for variable arguments

BODY

statements to execute each time the function is called

1def line():
2  print("---------------------------")
3
4def see(pet):
5  line()
6  print(pet["name"], "the", pet["color"], pet["kind"])
7  print(pet["pic"])
8

Reference#

Glossary#

Syntax#

chaining#
method chaining#

Stringing together multiple dot notation attribute references.

comment#

Parts in a source-code file which are ignored when the program is run. In Python add a # to the beginning a line to indicate that it is a comment. You can also comment out only part of a line by adding # followed by the comment text to the end of an expression. It is recommended to follow the # by a single space before the text of the comment.

keyword#

Reserved words that have special meanings in a programming language so that they cannot be used as an identifier. Some examples of keywords in Python are for, if, and def.

syntax#

A set of rules that determine how a programming language is understood by the computer. Grammar, but for code.

assign#

A statement that sets the value of a variable name.

identifier#

The name that refers to a some programming element, such as a variable, class, function or module.

variable#

A name given to a value.

See also#