An Introduction to Python

An Introduction to Python

An introduction to Python supported by An introduction to Python Abstract This guide provides a simple introduction to Python with examples and exercises to assist learning. Python is a high level object-oriented programming language. Data and functions are contained within an object (or storage container) which can then be used at a later stage in a program. Python is readable and simple to understand and hence is a great starting language for programming. Python has been around for over 20 years resulting in lots of available resources and many user created libraries to assist you or simplify tasks. Currently Python 3 is available with new features but Python 2 is still most commonly used and most libraries were built to work with this version. Hence we will learn the appropriate syntax for Python 2, however most code remains consistent if you wish to move to Python 3. An introduction to Python Contents 1 Getting started with Python 1 2 Data Types 7 3 Numbers, Booleans and Math 8 4 Strings 10 5 Variables 16 6 Output - The print function 19 7 User input 22 8 Operators 24 9 Defining Functions 29 10 Conditional Logic 33 11 Lists 38 12 Loops 48 13 Additional Topics 53 13.1 Vectors/Matrices . 53 13.2 Dictionaries . 54 13.3 Visualisation . 56 13.4 Exception Handling . 57 14 Free Online Resources 60 An introduction to Python 1 Getting started with Python When we use applications like Scratch, the blocks are converted into code which tells the computer what you wish to do. This code is the programming language that gives instructions to a computer which could be written in Python. In Python we can write a program which is just a sequence of instructions written in code which the computer can interpret and execute. These instructions are often referred to as statements/commands but are just lines of code telling the computer what you want it to do. There are diff erent ways to write and run Python code. Python shell and scripting The python shell is useful for basic calculations or one line of code. You type in the code and get an output underneath. This code is not saved. Scripting is writing lines of code to create a program which you want to save and run in the future. You can simply write the code in a text file and save it as "filename.py" which can then be run using python. Python editors Often Python editors or IDEs (Integrated Development Environments) are used when writing Python scripts so that you to build up a project containing multiple Python files. There are many different editors such as Pycharm, Spyder, Eclipse, PyScripter and Jupyter note-books. The examples throughout this guide are images from Trinket (trinket.io) an all-in-one coding environment designed for education. There’s no software to install to use Trinket as it runs in a web browser. Trinket provides a clean way to see the outputs clearly alongside the code input and is a great starting tool for learning Python. Page 1 An introduction to Python Importing libraries/functions A function is a named sequence of statements of instructions that you can use in your programme. There are many functions/commands available in basic Python that you can use without even thinking about. Many of these functions will be used throughout this booklet. However some functions are stored within libraries and so you have to inform Python that you wish to use them. For example, suppose you wish to find the square root of 16. Typing sqrt(16) will produce an error stating sqrt not defined. This is because the function sqrt is stored inside the math library. This is easily solved using the following code: This will output the answer of 4 as expected. If you wanted to import the whole library, you can just use an import math statement. Sometimes as functions can have similar names we want to ensure we are using the correct one from the required package. In this case we have two options: Page 2 An introduction to Python The second case is an optional shorthand that could be used if you will be using many functions from the one package. You will see this used often for popular packages such as numpy (np) or pandas (pd). Functions or Methods When it comes to understanding some of the terminology in Python, it can seem more complex than it is to use. Functions and methods are often confused and you can use Python without understanding the diff erence, as long as you know how to use them. Functions are stand alone, so you must provide them with the appropriate arguments they need to produce a result. They use the syntax my_function(x) taking x as input, doing something to that and outputting the result, for example, taking a number and finding the square root like sqrt. Methods are associated with objects or classes (groups) of object. You may have an object that is a word and you can apply a set number of operations to this object and only objects of this type. These methods use the syntax object.method() where the object is your word e.g. "HELLO".lower(). It sounds complicated but you will learn common functions and methods and so you know the appropriate syntax to use throughout this booklet. Good Coding Standards There are many good coding standards you should abide by when writing code in Python. The structure of statements is often referred to as syntax. The list below outlines the key principles you should follow: • Commenting & Documentation - It is important to add comments to your Page 3 An introduction to Python code, not only for other users’ benefit but also your own. It should allow you to easily follow what the programme is doing, however, if a line of code is self- explanatory then there is no need to comment. Single line comments are included using the octothorpe/hashtag symbol (# This is a comment) and multiline comments use triple double quotes (""" some long comment """). • Consistent Indentation - It is best practice to add indents or tab spaces to your code for easy reading. This becomes particularly important when we introduce functions and loops. • Code Grouping - It is a good idea to leave spaces between related code, for example, between functions. • Consistent Naming Scheme - There are two popular options for naming variables and functions in Python: camelCase is where the first letter of each word is capitalised, except the first word, whereas underscores uses underscores between words, like, my_name. You should stick to one type of naming scheme throughout your code. • DRY - Don’t Repeat Yourself. If you are going to repeat some lines of code this can be defined in a function for multiple use. We will see how to implement this later. • Limit line length - Keeping code lines short enough to follow without having to scroll across the screen is a good habit so that you can easily scan the code for errors. Combining shorter lines and indentation allows quicker reading of your code. • Programme ordering - Often, a programme description is written as a comment at the start of the programme, followed by imports and then user defined functions. The ordering of the code should be logical so that it is easily followed and understood. Page 4 An introduction to Python Getting help Python has a built in help utility, where you can get documentation about objects, methods, and attributes. To obtain documentation we just use the help() function around the name of the object e.g. help(str) will outline the definition of a string object and the functions/methods associated to that. There is also a lot of help available online at https://docs.python.org/2/library/. Bugs and Testing When we write programmes, we start small, ensuring that we obtain a piece of code that runs correctly and then we can build upon it. In order to ensure our code runs correctly, we must use a computational thinking concept known as debugging to check for errors and correct them. It is important to remember that not all errors will be obvious - error messages will only appear if Python fails to run the code. If our code runs, it does not necessarily mean it will produce the expected output. We must therefore test each piece of code and ensure we obtain the correct result. Testing could be done manually, however as programs become more complex, we require functions to test our code. If Python fails to run the code you may obtain an error message. The list below highlights some of the errors you may observe and what they relate to. This should help you to find and correct the code that Python is failing on. Some of these may not make complete sense yet but as you work through the booklet, you will understand these errors. Types of Errors • Attribute Error - Your object is the wrong data type for the method you are using. An example would be trying to append to an integer. • Syntax Error - This suggests a problem with a sequence of characters or words. Some examples would be if quotes are missing around a string, a Page 5 An introduction to Python colon is missing after an if/for statement or brackets are mismatched. • Type error - This suggests that there is a problem with the type of an object. Examples include using a function with the wrong number or type of arguments or using an object which Python expected to have a value and has None.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    63 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us