• JUPYTER
  • FAQ
  • View as Code
  • Python 2 Kernel
  • View on GitHub
  • Execute on Binder
  • Download Notebook
  1. ipython-notebooks
  2. notebooks
  3. language

Introduction To Python¶

This is a collection of various statements, features, etc. of IPython and the Python language. Much of this content is taken from other notebooks so I can't take credit for it, I just extracted the highlights I felt were most useful.

Code cells are run by pressing shift-enter or using the play button in the toolbar.

In [1]:
a = 10
In [2]:
print(a)
10
In [3]:
import math
In [4]:
x = math.cos(2 * math.pi)
print(x)
1.0

Import the whole module into the current namespace instead.

In [5]:
from math import *
x = cos(2 * pi)
print(x)
1.0

Several ways to look at documentation for a module.

In [6]:
print(dir(math))
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
In [7]:
help(math.cos)
Help on built-in function cos in module math:

cos(...)
    cos(x)
    
    Return the cosine of x (measured in radians).

Variables¶

In [8]:
x = 1.0
type(x)
Out[8]:
float
In [9]:
# dynamically typed
x = 1
type(x)
Out[9]:
int

Operators¶

In [10]:
1 + 2, 1 - 2, 1 * 2, 1 / 2
Out[10]:
(3, -1, 2, 0)
In [11]:
# integer division of float numbers
3.0 // 2.0
Out[11]:
1.0
In [12]:
# power operator
2 ** 2
Out[12]:
4
In [13]:
True and False
Out[13]:
False
In [14]:
not False
Out[14]:
True
In [15]:
True or False
Out[15]:
True
In [16]:
2 > 1, 2 < 1, 2 > 2, 2 < 2, 2 >= 2, 2 <= 2
Out[16]:
(True, False, False, False, True, True)
In [17]:
# equality
[1,2] == [1,2]
Out[17]:
True

Strings¶

In [18]:
s = "Hello world"
type(s)
Out[18]:
str
In [19]:
len(s)
Out[19]:
11
In [20]:
s2 = s.replace("world", "test")
print(s2)
Hello test
In [21]:
s[0]
Out[21]:
'H'
In [22]:
s[0:5]
Out[22]:
'Hello'
In [23]:
s[6:]
Out[23]:
'world'
In [24]:
s[:]
Out[24]:
'Hello world'
In [25]:
# define step size of 2
s[::2]
Out[25]:
'Hlowrd'
In [26]:
# automatically adds a space
print("str1", "str2", "str3")
('str1', 'str2', 'str3')
In [27]:
# C-style formatting
print("value = %f" % 1.0) 
value = 1.000000
In [28]:
# alternative, more intuitive way of formatting a string 
s3 = 'value1 = {0}, value2 = {1}'.format(3.1415, 1.5)
print(s3)
value1 = 3.1415, value2 = 1.5

Lists¶

In [29]:
l = [1,2,3,4]

print(type(l))
print(l)
<type 'list'>
[1, 2, 3, 4]
In [30]:
print(l[1:3])
print(l[::2])
[2, 3]
[1, 3]
In [31]:
l[0]
Out[31]:
1
In [32]:
# don't have to be the same type
l = [1, 'a', 1.0, 1-1j]
print(l)
[1, 'a', 1.0, (1-1j)]
In [33]:
start = 10
stop = 30
step = 2
range(start, stop, step)

