Coding Bootcamp: Python tutorial

  • Adapted by the original online tutorial.

  • The material will give you an idea of the Python programming language.

The nature of Python

  • Python is an interpreted language.

  • It is available in all major platforms and runs anywhere from High Performance Computers (HPCs) to embedded devices.

  • It is a very popular choice for scientific computing and big data processing.

  • It is completely open source.

How can I get it?

  • The standard Python distribution is available at http://www.python.org.

  • Be sure to select the latest Python 3 version.

Running Python interactively

  • To get a first taste of Python, we will be using it interactively.

  • Start the IDLE program on your machine.

  • In the program's main console you can see a prompt:

    >>>
  • This is where you enter Python commands.

  • When you press Enter, the Python interpreter takes your input and executes it, then waits for new input.

Numbers

  • The interpreter acts as a simple calculator.

  • You can type an expression at it and it will write the value.

  • Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping.

In [1]:
2 + 2
Out[1]:
4
In [2]:
50 - 5*6
Out[2]:
20
  • Note that division always returns a floating point number.
In [3]:
8 / 5
Out[3]:
1.6
  • The integer numbers (e.g. 2, 4, 20) have type int.

  • Τhe ones with a fractional part (e.g. 5.0, 1.6) have type float.

Division

  • As we saw, division (/) always returns a float.

  • To do floor division and get an integer result (discarding any fractional result) you can use the // operator.

  • To calculate the remainder you can use %.

In [4]:
17 / 3
Out[4]:
5.666666666666667
In [5]:
17 // 3
Out[5]:
5
In [6]:
17 % 3 
Out[6]:
2
In [7]:
5 * 3 + 2 
Out[7]:
17

Precedence of operators

  • The arithmetic operators have the following precedence:

    • *, /, %: highest
    • +, -: lowest
  • To alter the default calculation order we can use parentheses.

In [8]:
2 * 3 + 4
Out[8]:
10
In [9]:
2 * (3 + 4)
Out[9]:
14
In [10]:
((1 + 2) * 3) * ((3 + 4) * 5)
Out[10]:
315

Powers

  • To raise to a power you use the ** operator.
  • This is $5^2$:
In [11]:
5 ** 2
Out[11]:
25
  • And this is $2^7$:
In [12]:
2 ** 7
Out[12]:
128
  • Be careful. The operator ** has higher precedence than unary minus (-), so:
In [13]:
-3 ** 2
Out[13]:
-9
In [14]:
(-3)**2
Out[14]:
9

Variables and assignment

  • A variable in programming is a name that refers to a value.

  • The = operator is used to assign a value to a variable.

  • In Python you do not need to declare the type of the variable.

  • You cannot use a variable before you assign a value to it.

  • The name of a variable can be as long as we like, cannot begin with a number, and cannot container spaces (we use _ instead).

In [15]:
width = 20
In [16]:
height = 5 * 9
In [17]:
width * height
Out[17]:
900
  • If a variable is not “defined” (assigned a value), trying to use it will give you an error:
n  # try to access an undefined variable
----> 1 n  # try to access an undefined variable

NameError: name 'n' is not defined
  • The following names cannot be used for variables, as they are reserved by Python.

  • They are called keywords.

False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise
  • True to its name, a variable can change its value.
In [18]:
radius = 10
area = 3.14 * radius**2
print("The area of circle with radius", radius, "is", area)
The area of circle with radius 10 is 314.0
In [19]:
radius = 20
area = 3.14 * radius**2
print("The area of circle with radius", radius, "is", area)
The area of circle with radius 20 is 1256.0
  • Note that it can be tricky to swap the values of two variables.
In [20]:
a = 10
b = 20
print("a = ", a, "b = ", b)
b = a
a = b
print("a = ", b, "b = ", b)
a =  10 b =  20
a =  10 b =  10
  • To swap the values of two variables we must use a third variable.
In [21]:
a = 10
b = 20
print("a = ", a, "b = ", b)
t = a
a = b
b = t
print("a = ", a, "b = ", b)
a =  10 b =  20
a =  20 b =  10
  • This is the standard procedure in most programming languages.

  • It also works, as you have just seen, in Python.

  • However, in Python we can also do more simply the following.

In [22]:
a = 10
b = 20
print("a = ", a, "b = ", b)
b, a = a, b
print("a = ", a, "b = ", b)
a =  10 b =  20
a =  20 b =  10

