DATA PROCESSING
PC04 Expressions .................................................................................................................................................................................3
Data types..........................................................................................................................................................................................3
PC05 Variables .....................................................................................................................................................................................3
Soft typing .........................................................................................................................................................................................3
PC06 Simple Functions ........................................................................................................................................................................3
Calculation functions ........................................................................................................................................................................3
Modules (math, random) ...................................................................................................................................................................3
PC07 Conditions ...................................................................................................................................................................................4
Boolean expressions (True and False) ..............................................................................................................................................4
Conditional statements (if and elif)...................................................................................................................................................4
PC08 Iterations......................................................................................................................................................................................4
While loops .......................................................................................................................................................................................4
For loops ...........................................................................................................................................................................................4
Loop control statements (else, break, continue) ...............................................................................................................................4
Nested loops ......................................................................................................................................................................................5
The loop-and-a-half (while True) .....................................................................................................................................................5
PC09 Functions .....................................................................................................................................................................................5
Return ................................................................................................................................................................................................5
Difference return and print................................................................................................................................................................5
Main() ...............................................................................................................................................................................................5
PC11 Strings .........................................................................................................................................................................................5
Multiline strings (\n\) ........................................................................................................................................................................5
Accessing characters of a string ( eg [0:5:2] ) ..................................................................................................................................5
Reversing a string by using step size ................................................................................................................................................6
Strings are immutable .......................................................................................................................................................................6
String methods (strip(), upper(), lower(), find(), replace(), split(), join()) .......................................................................................6
Character encoding with ASCII (ord() and chr()).............................................................................................................................6
PC12 Tuples ..........................................................................................................................................................................................6
Tuples and coordinates .....................................................................................................................................................................7
PC13 Lists .............................................................................................................................................................................................7
Lists are mutable ...............................................................................................................................................................................7
List methods (append(), extend(), insert(), remove(), pop(), del, index(), count(), sort(), reverse(), list()) .....................................7
Aliasing and id() ...............................................................................................................................................................................7
Deep copies to copy lists and their sublists ......................................................................................................................................8
Nested lists (board games) ................................................................................................................................................................8
PC14 Dictionaries .................................................................................................................................................................................8
Dictionary methods (copy(), keys(), values(), items(), get()) ...........................................................................................................8
Storing complicated values (example courses and student numbers) ...............................................................................................8
Lookup speed ....................................................................................................................................................................................8
PC16 Operating System ........................................................................................................................................................................9
os functions (getcwd(), chdir(), listdir(), system())...........................................................................................................................9
PC17 Text Files ....................................................................................................................................................................................9
Reading text files (open(), read(), close(), readline(), readlines()) ...................................................................................................9
Writing text files (“w”, write(), writelines()) ....................................................................................................................................9
Appending to text files (“a”) .............................................................................................................................................................9
Os.path methods (exists(), isfile(), isdir(), join(), basename ............................................................................................................9
PC18 Exceptions .................................................................................................................................................................................10
Exception handling (try … except) .................................................................................................................................................10
Adding a finally clause ...................................................................................................................................................................10
EXERCISES .......................................................................................................................................................................................11
5.3 Maximum number of a type of coins in a given amount of money ..........................................................................................11
5.4 Swapping values of two variables.............................................................................................................................................11
7.4 Quadratic equations ..................................................................................................................................................................11
8.3 Ask the user for 4 numbers and print the largest, smallest and how many are dividable by 3 .................................................12
8.5 Fibonacci sequence until 1000 (every next number is the sum of the previous two) ...............................................................12
8.6 Ask two words and print the letters in common .......................................................................................................................12
8.7 Guess the random number chosen by the computer with ‘higher’ or ‘lower’ hints .................................................................13
8.8 Let the computer guess your number with ‘higher’ or ‘lower’ hints ........................................................................................13
8.9 Let the user enter a number and test whether it is a prime .......................................................................................................13
1
,8.10 Print a multiplication table in a nice format............................................................................................................................14
8.11 Print all integers between 0 and 10 that can be written as the sum of two squares ................................................................14
8.12 Roll 5 dices. What is the probability that each value is greater or equal to the value of the previous rolled dice? ...............14
8.13 Solve 4*ABCD = DCBA where the letters are all different digits .........................................................................................14
9.2 Write a function for common characters in two strings ............................................................................................................14
9.3 Gregory-Leibnitz series with a parameter that determines the number of terms to be calculated ............................................15
9.6 Calculate binomial coefficient by using a factorial function. Put your tests in a main() function. ..........................................15
11.6 Typically autocorrect a text ....................................................................................................................................................15
12.1 Represent a complex number as a tuple of two numeric values and create a function that adds these ..................................15
12.3 Processing inttuples using isinstance() ...................................................................................................................................16
13.2 Create a list of a deck of playing cards and shuffle the deck in random order .......................................................................16
13.3 FIFO structure/a ‘queue’ where an items are collected through input and the queue is popped if a ‘?’ is given ...................16
13.4 Count (case-insensitively how often a letter occurs in the text. Ignore every other character. Print from high to low. ........17
13.5 Eratosthenes: find all prime numbers by looping over a list and setting all multiples of each item to non-prime.................17
13.6, 13.7: Tic Tac Toe, Battleship see PC99 .................................................................................................................................17
14.1 Count every word in the text using dictionairies ....................................................................................................................17
16.1 List all files and directories, displaying their full path names ................................................................................................18
17.2 Open and read a file and count words line by line (for very long texts).................................................................................18
17.3 Open a file, process file line by line. Create output file with the same content except the vowels removed .........................18
17.4 From three files find which words of 10 or more letters are found in all files .......................................................................19
18.1 Different kind of exceptions. Extend code to handle them. ....................................................................................................19
2
, PC04 Expressions
Expressions are straightforward calculations which can also be done with a simple calculator.
Data types
- Strings (text)
Put a backslash (\) in front of a single or double quote that is part of the string to make it part of the string and not an ending.
i.e., 'I can\'t stand it' is a legal string.
- Integers (whole numbers)
- Floats (decimal numbers)
Certain numbers cannot be expressed exactly. Use a round() function to avoid long floating-points.
Use type casting to change the data type à int( parameter ), float(), str()
Basic calculating operators
// integer division (rounds down to whole number)
** power
% modulo (takes the remainder of a division)
PC05 Variables
If you want to write code that solves problems in a more general way, you need to use variables that store values.
Soft typing
In Python you do not declare the type of a variable. If you assign a new value to a variable, its type might change (= soft typing).
To see the type of a variable à type()
PC06 Simple Functions
A function is a block of code that performs some action. Some functions are called with parameters (or arguments), which may or
may not be mandatory. If a function has no return value, Python returns ‘None’.
Calculation functions
- abs(): 1 parameter, makes all values positive
- max(): 2 or more parameters, returns largest value
- min(): 2 or more parameters, returns smallest
- pow(): 2 parameters, returns the first to the power of the second
- round (): 2 parameters, the number to be rounded and the number of decimals
Some basic functions (len, input, print, format)
- len(): 1 parameter, returns length of that parameter
- input(): 1 string parameter (the prompt), returns the value entered by the user in string
- print() can have two special parameters, called “sep” and “end”.
- <string>.format(): is a method, not a function. Returns a new string, which is a formatted version of the given string.
Use curly brackets in the string to insert to parameter values.
o Precision: reserving a certain number of places for a string by using a colon (:) and an integer left of the colon.
If the given integer is larger than the length of the parameter, the returned string will be filled up with spaces.
o Alignment: by placing an alignment character between the colon and the precision e.g. {:>7} or {:^9}
o Display as integer: use a “d” e.g. {:d}
o Display as float: use an “f” e.g. {:f}
o Number of decimals for a floating point: place a period (.) and an integer at the end of the {}. E.g. {:<15.2f}
o Combinations of these can create table-like displays.
Modules (math, random)
from <modulename> import <functionname>
- Math: exp(), log(), log10(), sqrt()
- Random: random() in range [0,1), randint(), seed() to remember a random number
- Pcinput: getInteger(), getFloat(), getString(), getLetter()
3