# consume the iterator created by range
list(range(start, stop, step))
Out[33]:
[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
In [34]:
# create a new empty list
l = []

# add an elements using `append`
l.append("A")
l.append("d")
l.append("d")

print(l)
['A', 'd', 'd']
In [35]:
l[1:3] = ["b", "c"]
print(l)
['A', 'b', 'c']
In [36]:
l.insert(0, "i")
l.insert(1, "n")
l.insert(2, "s")
l.insert(3, "e")
l.insert(4, "r")
l.insert(5, "t")

print(l)
['i', 'n', 's', 'e', 'r', 't', 'A', 'b', 'c']
In [37]:
l.remove("A")
print(l)
['i', 'n', 's', 'e', 'r', 't', 'b', 'c']
In [38]:
del l[7]
del l[6]

print(l)
['i', 'n', 's', 'e', 'r', 't']

Tuples¶

In [39]:
point = (10, 20)
print(point, type(point))
((10, 20), <type 'tuple'>)
In [40]:
# unpacking
x, y = point

print("x =", x)
print("y =", y)
('x =', 10)
('y =', 20)

Dictionaries¶

In [41]:
params = {"parameter1" : 1.0,
          "parameter2" : 2.0,
          "parameter3" : 3.0,}

print(type(params))
print(params)
<type 'dict'>
{'parameter1': 1.0, 'parameter3': 3.0, 'parameter2': 2.0}
In [42]:
params["parameter1"] = "A"
params["parameter2"] = "B"

# add a new entry
params["parameter4"] = "D"

print("parameter1 = " + str(params["parameter1"]))
print("parameter2 = " + str(params["parameter2"]))
print("parameter3 = " + str(params["parameter3"]))
print("parameter4 = " + str(params["parameter4"]))
parameter1 = A
parameter2 = B
parameter3 = 3.0
parameter4 = D

Control Flow¶

In [43]:
statement1 = False
statement2 = False

if statement1:
    print("statement1 is True")
elif statement2:
    print("statement2 is True")
else:
    print("statement1 and statement2 are False")
statement1 and statement2 are False

Loops¶

In [44]:
for x in range(4):
    print(x)
0
1
2
3
In [45]:
for word in ["scientific", "computing", "with", "python"]:
    print(word)
scientific
computing
with
python
In [46]:
for key, value in params.items():
    print(key + " = " + str(value))
parameter4 = D
parameter1 = A
parameter3 = 3.0
parameter2 = B
In [47]:
for idx, x in enumerate(range(-3,3)):
    print(idx, x)
(0, -3)
(1, -2)
(2, -1)
(3, 0)
(4, 1)
(5, 2)
In [48]:
l1 = [x**2 for x in range(0,5)]
print(l1)
[0, 1, 4, 9, 16]
In [49]:
i = 0
while i < 5:
    print(i)
    i = i + 1
print("done")
0
1
2
3
4
done

Functions¶

In [50]:
# include a docstring
def func(s):
    """
    Print a string 's' and tell how many characters it has    
    """
    
    print(s + " has " + str(len(s)) + " characters")
In [51]:
help(func)
Help on function func in module __main__:

func(s)
    Print a string 's' and tell how many characters it has

In [52]:
func("test")
test has 4 characters
In [53]:
def square(x):
    return x ** 2
In [54]:
square(5)
Out[54]:
25
In [55]:
# multiple return values
def powers(x):
    return x ** 2, x ** 3, x ** 4
In [56]:
powers(5)
Out[56]:
(25, 125, 625)
In [57]:
x2, x3, x4 = powers(5)
print(x3)
125
In [58]:
f1 = lambda x: x**2
f1(5)
Out[58]:
25
In [59]:
map(lambda x: x**2, range(-3,4))
Out[59]:
[9, 4, 1, 0, 1, 4, 9]
In [60]:
# convert iterator to list
list(map(lambda x: x**2, range(-3,4)))
Out[60]:
[9, 4, 1, 0, 1, 4, 9]

Classes¶

In [61]:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def translate(self, dx, dy):
        self.x += dx
        self.y += dy
        
    def __str__(self):
        return("Point at [%f, %f]" % (self.x, self.y))
In [62]:
p1 = Point(0, 0)
print(p1)
Point at [0.000000, 0.000000]
In [63]:
p2 = Point(1, 1)

p1.translate(0.25, 1.5)

print(p1)
print(p2)
Point at [0.250000, 1.500000]
Point at [1.000000, 1.000000]

Exceptions¶

In [64]:
try:
    print(test)
except:
    print("Caught an expection")
Caught an expection
In [65]:
try:
    print(test)
except Exception as e:
    print("Caught an exception: " + str(e))
Caught an exception: name 'test' is not defined

This website does not host notebooks, it only renders notebooks available on other websites.

Delivered by Fastly, Rendered by OVHcloud

nbviewer GitHub repository.

nbconvert version: 7.16.6

Rendered (Mon, 01 Dec 2025 11:04:41 UTC)