Click to see the rest of the programming section :
When we first learn programming, it’s very easy to want to jump straight in and expect to be able to write exciting programs straight away. In fact, one of the best things that you can do is make sure that you understand the basics first, such as inputs, outputs, and variables.
The building blocks of programming are known as constructs. These form three main types of construct:
Sequence: the order in which the lines of code are run
Selection: code that only runs if a condition is met
Iteration: code that repeats without needing to be rewritten
Inputs and outputs form the foundations of many of our programs. For instance, if we wanted to write a program that multiplied two numbers together, we would need the user to input what the numbers are, and then output the answer to the user.
Of course there’s no point in having an input if we can’t store it and use the data in the program. This is where variables come in.
A variable is a named piece of memory within the program that can change while the program runs. We usually declare the name of the variable at the start of the program along with its data type.
Hover over the image for the answer!
This does however depend on the programming language. For instance, if I wanted to declare an integer (whole number) variable called num this would look different in different programming languages:
C# int num;
VB dim num as integer;
Pascal num = integer;
Python num = 0
You’ll notice that they are all logically very similar, only the grammar of the programming languages really changes. The spelling and grammar of a language is known as the syntax.
In our program, we are going to store the inputs into variables, process the calculation and then output the answer. In pseudocode this may look like:
num1 = INPUT
num2 = INPUT
OUTPUT (num1 * num2)
The Python3 code below has implemented the algorithm. Add more to the code to output addition, subtraction, and division. Press Ctrl + Enter (Cmd + Enter on Mac) to run the code when you’re ready.
Something that you may have noticed in the Python3 code was the use of int() around the inputs. In some languages, all inputs are treated as strings, so they must be converted into the correct data type before they can be used. This is known as casting.
Find this page helpful? Share the love on your social media mentioning @TeachAllAboutIT and we’ll enter you in our monthly draw to win a gift voucher towards any product on the site!