Python challenge: warmup exercises
I decided to start my Python challenge with a bunch of warmup exercises simply to get a feeling for the syntax and for how to work with that language. This exercises include:
- hello world and running python
- getting the user’s input
- handling command line arguments
- working with functions
- writing test cases
How to execute a simple ‘hello world’?
After installing python 3, I took the classic hello world example
…and executed it like this:
How to get the user’s input?
The user’s input can be caught by the input function followed by a message.
How to handle command line arguments?
In order to handle command line arguments, the sys module needs to be imported.
The arguments themselves are stored in the argv array
Implementing a simple function
A function starts with the keyword def followed by the name and parameters if suitable.
The function’s body needs to be indented.
Writing a test case
Usually, Python is not strictly object-oriented. Test cases however are implemented as classes.
The following is a test class that contains a test case for the sum function above:
A couple of things are to consider here:
- Note that the class SumTestCase inherits from the class TestCase, that is imported from the module unittest.
- The function under test (in this case sum) is imported
- The function test_sum performs the actual test by calling self.assertTrue
- ’ name’ is a built-in variable that checks if the script is executed directly or if it is imported by another module. If it is executed directly the main funtion of unittest will be called. In other words, the test case will be executed.