Python basics

Objects, dir, help

  • Everything in Python is an object
  • Objects have attributes
  • Use TAB for autocompletion

Example: a list


In [1]:
a = ["Hello", "World", 42]

Type a., then press tab to see attributes:


In [ ]:

Alternatively, use the dir(a) command to see the attributes (ignore everything starting with __):


In [ ]:
dir(a)

Imagine we want to find out what the append attribute is: use help(a.append) or a.append? to learn more about an attribute:


In [3]:
help(a.append)


Help on built-in function append:

append(...) method of builtins.list instance
    L.append(object) -> None -- append object to end

Let's try this:


In [4]:
print(a)


['Hello', 'World', 42]

In [5]:
a.append("New element")

In [6]:
print(a)


['Hello', 'World', 42, 'New element']

Comments

Anything following a # sign is considered a comment (to the end of the line)


In [7]:
d = 20e-9   # distance in metres

Importing libraries

The core Python commands can be extened through importing additonal libraries.

import syntax 1


In [8]:
import math
math.sin(0)


Out[8]:
0.0

import syntax 2


In [9]:
import math as m
m.sin(0)


Out[9]:
0.0

Functions

A function is defined in Python using the def keyword. For example, the greet function accepts two input arguments, and concatenates them to become a greeting:


In [10]:
def greet(greeting, name):
    """Optional documentation string, inclosed in tripple quotes.
    Can extend over mutliple lines."""
    print(greeting + " " + name)

In [11]:
greet("Hello", "World")


Hello World

In [12]:
greet("Bonjour", "tout le monde")


Bonjour tout le monde

In above examples, the input argument to the function has been identified by the order of the arguments.

In general, we prefer another way of passing the input arguments as

  • this provides additional clarity and
  • the order of the arguments stops to matter.

In [13]:
greet(greeting="Hello", name="World")


Hello World

In [14]:
greet(name="World", greeting="Hello")


Hello World

Note that the names of the input arguments can be displayed intermittently if you type greet( and then press SHIFT+TAB (the cursor needs to be just to the right of the opening paranthesis).

A loop


In [15]:
def say_hello(name):             # function
    print("Hello " + name)

In [16]:
# main program starts here
names = ["Landau", "Lifshitz", "Gilbert"]
for name in names:
    say_hello(name=name)


Hello Landau
Hello Lifshitz
Hello Gilbert

In [ ]: