TechLife Australia

Keep to the code!

LEARNING TO CODE IS ONE OF THE MOST EMPOWERING THINGS YOU CAN DO IN TECH. TECHLIFE SHOWS HOW TO DIP YOUR TOE INTO THE CODING POOL AND START WRITING YOUR OWN.

- [ DARREN YATES ]

PCS, LAPTOPS, TABLETS, phones — we use them every day, but for many, there comes a point where the urge to start writing your own apps is hard to resist. If you’ve never coded before, don’t let that stop you. Python is one of the world’s most popular programmin­g languages, taught in schools and used in industry and academic research. One reason it’s so popular is because it’s one of the easiest languages to learn. You can learn Python at university, but we’re going to show you in these four pages five key Python basics to get you started in coding your own programs.

THE FIVE PYTHON BASICS

Download the latest Python 3.6 programmin­g language for your computer from www.python.

org/downloads. Install it and launch ‘IDLE’, Python’s code terminal or ‘shell’. Here, you can type single commands and execute them. To write and save programs with many commands, choose ‘File > New File’ to launch a new code editor window.

PRINT

The first thing you do when learning a programmin­g language is print ‘hello world’ — newbie coders have been doing this for nearly 50 years. The ‘print’ function writes to the screen whatever you tell it to, but it’s also a little cleverer than that:

print(“hello world”)

Enter this line into the Python shell at the ‘>>>’ prompt and it’ll print ‘hello world’. The brackets after the command or ‘key’ word ‘print’ is where you place the data or ‘input’ to this function. Just like a quote in a book, you place the string of characters you want printed inside quote marks.

print(“hello”, 23)

All programmin­g languages handle character strings and numbers differentl­y and, here, we print the word ‘hello’ and the number ‘23’, separated by a comma to indicate they are separate entities.

print(10+12/6-2*5)

This is the clever bit — enter the above instructio­n into Python shell and it will calculate this problem and print the answer for you. Leaving out the quote marks tells Python this isn’t text to print but a mathematic­al problem to solve.

VARIABLES

In programmin­g, variables are storage buckets for holding a single entity of data — it can be a string of characters, for example, “hello world”, or a number, such as 438. It can also be a mathematic­al expression, like ‘9 + 5’ or ‘7 * 9 + 10’ (here, the star * symbol or asterisk means ‘multiply’).

price = 9.95 quantity = 23 total_price = quantity * price print(“The total price is”, total_price)

Open a new code editor window, type in the above code, save it as ‘variable.py’ and press key

‘F5’. If you’ve never coded before, congrats — you have now. The first line assigns the decimal value ‘9.95’ to the variable ‘price’. The second line assigns ‘23’ to ‘quantity’. Essentiall­y, when it comes to variables, whatever is on the right-side of the equals sign (=) is assigned to the variable on the left-side. Any time Python sees a word or string of characters without quote marks, it treats it either as a command word or a variable. Python has rules for selecting variable names — to keep it simple, start them with a letter and don’t use Python keywords, for example, you can’t use ‘print’ as a variable because Python already uses that word.

The third codeline is simple, but profound — on the right side, we ask Python to multiply (*) the values in variables ‘quantity’ and ‘price’. Python performs any calculatio­ns on the right-side first, then assigns the result to the variable on the left-side. So it multiplies ‘quantity’ by ‘price’ and stores the result in variable ‘total_price’. Finally, the last line prints the result to the screen, first with a simple message, followed by the value inside the ‘total_price’ variable.

There are two other things to see here — first, Python executes your instructio­ns one at a time and second, it starts at the top and works down (called ‘top-down execution’).

INPUT

If you want users to interact with your code, you need to get input from them and that’s what the input() function does. It gives the user a text prompt and waits for the user to enter a response, halting further execution of your code until the user presses the Enter key.

price = input(“Enter the price:”) quantity = input(“Enter the quantity:”) total_price = float(quantity) * float(price) print(“The total price is”, total_price)

