Lesson 1: Python Fundamentals

Purpose: To introduce fundamental concepts of the Python language.
Important terms: Number, stings, lists, variables.
Datatypes.
Work procedure: You are encouraged to discuss the work with others but you should write your own code!
Estimated working time: < 1 hour.
Examination: No mandatory examination. If you are having trouble understanding parts of the material or have other questions, feel free to grab a teaching assistant and ask.

First steps

Python is installed on all Linux computers at ITC.

If you are planning on using your own computer during the lessons, this video by Corey Schaffer will walk you through installing Python 3 on both Mac and Windows computers. Note that both Linux and Mac computers probably already have a version of Python installed, but it is recommended that you install and use the latest version of Python.

(Note: In the video, Schaffer edits a file called .bash_profile. This file may be called .profile instead on your computer.)

After you've installed Python on your computer, you can start Python by typing python3 in a terminal. It will look something like the following:

Python interpreter start.

You can now write Python commands in the terminal after the prompt (the >>> at the start of the last line).

Tips: You can use the 'up arrow key' and 'down arrow key' on your keyboard to cycle through commands executed in both the Python interpreter and in the terminal.

Note: The above text is only guaranteed to work on the Linux computers at ITC. You may only need to write python on your computer. However, it is important that you use Python 3.6 or a newer version, and not Python 2, when running you code. It is recommended that you use Python 3 during this course.

Closing the Interpreter

To close the Python interpreter, input either exit() or quit() like any other Python command. Pressing the key combination ctrl-D will also close the interpreter.

Arithmetic Expressions

Numbers are expressed as normal except that the dot character ('.') is used as the decimal separator.
Arithmetic operators: +, -, *, /, //, % and **.

The first four operator work as expected. The // is the 'integer devision' operator, the % is the modulo operator and the ** is the power operator.

You are encouraged to test the above mentioned operators. Below you can see examples of valid arithmetic operations in Python.