Numeric types

  • In Python, as in most programming languages, different kinds of numbers are represented by different types.

  • In general, different kinds of things are represented by different types, as will will see.

  • The two basic numeric types are integers and floating point.

  • There is full support for floating point.

  • Operators with mixed type operands convert the integer operand to floating point.

In [23]:
3 * 3.75 / 1.5
Out[23]:
7.5
In [24]:
7.0 / 2
Out[24]:
3.5

Integer ranges

  • In contrast to other languages, there is no limit on the size of an integer.

  • An integer will be calculated, as long as it fits in the memory available to Python.

In [25]:
2 ** 8192
Out[25]:
1090748135619415929462984244733782862448264161996232692431832786189721331849119295216264234525201987223957291796157025273109870820177184063610979765077554799078906298842192989538609825228048205159696851613591638196771886542609324560121290553901886301017900252535799917200010079600026535836800905297805880952350501630195475653911005312364560014847426035293551245843928918752768696279344088055617515694349945406677825140814900616105920256438504578013326493565836047242407382442812245131517757519164899226365743722432277368075027627883045206501792761700945699168497257879683851737049996900961120515655050115561271491492515342105748966629547032786321505730828430221664970324396138635251626409516168005427623435996308921691446181187406395310665404885739434832877428167407495370993511868756359970390117021823616749458620969857006263612082706715408157066575137281027022310927564910276759160520878304632411049364568754920967322982459184763427383790272448438018526977764941072715611580434690827459339991961414242741410599117426060556483763756314527611362658628383368621157993638020878537675545336789915694234433955666315070087213535470255670312004130725495834508357439653828936077080978550578912967907352780054935621561090795845172954115972927479877527738560008204118558930004777748727761853813510493840581861598652211605960308356405941821189714037868726219481498727603653616298856174822413033485438785324024751419417183012281078209729303537372804574372095228703622776363945290869806258422355148507571039619387449629866808188769662815778153079393179093143648340761738581819563002994422790754955061288818308430079648693232179158765918035565216157115402992120276155607873107937477466841528362987708699450152031231862594203085693838944657061346236704234026821102958954951197087076546186622796294536451620756509351018906023773821539532776208676978589731966330308893304665169436185078350641568336944530051437491311298834367265238595404904273455928723949525227184617404367854754610474377019768025576605881038077270707717942221977090385438585844095492116099852538903974655703943973086090930596963360767529964938414598185705963754561497355827813623833288906309004288017321424808663962671333528009232758350873059614118723781422101460198615747386855096896089189180441339558524822867541113212638793675567650340362970031930023397828465318547238244232028015189689660418822976000815437610652254270163595650875433851147123214227266605403581781469090806576468950587661997186505665475715792896

Other numeric types

  • Python has numeric types for fractions (Fraction) and for decimal numbers (Decimal).

  • The Decimal type is used for money, or any case where we need to calculate with exact decimal precision.

  • Python also supports complex numbers. The suffix j or J is used for the imaginary part: 3 + 4j.

First steps in programming: Fibonacci series

  • Of course, we can use Python for more complicated tasks than adding two and two together.

  • For instance, we can write an initial sub-sequence of the Fibonacci series as shown below.

  • If you have not seen it before, the Fibonacci series is a series of numbers starting with 0 and 1, where every number is the sum of the previous two numbers.

In [26]:
a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b
1
1
2
3
5
8
  • The first line contains a multiple assignment.

  • The variables a and b simultaneously get the new values 0 and 1.

  • On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place.

  • The right-hand side expressions are evaluated from the left to the right.

  • The while loop executes as long as the condition (here: b < 10) remains true.

  • In Python, like in many programming languages, any non-zero integer value is true; zero is false.

  • The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false.

  • The test used in the example is a simple comparison.

  • The standard comparison operators are written the same as in most other programming languages: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

  • Note the expression a, b = b, a+b.

  • The two assignments are executed at the same time.

  • We have seen that before: to swap two variables in python you only need x, y = y, x and not a temporary variable like in many other languages.

Indentation

  • Unlike most other languages, whitespace and indentation is important in Python.

  • The body of the loop is indented: indentation is Python’s way of grouping statements.

  • At the interactive prompt, you have to type a tab or space(s) for each indented line.

  • In practice you will prepare more complicated input for Python with a text editor.

  • All decent text editors have an auto-indent facility.

  • When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line).

  • Note that each line within a basic block must be indented by the same amount, otherwise you will get an error, or you will indicate an inner block.

