from IPython.core.display import HTML

HTML(open("custom.html", "r").read())
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright (C) 2014-2023 Scientific IT Services of ETH Zurich,
Contributing Authors: Uwe Schmitt, Mikolaj Rybniski

1. Basics: variables and a bit of math¶

  • print writes strings and values
  • a plain print() prints a line break aka "\n"
  • separate arguments with ,
print("values are", 1, 2, 3)
print()
print("done")
values are 1 2 3

done

Dynamic type system¶

Python requires no declaration of variable types, just assign values. Type of variable is determined from value on the right side of =:

a = 1.23
print(a * a)
1.5129

Check type of a variable with built in type function:

print(type(a))
<class 'float'>
b = 4711 * 42
print(type(b))
<class 'int'>
c = "I heart Python"
print(type(c))
<class 'str'>

Comments in Python¶

# this is a single line comment


"""
this is a 
multiline comment
"""

print(3)  # and a comment at the end of the line
3

Basic math¶

+, *, -, / and parenthesis as usual, ** for exponentiation:

print(2 * (3 + 4) - 7)
7
print(2 ** 10)
1024

The caret operator ^ also exists in Python (https://stackoverflow.com/questions/2451386/what-does-the-caret-operator-in-python-do) but does not compute exponentiation as in some other programming languages. So using ^ is syntactically correct, but might not compute the wanted result:

print(2 ^ 10)
8

In Python 3 (Python 2 was different) / always computes floating point division:

print(-7 / 2)
-3.5

Integer division (round down to the next integer) is //:

print(-7 // 2)
-4

% for modulo (aka division remainder) computation:

print(13 % 4)
1

We use % in a few examples in this script to check if a given number is a multiple of another number. For example 12 is a multiple of 4 because 12 % 4 is zero.

Further _ in numbers are ignored:

1_2_3_4.5_6
1234.56

The typical use case is to improve readability of larger numbers:

one_billion = 1_000_000_000

Math with the math module and how to import extension modules¶

  • Python ships with extra modules collected in the so called "Python standard library".
  • The documentation on http://python.org is complete but https://pymotw.com/3/ is more detailed and shows more examples.
  • Use import to use such modules.
import math
print(math)
<module 'math' from '/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload/math.cpython-310-darwin.so'>

Now functions and constants are "attached" to math (Python speak: "attributes" of "math"):

print(math.pi)
3.141592653589793
print(math.sin(1.0))
0.8414709848078965

Alternative ways to import functions, values, etc:

from math import e, log, pi, sin
print(log(e))
1.0

from math import * works, it imports everything (which might be a lot), but is dangerous, for example this overwrites a variable e:

e = 123
from math import *

print(e)
2.718281828459045
  • jupyter might remember imports, but for real programs Program execution starts with a fresh interpreter and you must import all needed modules.
  • It is best practice to list all imports at the beginning of a program

Getting help¶

Python also has a built-in help system:

print(help(math.sin))
Help on built-in function sin in module math:

sin(x, /)
    Return the sine of x (measured in radians).

None

Lets learn a bit more about print:

print(help(print))
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

None

Additionally jupyter has a shortcut for help by appending a ? or inserting a ? at the beginning:

print?
?print

Exercise session 1¶

  1. Use Python to compute the remainder of $2^{63}$ divided by $13$.
  2. Which number is larger: $\pi^e$ or $e^\pi$ ?
  3. Complete the following snippet to compute the area and circumference of a circle, also print the result (Reminder: for diameter $d$ the area is $\pi \frac{d^2}{4}$ and the circumference is $\pi d$.
diameter = 1.23

# compute area and circumference

# also print result
  1. Use help to figure out what math.hypot computes. What is the result of math.hypot(3, 4)?
  2. Run import this. (see also https://peps.python.org/pep-0020)

Optional exercises*¶

  1. Write a program which starts with values for $p$ and $q$ in the equation $x^2 + p x + q = 0$ and prints the solution(s): $$x = -\frac{p}{2} \pm \sqrt{\left(\frac{p}{2}\right)^2 - q}.$$

What $x$ do you get for $p=2$ and $q=1$ ? What happens if you use $p=1$ and $q=1$ ? 2. Use the module cmath instead of math for the preceeding exercise and test again with $p=1$ and $q=1$. 3. Compute math.hypot(1e300, 1e300). Now implement the same computation using the pythagorean theorem. and do the same computation again, what do you observe ? Can you explain your implementation and rewrite the formula to match the result of math.hypot(1e300, 1e300)?

A few more basics¶

Rebinding¶

You may reuse variable names in a script, the type might change:

a = 6
print(a, type(a))

a = 3.14
print(a, type(a))
6 <class 'int'>
3.14 <class 'float'>

Valid variable names:¶

  • start with lower or upper case letter or _
  • followed by lower or upper case letters or _ or digits
  • names of built-in functions allowed (but not recommended)
  • names of Python statements not allowed.
# those are fine:
a_b_c = 1
a123 = 2
_aXz = 3

# overwrite existin functions is not such a great idea, you see the different color ?
print = 19
type = 4

# bang, SyntaxError !
for = 3
  Cell In[29], line 11
    for = 3
        ^
SyntaxError: invalid syntax

Code style conventions¶

PEP 8 (https://www.python.org/dev/peps/pep-0008/) recommends:

  • use lower case letters and "_" unless you name classes:

    prefer this_is_a_long_name over thisIsALongName.

  • use "CamelStyle" only for class names

  • use space after , and spaces around operators like +.

  • further: use only lower case letters for file names

Naming conflicts¶

  • built in functions as type and statements as for may conflict with your preferred variable name
  • use type_ and for_ instead as names.

Integers do not overflow in Python:¶

x = 2 ** 62  # this can be represented by a 64 bit integer.
y = 2 ** 63  # this overflows in 64 bit integers
print(x, y)
4611686018427387904 9223372036854775808

There is no distinction between single or double precision floats, the Python float type is always with double precision, but may overflow:

print(2.0 ** 1000)
print(2.0 ** 1500)
1.0715086071862673e+301
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
Cell In[31], line 2
      1 print(2.0 ** 1000)
----> 2 print(2.0 ** 1500)

OverflowError: (34, 'Result too large')

Algebraic updates¶

x = 3
x += 3  # same as x = x + 3
x *= 2  # same as x = x * 2
x /= 4  # same as x = x / 4
print(x)
3.0

Everything is an object¶

Everything in Python is a so called "object" and can be assigned to variables:

import math

# assign module to a variable:
m = math
print(m.sin(m.pi))

# assign module function to a variable:
s = m.sin
print(s(0.0))

# assign built in function to a variable:

p = print
p(1.0)
1.2246467991473532e-16
0.0
1.0

Exercise section 2¶

Please try to answer the following questions using pen and paper. You can afterwards check your results by writing and running code:

  1. Which of the following are valid variable names: abc, a0, 0a, a_b, a.b, a$b, _a, _012? You can check your results on your own by writing Python code which assigns a value like 0 to these variables.### Check questions

  2. What is the result of 2 ** 4 % 11 // 2? How does the result change when you replace // by /?a

  3. What is the value of x?

      a = 3_0 // 20
      a = a * 3
      a += 1
      a -= 4
      x = 2 ** a