Create a new code editor window, type in the above code, save it as ‘input.py’ and press F5. Rather than use fixed values as before, we’ll allow the user to enter in their own values. The first codeline prompts the user to enter in the price of an item — the characters typed in are stored in the variable ‘price’. The second codeline does likewise for quantity.

However, the input function only returns strings of characters, but you can’t multiply strings together, only numbers. So to multiply the values entered in by the user, we need to use the float() function, which converts the character values in each variable into decimal or ‘floating point’ numbers — the third codeline does this, multiplyin­g the number values and storing the result in variable

‘total_price’. Finally, we have the same print() codeline as before.

BRANCHING

Computer programs are a top-down structure of instructio­ns, but there’ll be times when you want your code to switch or ‘branch’ depending on a variable value or input provided by a user. This is exactly what ‘branching’ is used for. Branching in Python takes the form of if-else statements.

number = input(“Enter a number:”) if (int(number) % 2 == 0):

print(“Your number is even.”) else: print(“Your number is odd.”)

Create a new code editor window, type in the above code, save it as ‘branch.py’ and press F5. The first codeline asks the user for a number and stores the value in variable ‘number’. The codelines following that are an if-else codeblock. We start with the ‘if’ keyword, followed by a funny-looking statement inside the brackets () and ending in a colon. The code inside the brackets is called a ‘condition statement’ — if the statement is true, the code immediatel­y following the colon is executed, but if the statement is false, the code after the ‘else:’ keyword runs instead.

So what’s going on inside those if-brackets? The first bit is ‘int(number)’ — this tells Python we want to turn the string of characters stored in the ‘number’ variable into a whole number or ‘integer’. That’s followed by ‘% 2’. The percentage sign is Python’s code for modulo, the remainder you get when you divide by a whole number, in this case, two. So for example, 7 modulo 2 gives 1, since 2 divides into 7 three times, with 1 left over. Next comes the double-equals ‘==’ sign — this means ‘is equal to’. A single equals sign ‘=’ is used to assign a value to a variable, so the double-equals sign is used instead to refer to equality. Finally, the statement finishes with ‘0’, so all together, we want to know if the integer value of variable ‘number’ when divided by two has a remainder equal to zero. This is a very common method for working out if a number is odd or even. If the remainder of a number divided by two is zero, the number is even and we print “your number is even”. Otherwise (else), we print “your number is odd”.

PYTHON CODE INDENTING

Note the indented codelines — because the if-else statement introduces the idea of separate blocks of code, Python uses the tab key to identify code to be executed as a separate group. You can execute multiple statements within each block, provided they start with this minimum indent.

LOOPS

Writing code for something to occur repeatedly can itself become repetitive — think Bart Simpson writing 100 times on the blackboard ‘I will not instigate revolution’. That’s where loops come in. A loop is a block of code you want executed, either a fixed number of times or while certain conditions are met. The first type is known as a ‘for-loop’. number = input(“Enter a number:”) for count in range(13):

print(int(number), “x”, count, “=”, int(number)*count)

Create a new code editor window, type in the above code, save it as ‘forloop.py’ and press F5. The first codeline asks the user for a number as before. The following lines are the for-loop. We start with the ‘for’ keyword, followed by a variable name, in this case, ‘count’. That’s followed by another keyword, ‘in’, a ‘range(13)’ function and a colon ‘:’. The ‘range(13)’ part tells Python to create a sequence of whole numbers or ‘integers’, starting from zero, up to one less than the number shown in the brackets. In this case, range(13) gives a sequence of 0 to 12. The codeline in total says “for each number in range(13) that is stored in turn in the variable ‘count’, do this”. The ‘this’ refers to code after the colon and indented on the next line, in this case, a print command.

Here’s how the for-loop works — range(13) starts at zero, so the variable ‘count’ is given the

value ‘0’. The print statement forming the loop first prints the value of the variable ‘number’ entered by the user (let’s say ‘6’). It then prints ‘x’, followed by the value of variable ‘count’, which is ‘0’. Next, it prints an equals sign and, finally, the value of the user number multiplied by the value of variable ‘count’. Or in other words, ‘6 x 0 = 0’.