Output

  • The print() function writes the value of the argument(s) it is given.

  • It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings.

  • Strings are printed without quotes, and a space is inserted between items, so you can format things nicely.

In [27]:
i = 256*256
print('The value of i is', i)
The value of i is 65536
  • The keyword argument end can be used to avoid the newline after the output, or end the output with a different string.
In [28]:
a, b = 0, 1
while b < 1000:
    print(b, end=',')
    a, b = b, a+b
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

Running Python scripts

  • However, most uses of Python involve writing Python programs, scripts, saved in files.

  • A Python file has by convention the extension .py, for example, foo.py.

  • To run such a program we enter python foo.py or python3 foo.py (depending on the details of our installation).

  • We must ensure that python or python3 is in the system's path.

  • When foo.py is run we'll see that a file foo.pyc is generated. That is a compiled file that does not contain executable machine code but some intermediate level code.

First steps in programming: perfect numbers

  • A perfect number is a number that is the sum of all its divisors, except for itself.

  • We do not currently know whether there are infinitely many perfect numbers.

  • Perfect numbers appear as early as as early Euclid's Elements (VII.22).

In [29]:
for test_number in range(1, 10000):
    sum = 0
    for i in range(1, test_number):
        if test_number % i == 0:
            sum += i
    if sum == test_number:
        print(test_number, "is a perfect number")
6 is a perfect number
28 is a perfect number
496 is a perfect number
8128 is a perfect number
  • The range(1, 10000) function produces the values 1, 2, ..., 9999.

  • In general, range(a, b) produces the values a, a + 1, ..., b - 1.

  • The simplified range(a) produces the values 0, 1, 2, ...., a - 1.

  • The if statement is a conditional statement.

  • If the condition that follows is true, the indented code below it will be executed.

  • Note also the sum += i expression.

  • This is a shortcut for sum = sum + 1.

  • In general, for an operator op, the expression x op= y means x = x op y.

First steps in programming: multiples of 2 or 3 up to 10

  • Let's suppose we want to write a program that checks the multiples of 2 or 3 up to 10.
In [30]:
i = 1
while i <= 10:
    if i % 2 == 0:
        print(i, "check")
    elif i % 3 == 0:
        print(i, "check")
    else:
        print(i, "is not a multiple of 2 nor 3")
    i += 1
1 is not a multiple of 2 nor 3
2 check
3 check
4 check
5 is not a multiple of 2 nor 3
6 check
7 is not a multiple of 2 nor 3
8 check
9 check
10 check
  • This time we use the if .. elif ... else construct.

  • The elif branch is executed if the condition of the if is not true, but the condition following it is true.

  • The else branch is executed when all other conditions are false.

  • Note that both elif and else are optional:

    • You may have if without else and elif
    • You may have if with elif but without else
    • You may have if with else but without elif

A small detour in computer arithmetic.

  • We mentioned before that Python offers the Decimal type when we want exact arithmetic calculations.

  • That is because computer arithmetic is not the same as school arithmetic.

  • Consider the following.

In [31]:
step = 0.1
total = 0
for i in range(1000):
    total += step
print(total)
99.9999999999986
  • The range(a) function produces the function 0, 1, 2, ..., a - 1.

  • So the above program adds 1000 times 0.1, which would produce $1000 \times 0.1 = 100$.

  • But in computers, this does not happen.

  • When we do need to be as accurate as normal arithmetic requires, we use mechanisms such as the Decimal type to which we referred.

  • We won't be needing it that now, but just be aware that computer arithmetic is not everyday arithmetic.

Input from the command line

  • To ask for input from the user on the command line, we use the input() function.

  • The function then reads a line from input and returns it to the program.

input_name = input("What's your name? ")
print("Hello,", input_name)
What's your name? Panos
Hello, Panos
  • Note that input() returns an object that is called a string.

  • We will have much more to say about strings in a bit.

  • For now, be aware that a string is not a number, even if it looks like a number.

input_radius = input("Give the circle radius: ")
area = input_radius**2 * 3.13
print(area)
Give the circle radius: 10

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-232c7e4563eb> in <module>()
      1 input_radius = input("Give the circle radius: ")
