Python
Python
• This means that your code is not directly run by the hardware. It is instead passed
to a virtual machine, which is just another programme that reads and interprets
your code. If your code used the ‘+’ operation, this would be recognised by the
interpreter at run time, which would then call its own internal function ‘add(a,b)’,
which would then execute the machine code ‘ADD’.
• This is in contrast to compiled languages, where your code is translated into
native machine instructions, which are then directly executed by the hardware.
Here, the ‘+’ in your code would be translated directly in the ‘ADD’ machine
code.
ADVANTAGES OF PYTHON?
• The Anaconda distribution is the most popular Python distribution out there.
• Most importable packages are pre-installed.
• Offers a nice GUI in the form of Spyder.
• Before we go any further, let’s open Spyder:
Identifiers:
• A name in the python program is called as identifier.
• It can be a class name or function or module name or
variable name.
Ex: a=10
def(): class test:
Rules to define identifiers in python:
• If identifier starts with underscore (_) then it indicates it is private.
• We can't use reserved words as identifiers Ex: def=10
• There is no length limit for python identifiers. But lengthy identifiers are not
recommended
• Dollar ($) symbol is not allowed in python.
• symbols then the identifier is language defined
• special name, which is also o known as magic methods.
Ex: add
VARIABLES
• Variables in python can contain alphanumerical characters and some special characters.
• It is common to have variable names that start with lower case letters and have class names beginning with a
capital letter; but you can do whatever you want.
• Keywords: Reserved and cannot be used as variable names as they are used in-built Python function; i.e. and,
continue, break.
• Python is dynamically typed; the type of the variable is derived from the value it is assigned.
Rules to define a variable:
In: Out:
In:
Out:
ARITHMETIC OPERATORS
• Write a couple of operations
The arithmetic operators: using the arithmetic operators,
• Addition: + and print the results to the
• Subtract: - screen.
• Multiplication: *
• Division: /
In: Out:
• Power: **
A QUICK NOTE ON THE INCREMENT OPERATOR
SHORTHAND
• Python has a common idiom that is not necessary, but which is used frequently and is therefore worth noting:
x += 1
Is the same as:
x=x+1
• Boolean operators are useful when making conditional statements, we will cover these in-depth later.
• and
• or
• not
COMPARISON OPERATORS
• Write a couple of operations using
comparison operators; i.e.
In:
• Greater than: >
• Lesser than: <
• Greater than or equal to: >=
• Lesser than or equal to: <=
• Is equal to: ==
Out:
WORKING WITH STRINGS
In: Out:
In:
Out:
INDEXING
• Indexing in Python is 0-based, meaning that the first element in a string, list, array, etc, has an index of 0.
The second element then has an index of 1, and so on.
In: O
ut
: array, etc, by placing a
• You can cycle backwards through a list, string,
minus symbol in front of the index location.
In: Out:
In: Out:
In: O
ut
• Create a string that is 10 characters in length.
:
• Print the second character to the screen.
• Print the third to last character to the screen.
• Print all characters after the fourth character.
• Print characters 2-8.
TUPLES
• Tuples are containers that are immutable; i.e. their contents cannot be altered once created.
In: Out:
In: Out:
LISTS
• Lists are containers of arbitrary type. I
• They are the container that you will use most
frequently. n
• The elements of a list can be of different :
types.
• The difference between tuples and lists is in
performance; it is much faster to ‘grab’ an Out:
element stored in a tuple, but lists are much
more versatile. :
• Note that lists are denoted by [] and not the ()
used by tuples.
Out:
In:
• Use insert() to put the integer 3 after the 2 that you just added to your
string.
• You can add an element to the end of a list using the append() function.
In: O
ut
:
• Use append() to add the string “end” as the last element in your
list.
REMOVING ELEMENTS FROM A LIST
• You can remove an element from a list based upon the element value.
• Remember: If there is more than one element with this value, only the first occurrence will be removed.
In: Out:
• It is better practice to remove elements by their index using the del
function.
In: Out:
• Use del to remove the 3 that you added to the list earlier.
FOR LOOPS
• The for loop is used to iterate over elements in a sequence, and is often used when you have a
piece of code that you want to repeat a number of times.
• For loops essentially say:
• The command underneath the list then cycles through each entry in the species list
and prints the animal’s name to the screen. Note: The i is quite arbitrary. You could
just as easily replace it with ‘animal’, ‘t’, or anything else.
ANOTHER EXAMPLE
• We can also use for loops for operations other than printing to a screen. For example:
• Using the list you made a moment ago, use a for loop to print each
element of the list to the screen in turn.
THE RANGE() FUNCTION
• The range() function generates a list of numbers, which is used to iterate over within for loops.
• The range() function has two sets of parameters to follow:
range(stop) range([start], stop[, step])
stop: Number of integers start: Starting number of the sequence.
(whole numbers) to generate, stop: Generate numbers up to, but not including this number.
starting from zero. i.e: step: Difference between each number in the sequence
i.e.:
Note:
• All parameters must be integers.
• Parameters can be positive or negative.
• The range() function (and Python in general) is 0-index based, meaning list indexes start at 0, not 1. eg.
The syntax to access the first element of a list is mylist[0]. Therefore the last integer generated by range() is
up to, but not including, stop.
• Create an empty list.
• Use the range() and append() functions to add the integers 1-20 to
the empty list.
Out
put:
THE BREAK() FUNCTION
• To terminate a loop, you can use the break() function.
• The break() statement breaks out of the innermost enclosing for or while loop.
THE CONTINUE () FUNCTION
• The continue() statement is used to tell Python to skip the rest of the statements in the current loop
block, and then to continue to the next iteration of the loop.
WHILE LOOPS
• The while loop tells the computer to do something as long as a specific condition is met.
• It essentially says:
• When working with while loops, it's important to remember the nature of various operators.
• While loops use the break() and continue() functions in the same way as a for loop does.
AN EXAMPLE
• Create a variable and set it to zero.
• Write a while loop that states that, while the variable is less than 250, add 1 to the
variable and print the variable to the screen.
In: Out:
• You will use for loops more often than while loops.
• The for loop is the natural choice for cycling through a list, characters in a string, etc;
basically, anything of determinate size.
• The while loop is the natural choice if you are cycling through something, such as a sequence
of numbers, an indeterminate number of times until some condition is met.
NESTED LOOPS
• In some situations, you may want a loop within a loop; this is known as a nested loop.
Out:
CONDITIONALS
• There are three main conditional statements in Python; if, else, elif.
• We have already used if when looking at while loops.
In: Out:
In: Out:
AN EXAMPLE OF ELIF
In: Out:
FUNCTIONS
In:
• A function is a block of code which only runs
when it is called.
• Useful if you have operations that need to be
done repeatedly; i.e. calculations.
• The function must be defined before it is called.
In other words, the block of code that makes up Out:
the function must come before the block of code
that makes use of the function.
• Create a function that takes two inputs, multiplies them, and then returns the result. It
should look some like:
In: O
ut
:
MULTIPLE RETURNS
• You can have a function return multiple outputs.
I O
n ut
: :
READING AND WRITING TO FILES IN
PYTHON: THE FILE OBJECT
• Open up notepad or notepad++. Write some text and save the file to
a location and with a name you’ll remember.
• File handling in Python can easily be done with the built-in object file.
• The file object provides all of the basic functions necessary in order to manipulate files.
THE OPEN() FUNCTION
• Before you can work with a file, you first have to open it using Python’s in-built
open() function.
• The open() function takes two arguments; the name of the file that you wish to
use and the mode for which we would like to open the file
• By default, the open() function opens a file in ‘read mode’; this is what the ‘r’
above signifies.
• There are a number of different file opening modes. The most common are: ‘r’=
read, ‘w’=write, ‘r+’=both reading and writing, ‘a’=appending.
• Use a for loop and the variable name that you assigned the open file to in
order to print each of the lines in your file to the screen.
In Out:
:
THE READ() FUNCTION
• However, you don’t need to use any loops to access file contents. Python has three in-built file reading
commands:
• Important: Using the write() or writelines() function will overwrite anything contained
within a file, if a file of the same name already exists in the working directory.
PRACTICE – WRITING TO A FILE IN PYTHON
Part 1:
• Open the file you created in the last practice and ready it for being written to.
• Write a string to that file. Note: this will overwrite the old contents.
• Remember to close the file once you are done.
Part 2:
• Create a list of strings.
• Use the open() function to create a new .txt file and write your list of strings to
this file.
• Remember to close the file once you are done.
THE APPEND() FUNCTION
• If you do not want to overwrite a file’s contents, you can use the append() function.
• To append to an existing file, simply put ‘a’ instead of ‘r’ or ‘w’ in the open() when opening a file.
PRACTICE – APPENDING TO A FILE IN
PYTHON
• Open the text file you created in part two of the writing to a file practice, and ready it
for appending.
• Define a string object.
• Appending this new string object to the file.
• Remember to close the file once you are done.
A WORD ON IMPORT
• To use a package in your code, you must first make it accessible.
• This is one of the features of Python that make it so popular.
In:
In:
DEBUGGING
• Debugging is in fundamental aspect of coding, and you will probably spend more time debugging than
actually writing code.
• EVERYONE has to debug, it is nothing to be ashamed of.
• In fact, you should be particularly concerned if you do write a programme that does not display any obvious
errors, as it likely means that you are just unaware of them.
• There are a number of debugging programmes available to coders. However, debugging the most common
issues that you’ll encounter when developing programmes can be done by following a few key principles.
• When debugging, the most important function at your disposal is the print command. Every coder uses this
as a debugging tool, regardless of their amount of experience.
• You should have some sense as to what every line of code you have written does. If not, print those lines
out. You will then be able to see how the values of variables are changing as the programme runs through.
• Even if you think you know what each line does, it is still recommended that you print out certain lines as
often this can aid you in realising errors that you may have overlooked.
PRINT EXAMPLES
Did this chunk of code run? I want the value of variable to be 10 upon
completion of the for loop. Did the for loop work
correctly?
No.
Yes, it did.
RUN YOUR CODE WHEN YOU MAKE CHANGES
• Do not sit down and code for a hour or so without running the code you are writing. Chances are, you
will never get to the bottom of all of the errors that your programme reports when it runs.
• Instead, you should run your script every few minutes. It is not possible to run your code too many
times.
• Remember, the more code you write or edit between test runs, the more places you are going to have
to go back an investigate when your code hits an error.
READ YOUR ERROR MESSAGES
• Do not be disheartened when you get an error message. More often than not, you’ll realise what the
error is as soon as you read the message; i.e. the for loop doesn’t work on a list because the list is
empty.
• This is particularly the case with Python, which provides you with error messages in ‘clear English’
compared to the cryptic messages given by offered by other languages.
• At the very least, the error message will let you know which lines is experiencing the error. However,
this may not be the line causing the error. Still, this offers a good starting point for your bug search.
• This can sometimes be a bit of a hit-or-miss, depending on the
nature of the error.
• If your error is fairly specific, then there will nearly always be a
webpage where someone has already asked for help with an error
that is either identical or very similar to the one you are
experiencing; stackoverflow.com is the most common page you’ll
come across in this scenario.
• If you cannot work out the cause of an error message, google the
error code and description.
• You can often comment out bits of code that are not related to the chunk of code that contains the error.
• This will obviously make the code run faster and might make it easier to isolate the error.
BINARY SEARCHES
• This method draws upon a lot of the methods we have already covered.
• Here, you want to break the code into chunks; normally two chunks, hence this method’s name.
• You then isolate which chunk of code the error is in.
• After which, you take the chunk of code in question, and divide that up, and work out which of these
new chunks contains the error.
• So on until you’ve isolate the cause of the error.
WALK AWAY
• If you have been trying to fix an error for a prolonged period of time, 30 minutes or so, get up and walk
away from the screen and do something else for a while.
• Often the answer to your issue will present itself upon your return to the computer, as if by magic.
PHRASE YOUR PROBLEM AS A QUESTION
• If all else fails, do not hesitate to ask a colleague or friend who is a coder and maybe familiar with the
language for help.
• They may not even need to be a specialist, sometimes a fresh pair of eyes belonging to someone who is
not invested in the project is more efficient at helping you work out your issue than spending hours
trying to solve the issue on your own or getting lost the internet trying to find a solution.
ANY QUESTIONS?
USEFUL RESOURCES
• There are two great online resources for learning this language through practical examples. These are
the Code Academy (https://www.codecademy.com/catalog/subject/web-development) and Data Camp
(
https://www.datacamp.com/?utm_source=adwords_ppc&utm_campaignid=805200711&utm_adgroupi
d=39268379982&utm_device=c&utm_keyword=data%20camp&utm_matchtype=e&utm_network=g&u
tm_adpostion=1t1&utm_creative=230953641482&utm_targetid=kwd-298095775602&utm_loc_interes
t_ms=&utm_loc_physical_ms=1006707&gclid=EAIaIQobChMI3o2iqtbV2wIVTkPTCh2QRA19EAAYASAAEg
LZdPD_BwE
).