Once that print statement is complete, it goes back to the for-loop and selects the next value in the range(13) sequence, which is ‘1’. It runs through the print statement, printing ‘6 x 1 = 6’. Again, after this, it goes back to the for-loop statement for the next number in the sequence, which is ‘2’ and prints ‘6 x 2 = 12’ and so on until the final sequence number is reached, ‘12’, and prints ‘6 x 12 = 72’. Once that’s printed, the program stops because it’s reached the end of the sequence. And yes, this program prints out times-tables.

The second loop type, the while-loop, works similarly but continues loop-execution while a condition remains true.

import random number = random.randrange(10) guess = -1 while (guess != number): guess = int(input(“Guess my number (0-9):”)) if (guess != number): print(“Nope! Try again…”) print(“You got it!”)

Create a new code editor window, type in the above code, save it as ‘whileloop.py’ and press F5. The first codeline imports the ‘random’ module into Python — modules are like plug-ins for Python adding extra functions, the random module generates random numbers. The next line generates a random integer between 0 and 9 and stores it in the variable ‘number’. After that, we create a variable ‘guess’ and store minus-one in it. Next comes the while-loop. It starts with the ‘while’ keyword, followed by the condition inside the brackets, in this case, that the value of variable ‘guess’ is not equal to the value of variable ‘number’. As long as this condition is true, meaning we haven’t yet guessed the correct number, the loop continues. That loop codeblock starts with the indented code, initially asking the user for a number and storing the number value in variable ‘guess’. The if-statement following checks if the value of ‘guess’ is not equal to the value of ‘number’ and if that condition is true, prints the message ‘try again’. Note the double-indent here — this is known as nested-indenting and allows Python to follow the correct code path. Once that ‘try again’ message is printed, we go back to the while-loop line, check that the values of ‘guess’ and ‘number’ are still not equal. If they weren’t equal at the if-statement, they won’t be here, so we ask the user again for a number. This time, let’s assume the user gets the number right — when we get to the if-statement now, ‘guess is not equal to number’ is now false, so the ‘try again’ statement is not printed. We go back to the while-loop and again ‘guess is not equal to number’ is false, so we quit the while-loop and go to the next codeline on the same indent level as the while-loop codeline, which is the final print statement ‘you got it’.

MORE TO LEARN, ENOUGH TO START

If you’ve got this far, congrats! There’s still plenty more to learn, such as functions and classes, but you now have enough to start writing your own useful programs. The thing to remember is think in terms of ‘input-processout­put’ — the input you want from the user, how you’ll process it, and the output you’ll deliver back to the user. Profession­al computing programmin­g starts with these basics.

DON’T GIVE UP

Every coder makes mistakes and the whole thing can seem difficult at first, but it’s like learning to drive, playing the piano or any other endeavour — be resilient, persist and you’ll get the hang of it! Good luck.

 ??  ?? A TECHLIFE PRIMER
A TECHLIFE PRIMER
 ??  ??
 ??  ?? The for-loop is ideal for printing out your times tables.
The for-loop is ideal for printing out your times tables.
 ??  ?? Our ‘branch.py’ code shows how to identify odd and even numbers.
Our ‘branch.py’ code shows how to identify odd and even numbers.
 ??  ?? The if-else statements allows you to branch to different code blocks.
The if-else statements allows you to branch to different code blocks.
 ??  ?? The print() function outputs not just text, but calculates as well.
The print() function outputs not just text, but calculates as well.
 ??  ?? Use the input() function to get data from the user.
Use the input() function to get data from the user.
 ??  ?? The print() function can also output the value of variables.
The print() function can also output the value of variables.
 ??  ?? Get the Python programmin­g language free from the python.org website.
Get the Python programmin­g language free from the python.org website.
 ??  ?? A while-loop is ideal when you don’t know how many times to loop.
A while-loop is ideal when you don’t know how many times to loop.
 ??  ?? Python uses nested indented codeblocks to direct its code path.
Python uses nested indented codeblocks to direct its code path.

Newspapers in English

Newspapers from Australia