For this tutorial I will be using a python editor in Trinket https://trinket.io/. I like Trinket because it is free and works in a browser. Please read the terms and conditions when you sign up. All links in this article were correct when they were created. Feel free to use any form of Python you are comfortable with. I am going to assume the basics and jump into a few projects to allow you to experience the basic building blocks of coding:
- Sequence – Executing instructions in order
- Selection – Choosing a direction to go based on a condition (IF, ELSE)
- Iteration – Looping to execute the same code repeatedly
- Sign up for Trinket(link above).
- select the dropdown by your username and New Trinket/Python
- This first algorithm (sequence of steps to solve a problem) is going to solve a problem as old as time itself. Knowing how many cows you have. Everybody knows the best way to count cows is on a cowculator!
Write this code. I have added comments using # They show in green to aid understanding. The # tells Python to ignore them they are for humans and not part of the program.
By the way this code will not work!
At the bottom of the screen you will see this error:
TypeError: unsupported operand type(s) for Add: ‘int’ and ‘str’ on line 4 in main.py
This is telling me the variables Number and Total are not compatible. One is an int (integer or number) and one is a str (string or sequence of characters from the keyboard) see image below:
The place the interpreter failed is highlighted. As no code after this has been executed the problem is always here or above. NB. It isn’t always on the line highlighted. Look above as well.
To fix this error we need to cast the input from a str (string) to an int (integer). See the image below.
I have added code to cast the input from a string to an integer. Even though I typed a number in, any input is always a string because it is a set of characters you press on the keyboard. You need to tell python it is a number using int() … int (input (‘How many cows do you want to add?’)) see below line 3. The code now works.
It is working but you can only enter one number. Lets make it add more.
I have added the number variable at line 4 and assigned it 0 to allow the while loop to work.
I have added a conditional loop while the variable Number is an integer keep looping. I want to type a letter to make the loop end.
The problem is this gives an error because of the sequential execution of instructions the loop is running when I input a letter so the calculation can not be done as a letter can not be made into a number. See below:
I need to find a neater way to control the while loop. There are lots of ways to do this. Here is an example.