Operation Comment
4 + 3*5 - 2*2 Normal order of operations, i.e. * and / before + and -.
4 + 3*(5-2)*2 Operations inside of a parenthesis are performed before operations outside of the parenthesis.
4+2+1
4+2+1. Like the command above but with a decimal number.
5/2 Normal division operation.
5//2 Integer division operation.
-5//2 Integer division.
-(5//2) This operation has a different result than the previous operation!
37%10 Modulo operation.
1234567//1000%10 Forth number from the end.
1/0
3e2 + 1e4 + 2.5e-2 3·102 + 1·104 + 2.5·10-2
3*10**2 + 10**4 + 2.5*10**-2 Same operation as above but less elegant.
0.1*0.1 This might not behave as expected...
10**1000
10.**1000
-1**0.5 Power operator befor negation.
(-1)**0.5 Negation before power operation.

Observations

  1. In Python (and other programming languages) there are two different types of numbers: integers numbers and float numbers. Integer numbers are all numbers without a decimal part, while float numbers may have a decimal part. These two different kinds of numbers are said to be different datatypes. The name of the datatypes are int and float respectively.
  2. If an operation has at least one operator that is a float, then the result of the operation will also be a float.
  3. If all operands of an operation are integers, the result of the operation will also be an integer except if it is the division operation (/). The result of a division operation is always a float.
  4. It is very import to know the order of operations in a Python command.
  5. Computers don't always give the correct result! Python's integer operations are correct but any float operations may have rounding errors.
  6. There appears to be an upper limit to how large a float number can be, however, there seems to be no such limit for integer numbers.
  7. As seen in the last example, you can use complex numbers in Python but we won't be using them in this course.

Exercises

Use Python to answer the following questions.
  1. How many seconds are there in a year? Answer
    Input:
     >>> 365*24*60*60 
    which will give you the answer 31536000.
  2. If you put 1 kr in a bank that has an interest rate of 2 percent per year. How many kronor will you have after 2000 years?
    Answer
    Input:
    >>> 1.02**2000 
    which will give you the answer 1.586147327603768e+17 kronor.

Variables and declarations

In Python, a variable is a named unit of data containing a value.

  1. Variables are created by using a declaration statement: variable name = expression. In Python, a variable always has a value.
  2. After a variable has been declared, it can be used in operations instead of numbers. The operation uses the value stored in the variable when it's executed.
  3. A variable's value can be re-declared by using the declaration statement.
  4. A variable's name can contain letters, numbers and the underscore character (_). The first character must not be a number and variable names are case sensitive, e.g. page and Page are different variable names.
  5. As of Python version 3, variables can be named using national letters (e.g. â, å, å, ö, ç, é, è, ï, ...) but using them makes code written harder to read and even harder to maintain and as such we recomend that you only use english letters.

    Variables with names starting with underscores (_) have special meaning in some contexts.

  6. In our examples we've used very short variable names. When writing production code it is very important to use descriptive variable names, e.g. weekday, lines_per_page and numer_of_convolutioins.

    Note that the variables in Python follow a naming convention called snake case. Variable names use underscores (_) instead of spaces.

Try the following statements in order:

Try!
i = 2
x = 4.5
y = i*x
y = i*y
x = i + 2

By typing a variable's name at the prompt in the Python interpreter and pressing enter, the variable's data will be printed. In the examples above, i is declared as an integer datatype, y is declared as a floating point datatype and x is at first declared as a floating point datatype but is declared as an integer datatype at the end.

You can print the i, x and y variables by using this statement: print(i, x, y).

Try!
x = 2
x += 4
x
x *= 2
x
x -= 11
x
x /= 2
x

The statement x += 4 increments the value stored in x by 4. It is equivalent to x = x + 4 .

( Note: If you previously programmed using C, C++, Java or a similar language, you might have used the operators ++ and -- . They don't exist in Python. If you use them by accident you might not be given an exception. For example, 3 + ++x is a legal statement in Python but does not behave as you might expect it to. Try to figure out what is happening when you run that statement in Python.)

Mathematical functions

The package math contain mathematical functions. To be able to use the functions in the package, use the statement import math.

Example: Calculate the hypotenuse of a right triangle.

Try!
import math
k1 = 3
k2 = 4
hyp = math.sqrt(k1*k1 + k2*k2)
hyp

Example of other functions in math are sin, cos, exp och log. The trigonometric functions use radians and log is the natural logarithm.

The statement dir(math) produces a list of functions and constants in the package. The statement help(math) prints a help document for the packages, if there is one. If the statement prints Squeezed text, double click the text and you will see the entire help document.

You can find more information in the official documentation!

The package math also contains the variables pi and e. To get the values stored in the variables, use the statements math.pi and math.e.

If you, for example, use the math.sqrt() function from math repeatedly, you may want to be able to use it without writing the package's name every time you use it. Using this import statement

from math import sqrt
will allow you to do just that.

If you're using many functions from the packages, the following statement will import all functions and you can use them without the math. prefix.

from math import *

However, it is recommended that you use the full expression since it will make it more explicit what functions you are using.

Strings

Strings is another datatype in Python and it has the following attributes:

Examples:

Try!  Comments  
name = 'Kalle' family_name = 'Andersson' age = '12'
full_name = name + " " + family_name Concatenation  
full_name + " är " + age + " år"

Assign the variable age the numerical value of 12 and try the last statement again. Remember that you can use the arrow keys to cycle through previously executed expressions (if you are working from the IDLE interpreter, you might need to set the history-next and history-previous shortcuts in Options -> Configure IDLE -> Keys).

After changing age to the numerical value of 12, the expression can't be executed by Python. This shows that you can't mix datatypes arbitrarily. Although the + operator is defined on both strings and numbers it can't operate on a mix of the two datatypes. In order to get the expression to work as intended, you need to use type conversion to convert the variables into the appropriate datatypes.

f-strings

As of Python 3.6, a better alternative to formatting strings has been introduced: f-strings.

A f-string is declared using normal string notation prefixed with a lower- or uppercase f, e.g. f"text" or f'more text'.

By following the example bellow, we achieve the same formatting as in the table above.

Try!  Comments  
name = 'Kalle' family_name = 'Andersson' age = 12

Integer datatype.
full_name = f'{name} {family_name}'
f'{full_name} is {age} years'

When declaring a f-string, the variables given inside of a pair of curly brackets will be inserted into the new string and any type conversion will be handled automatically. Using f-strings results in shorter and more readable code.

The contents inside of {} are not limited to variable names but may also be general expressions. For example:

f'{x} squared is {x*x}'

Lists

In python, a list is a set of arbitrary values that may be of different datatypes. One way of creating a list is by listing the values to be stored in the list inside of a pair of square brackets, using commas to separate the values, e.g. a_list = [1, 2.0, 'three']. Square brackets are also used to access the values stored in a list. This is done by putting the index of the desired list element in the square brackets. The index of the first element of a list is zero.

Expression Value Comment
x = 4 n = [2, 3, x, x*x] [2, 3, 4, 16]
A list of integers.
n[0] + n[3] 18 Addition with the first and last element of the list.
n[1] = n[2] + 3 n [2, 7, 4, 16] Elements can be assigned new values.
n.append(25) n [2, 7, 4, 16, 25] You can append new elements onto a list.
Note the syntax!
len(n) 5 The len function gives you the length of a list.
['Eva', 'Åke'] A list of strings.
['Eva', 22, 'Åke', 24] A list with mixed datatypes.

Note how we used expanded the list by using append! Lists has a number of methods associated with it, where append is one of them. Methods are used to get information regarding an object or to modify it in some way. We will present other methods on both lists and other datatypes later on in the course.

Lists are a very powerful tool in Python and can be used in many different contexts.

Type conversions

To convert a value from one datatype to another, write the name of the datatype you want to convert to (int, float, str, etc.) followed by the expression you want converted inside of parenthesis, e.g. int(1.23).

Example:
Expression Value Comment
str(12) '12' Integer to string.
str(-12.5) '-12.5' Float to string.
str([1, 2, 3]) '[1, 2, 3]' List to string.
list('abc') ['a', 'b', 'c'] String to list
int('12') 12 String to integer.
int(12.8) 12 Float to integer. Decimals are truncated!
float('12.8') 12.8 String to float.

The str function can convert all datatypes while the int and float functions will not work if the argument given can't be interpreted as a number, i.e. the expression float('1x42') will produce only an error message.

Type conversion can be done anywhere inside of an expression. For example:

'Answer: ' + str(100*(1//n + int(math.exp(x))))

Questions and exercises

  1. When converting from a floating point number to an integer the value is truncated. However, if you wanted the number to be rounded to the closest whole number instead of truncated, how might one do that? Answer
    int(x + 0.5)    (presupposes that x ≥ 0)
    There also exists a function round that rounds a floating number.
  2. What datatypes have you seen in this lesson? Answer
    int for integer numbers,
    float for floating point numbers,
    str for strings and
    list for lists.
  3. What arithmetic operations have you seen this lesson? Answer
    +, -, *, /, //, %, **,
    +=, -=, *=, /=, %=
  4. What is the difference between integer and floating point arithmetic? Answer
    Integers always have the exact value and integer arithmetic always give the exact results.
    Floating point numbers can't always be represented exactly and floating point arithmetic can suffer from rounding errors.
  5. What happens if you use both integers and floats in the same expression? Answer
    In Python, all operation are done in isolation. If both operands are the same the result of the operation will have the same type as the operands. However, if one operand is a float and the other a int, then the integer is converted to a float and after that it operation is performed and the result is stored as a float.
    An exception to this is /, whose output always is a float.
    Example: The expression
      float(1//2 + int(3/2 + 2)) 
    results in the value 3.0.
  6. What does the math module contain? How is it used? Answer
    A set of mathematical functions, i.e. sin, cos, exp, log, etc.
    In order to use the functions, the module must be imported.
  7. What is a variable and what are its attributes? Answer
    A variable has a name and a value.
    The value (as well as the type) can be changed using the assignment operator =.
  8. Which type conversions can be done automatically? Answer
    From int to float.
  9. How can you perform explicit type conversions? Answer
    By using the functions int, float and str.
    Example:
    x = int(10*math.sin(z)) 
    ans = 'The answer is ' + str(x)
    
  10. Assign a variable x to contain a span of time expressed in months.
    Write a line of code that prints x in the number of years and months that x represents, ignoring leap years.
    Example: If x is assigned 208, then the output should be 17 years and 4 months.
    Try the line of code with different values of x. Answer
      x = 208 
      str(x//12) + ' years and ' + str(x%12) + ' months'
    
    or
      print(x//12, ' years and ', x%12, ' months')
    
    or, using f-strings,
      f'{x//12} years and {x%12} months'
    

Next lesson.

Valid CSS!