----> 2 area = input_radius**2 * 3.13
      3 print(area)

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
  • We need to convert the input to a number.

  • To convert to an integer, we use the int() function.

  • To convert to a floating point number, we use the float() function.

input_radius = input("Give the circle radius (must be integer): ")
area = int(input_radius)**2 * 3.14
print(area)
Give the circle radius (must be integer):10
314.0
input_radius = input("Give the circle radius:")
area = float(input_radius)**2 * 3.14
print(area)
Give the circle radius:12.3
475.0506000000001

Comments

  • In Python everything following the character # is a comment.

  • A comment is not executed by the computer.

  • It exists so that humans can understand a program.

  • They are an essential part of well-written programs: always include them in your programs!

In [32]:
# This is a comment

spam = 1  # and this is the second comment
          # ... and now a third!
  • Unless it is enclosed in quotes, in which case it is part of a string.
In [33]:
text = "# This is not a comment because it's inside quotes."
In [34]:
# Calculates the Fibonacci numbers up to 1000
a, b = 0, 1 # First two Fibonacci numbers are 0 and 1, by definition
while b < 1000:
    print(b, end=',')
    a, b = b, a+b
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

Exercises

Exercise 1

Write a program that produces the following output:

000000001
000000022
000000333
000004444
000055555
000666666
007777777
088888888
999999999

Exercise 2

Write a program that asks the user to provide different numbers of banknotes and coins, from €50 to €1. Then output the total sum in euros. For example:

Enter number of 50 euro banknotes: 10
Enter number of 20 euro banknotes: 20
Enter number of 10 euro banknotes: 30
Enter number of 5 euro banknotes: 40
Enter number of 2 euro coins: 50
Enter number 1 euro coints: 60
You have 1560 euros.

Exercise 3

If we want to calculate the area of a triange given its sides, we can use Heron's formula, which is: $$ A= \frac{1}{4}\sqrt{(a+b+c)(-a+b+c)(a-b+c)(a+b-c)} $$ where $a$, $b$, and $c$, are the three sides of the triangle. Write a program that asks the user for the three sides and calculates its area. Note that to calculate the square root in Python you have to include the line

import math

at the beginning of your program. Then, the square root of, say, r, is math.sqrt(r).

Exercise 4

A quadratic equation is an equation of the form:

$$ax^2 + bx + c$$

The roots of a quadratic equation are given by the formula:

$$x=\frac{-b\pm {\sqrt {b^{2}-4ac\ }}}{2a}$$

Note that if $b^2 - 4ac < 0$, then no real-valued solutions exist. Write a program that asks the user to enter values for $a$, $b$, $c$, then prints the solutions of the quadratic equation they define, if they exist. If they do not exist, it should output an appropriate message.

Exercise 5

Write a program that calculates the first five terms of the harmonic sequence, that is, the numbers: $$1$$ $$1 + \frac{1}{2}$$ $$1 + \frac{1}{2} + \frac{1}{3}$$ $$1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4}$$ $$1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \frac{1}{5}$$

These are the numbers:

1
1.5
1.8333333333333333
2.083333333333333
2.283333333333333

Exercise 6

The triangle or triangular numbers are given by the following formula: $$T_{n}=\sum _{k=1}^{n}k=1+2+3+\dotsb +n={\frac {n(n+1)}{2}}$$ So, the first six triangular numbers are: 0, 1, 3, 6, 10, 15, 21. Their name comes from the fact that it is the number of objects that we must use to form an equilateral triangle. Write a program that asks the user the number of triangular numbers to produce, then prints them out:

Enter number of triangle numbers: 9
1 3 6 10 15 21 28 36 45
Enter number of triangle numbers: 15
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120
Enter number of triangle numbers: 30
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 325 351 378 406 435 465

Exercise 7

The pronic numbers are those that are the product of two consecutive integers, so that they have the form $n(n + 1)$. For example, the first six pronic numbers are: $$ 1 \times 2 = 2$$ $$ 2 \times 3 = 6$$ $$ 3 \times 4 = 12$$ $$ 4 \times 5 = 20$$ $$ 5 \times 6 = 30$$ $$ 6 \times 7 = 42$$

Write a program that asks the user the number of pronic numbers to output, then goes on and prints them:

Enter number of pronic numbers: 10
2 6 12 20 30 42 56 72 90 110