An introduction to Python

Size: px
Start display at page:

Download "An introduction to Python"

Transcription

1 supported by

2 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.

3 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 Conditional Logic Lists Loops Additional Topics Vectors/Matrices Dictionaries Visualisation Exception Handling Free Online Resources 60

4 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

5 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

6 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

7 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 selfexplanatory 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

8 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 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

9 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. Indentation error - Your code is not aligned correctly. Name error - Python cannot find the function/object called. Examples include calling functions before they are defined, forgetting to import the relevant module or spelling a function/variable incorrectly. IO error - The file you are trying to import/open does not exist Key error - The key does not exist in the specified dictionary. Page 6

10 2 Data Types Every value in Python has a datatype. Data types in Python include Integers (int), Floats (float), Booleans (bool), Strings (str), Lists (list) and Dictionaries (dict). These will be discussed over the next few sections. We can find the type of an object by using the type function. There are functions and commands in Python which will only work for specific data types, for example, a function that multiplies two numbers will not work if you input two letters for the function to multiply. Page 7

11 3 Numbers, Booleans and Math Integers An integer in Python is a whole number which can be positive or negative. It is abbreviated to int when using the type function as shown in the example above. Some examples are 1,-1,1000 etc. Floats A float (or floating point number) is a decimal number containing a decimal point, for example, 3.6. Floats are like real numbers in Python. Booleans A Boolean value can take one of two values, generally True or False. This data type will become useful when we look at conditional logic in section 10. If we converted a Boolean to a number, True is converted to 1 and False 0. The data type is abbreviated to bool. Math Python can be used as a simple calculator. Operator Function Example Input Example Output + Addition Subtraction * Multiplication 3*5 15 / Division 15.0/ // Integer Division 15.0// % Remainder 15%4 3 ** Exponent 2**3 8 Page 8

12 Important Notes: If you use integers in a division calculation (/), the output will be the floored integer (i.e. rounded down). Once children begin to learn about remainders and decimals then floats can be introduced. This is Python 2 specific and in Python 3 you must use (//) to obtain the floored integer. Python follows the expected operational ordering BIDMAS (Brackets, Indices, Division, Multiplication, Addition and Subtraction). However, you can use brackets to be clear what you wish to calculate. Knowledge Point 3.1 What is the data type of 7.8? Use Python to check this answer. 3.2 Use Python to compare the answers to the following math equations: 2+3*4 (2+3)*4 3.3 Compare the answer for the following questions: 17/3 17//3 17.0/ //3.0 Can you tell the data type of the answers? Do you understand why the results are diff erent? Page 9

13 4 Strings A string is a sequence of characters which are contained inside single or double quotes. Basically a string is a word, sentence or paragraph e.g. "My name is Bob", "Hello", 'Goodbye'. If we wish to use apostrophes or speech marks inside a string we must either use the opposite quotes for defining the string or use escape characters. "It's a lovely day today!" 'It\'s a lovely day today!' If we have a very long paragraph, we can use triple single quotes. '''Today we are learning about strings in python. You have to be careful when using single or double quotes together. Using Triple quotes allows strings to extend over multiple lines like this! It also allows 'single quotes' and "double quotes" to be used inside. ''' Adding Strings When you combine two strings into one string it is called string concatenation. It is as simple as using: Note: If you wanted to add two words with a space between them you need to tell Python that a space is needed. Page 10

14 If we forget the space Python will output "GreenApple". Repeating Strings If we want to repeat a string multiple times we can just use the multiplication operator *. Indexing Strings Every character in a string is indexed which means it is assigned to a number by the order it appears in the string. Python begins counting from 0 so you have to be careful. You must also count spaces and punctuation too! This means if we want to find the first letter of the word "Python" we would require the letter at index 0. If we require the last letter, or the 6th letter of Python, we would require the letter at index 5. Page 11

15 Extracting a letter is known as subsetting which we will look at in more detail in the next section. You can also use negative indexes to count from the last letter to the first so that if we wanted the last letter we would use index -1. It is important to note that strings are immutable meaning that they cannot be changed. If we try to change a letter, "Python"[0]="p", we will obtain an error. Subsetting Strings We may wish to extract part of a string or a substring. Similar to the example above we can specify which characters we want using square brackets ([]) and a colon (:). Again remember indexing starts from 0 and when using [0:8] this specifies we want all characters from index 0 up to (but not including) 8. Here are some examples: Page 12

16 We can use negative indexes to extract the last letters and we can also reverse a string using similar indexing. You will see more use for indexing and subsetting when we introduce lists in Chapter 11. Other Useful String Functions upper() Converts all letters in a string to upper case (capital letters). lower() Converts all letters in a string to lower case. Page 13

17 isupper() Checks if a string is in all capitals. islower() Checks if a string is in all lower case letters. capitalize() Changes first letter of first word in string to a capital letter. split() Splits a sentence into words. split(",") Splits a sentence at the comma. Page 14

18 strip() Removes white space from the start and the end of a string. join() Join strings into one string. len() Returns the number of characters in a string. In some of these examples the string is split into a list or a list is joined into one string but we will look at lists in detail in Chapter 11 (these functions are here for reference). Knowledge Point 4.1 Type the following phrase into Python and determine the length: "I like Python" 4.2 What is the fourth letter? 4.3 How would you extract this letter? 4.4 Extract the word Python from the sentence. Page 15

19 5 Variables A variable is something which the user defines. It can be thought of as a container used to store information you may need later. It is realistically an allocated slot of computer memory for that piece of information. It consists of a name, a type and a value where the name is what you want to call the variable, the type relates to the type of data stored in it and the value is the data. A variable is simply defined using an equals sign (=) to assign a name to a piece of data. Notice that we cannot just type Davidson. In that case Python would look for a variable called Davidson. Adding the quotes tells Python that this is a new piece of data that is of type string. You can then apply functions to these variables. The following example will add the two strings (like in Section 4) with a space between them to output "Claire Davidson". This can also be used for maths and is especially useful when learning algebra. We tell Python that x is 3, y is 5 and ask what x plus y is, to which Python returns 8. Page 16

20 Variable names can be only one word long but they can contain letters, numbers or an underscore(_). However, there are a few important rules: They cannot start with a number Names should not contain spaces They should not be the name as built in functions or variables (e.g. sum(), pi) as you will overwrite these functions. The names should generally be memorable and relevant so that you can use them efficiently throughout your code. The names are case sensitive and so when you want to use your variable, be sure to use the correct format. So why do we define variables? Variables can be very useful when we want to reuse a piece of information later in our programme. It can reduce typing errors and make the programme more read-able by other individuals. The power of variables allows you to change one line of code (i.e. the value of your variable) and it will impact any code in the remainder of your program, which uses this variable. You will see how useful this can be for more complicated data types such as lists and vectors later and when programmes are more complex. Variables are easily modified and will always take the most recent value within the code. The example below defines Apple to be 32 and adds 5 to update Apple to 37. This just overwrites our original value for Apple. The next step sets Apple to 7 which then overwrites this value of 37. Page 17

21 Knowledge Point 5.1 Create a variable called radius equal to 5. Use this to find the area of a circle with a radius of 5cm. (Area of a circle = r2 ) HINT: You have to import pi from the math package 5.2 Create three variables: first_line = "Happy birthday to you" third_line="happy birthday dear friend" comma=", " Use these variables to write the Happy birthday song: Happy Birthday to you, Happy Birthday to you, Happy Birthday dear friend, Happy Birthday to you Page 18

22 6 Output - The print function The print function is one of the most simple functions but very useful. At this stage when we are only writing short pieces of code we can check everything is working as expected easily and can print the values of variables simply by typing their names. This is not possible in other IDEs and when using text editors. As we begin to use more complicated code and functions, printing is very useful to ensure our code does what it should do! It allows us to view variables at any point in our program which is great for debugging. The use of the print function will become clearer when we learn about defining functions later. You may want to print multiple values at one time which is easy in Python. There are various ways to do this, for example, Python allows you to make great use of the + operator where you can not only add numbers, but you can add strings as seen in Chapter 4. We can also use this to combine strings and variables. Page 19

23 However, if our variable contains data of any other type except a string, and we try to add this to another string, the + operator will throw an error when it tries to combine them. To overcome this, we can use the str() function to convert the number to a string and then combine this using the + operator. So, all the "pieces" added together should be the same data type. Alternatively, Python 2 allows you to use %s and %d within a string to represent strings or numbers respectively. You then tell Python which variable/values to insert at these points after the string. For example, "Hello %s" % "world" will create the string "Hello world". You can add multiple variables or values using brackets as shown in the example below. This syntax will unfortunately not work if using Python 3. Page 20

24 Knowledge Point 6.1 Create a variable called Name and store your own name in it. HINT: Remember to use quotes! 6.2 Check the data type of this variable. 6.3 Check the length of your name. 6.4 Create a variable Age with your current age stored in it and check its data type. 6.5 Print a sentence which says "My name is... and on my next birthday I will be... years old!", replacing the... by using your variables. Page 21

25 7 User input You may create a programme which requires input from the user. For example, you could build a battleships game where the user must input their guesses for where the battleships lie. These inputs are then used to compare against values in the programme. An even simpler example could be that you create a small maths game which asks the user some math questions, calculates the answer and compares the user s answer to the true answer. We can use the function input() which takes a string that presents a question to the user. It is also very useful to save the input to a variable for use in your programme as shown in the following example. We are running Python 2 in a browser with trinket.io and it allows us to use input to accept data like Claire and it will recognise it as a string. However, some IDEs, like Jupyter note-books, expect data entered by the user to be in the correct data type. In the example below we obtain an error because Python will search for a saved object (such as a variable) defined as Claire. We have to specify that Claire is a string using the double quotes. Page 22

26 In this case I recommend you use this function instead. It will interpret the input only when required. If you want to use the input as a number, you can then convert it later in the problem using the int() and float() functions. Realistically, if we ask the user for a number, we would want to ensure the number they input is a number and send an error if not. We will touch on this later but in general you would use exception handling (see Chapter 13.4). Knowledge Point 7.1 Write a few lines of code which asks the user what their name is and their age. Use these answers to print the sentence " Hello..., on your next birthday you will be... years old." Page 23

27 8 Operators In Python you can use operators to compare two pieces of data, some of which you may have seen from maths lessons. The examples below use numbers but you can also compare strings using operators where capital letters are considered less than lowercase letters ("H"<"h") and the first letter of each string is compared alphabetically ("apple"<"banana"). The table shows the operators, their use and an example for each. The result from operators is always a Boolean value, True or False. The statements, for example 2>3, are often referred to as conditions. Operator Function Example Input Example Output > Greater Than 2>3 FALSE < Less Than 3<5 TRUE >= Greater Than 3>=3 TRUE or Equal to <= Less Than 2<=5 TRUE or Equal to == Equal to 6==5 FALSE (Equivalent)!= Not Equal to 5!=5 FALSE <> Not Equal 3<>6 TRUE We can also combine multiple operators to check two conditions at once, which is often called chaining. The example below compares our variable x to see that it lies between 3 and 8. The result will be True. Page 24

28 It is important to consider the diff erence between = and ==. The single equals sign should be read as "is set to" where you define a variable and set a value to that name. The double equals symbol should be read as "is equivalent to" where you check if two numbers/strings/variables are exactly the same. The example below shows the use of both symbols (notice strings are case sensitive). There are logical operators which will also be very useful for coding in Python (especially when we cover conditional logic in Chapter 10). 1. and This compares two conditions and it will only return True if both conditions are True. Consider the following examples: Example a: Example b: Example c: Page 25

29 In example a, both conditions/statements are True and so the result is True. In example b only one of the conditions is True and so the and operator returns False. In example c both are False resulting in a False. 2. or This compares two conditions and if any one condition is True then it will return True. In other words at least one must be True to result in True. Example a: Example b: Example c: In this case, examples a and b both return True because at least one condition holds True. Example c remains False because both conditions are false. 3. not This operator reverses the result of a condition, so if the condition is True, the not operator returns False and visa versa. It becomes useful when checking if values are in a list which we will see later. In the example below 5>3 yields True hence using not we obtain False. Page 26

30 4. in This operator compares two objects to determine if one lies inside the other. You will see the vital use of this for lists later but for now it can be used for strings. You must be careful though as it matches characters not words. In the first example we obtain True because "coffee" is clearly in the sentence, however we also obtain True for the second example, but why? The character string "tea" lies inside the word "instead" and so Python finds it inside our string. As it is character matching, it is also case sensitive. Therefore the operator in is probably not best used for sentences. It could be used to check if a word contains a letter though (you may want to turn it to lower case using method lower() first). 5. not in As expected this checks if one object is not in another. The following example highlights that we must watch out for capital letters when comparing strings. Page 27

31 We often combine multiple logical operators throughout our code. There is a hierarchy in how operators are calculated where the and statement is checked before the or. To make sure you get the result you want, be sure to add parenthesis. Knowledge Point 8.1 What do you think the answers to the following conditions are? Check answers using Python. (a) 6>10 or 3==3 (b) 2<=3 and 2!=2 (c) not(16%4==0) (d) "ate" in "I will be late" 8.2 Write three statements of your own using a range of operators where: (a) At least one must be false and at least one must be true (b) At least one should include one of the following logical operators: and, or, not, in. Page 28

32 9 Defining Functions Python comes with lots of pre-defined functions such as print which you can use without even thinking about. Packages also contain functions which can then be imported and used, for example, the sqrt function from the math package (see Section 1). Sometimes we want to create our own functions. Our good coding standards tell us that we shouldn t duplicate code where possible, hence, if we want to repeat some code multiple times we should store this as a function. The general syntax for a function is shown below. You must start with def statement followed by your function s name with any inputs added in brackets. These inputs are often known as parameters or sometimes arguments. You can then carry out some transformations on those inputs and return something new. As an example we could create a function which takes any two numbers, adds them together and returns the output. In fact you have not told the function that it must be a number so it could take two strings. Page 29

33 You will find functions very useful as you start to build more complex and iterative code! There are a few very important concepts around functions to be aware of. Firstly, you have required and optional parameters. We could create a function that requires three numbers. It adds the first two numbers and then subtracts the third. In the example below our third variable x3 is optional. This is because we have assigned a default value to this variable. This means if the user sets a value for it, then Python will use that new value. However, if you do not specify x3 then the default value of 5 will be used. Page 30

34 Secondly, variables created inside the function environment are not accessible from outside the function. The function environment is just any code, functions or variables written or calculated between the def and return statements of a function. We create a variable result1 during our calculations but as this is inside the function we cannot access this from outside the function environment. This is where printing can become useful! If you want to check intermediate calculations or values, you simple write a print statement inside the function environment and Python will print these values as it runs through the function code. It is important to test your code and functions to ensure you obtain the output you expect. This can be done manually by adding in some values and ensuring you obtain the expected output, or else, by creating a test function. Testing is used to determine if there are errors in the users code. Often we hear the term unit testing which specifically tests one piece of code in isolation. Examples of errors were described in Chapter 1, however in the context of Python, two examples could be: Syntax errors are unintentional typing errors which result in Python being unable to understand a sequence of characters e.g. an extra period when using methods, "hello"..upper(). Logical errors are created when the algorithm is not correct. An example of this is an index error where we may try to extract the last letter of a string is by using the length function e.g. my_string[len(my_string)]. This is due to Python indexing starting at zero and hence the index does not exist. Page 31

35 Knowledge Point 9.1 Create a function called create_squiral which runs your squiral activity when you call it. 9.2 Create a function called upper_case which takes a string and returns all characters as capital letters. 9.3 Create a function which takes a number representing hours and returns the equivalent number of minutes. 9.4 Create a function which takes a number representing minutes and returns the value in hours. Print the number of full hours inside the function. Check using minutes=90 and minutes=165. HINT: To return the hours as a decimal you need to use floats. Page 32

36 10 Conditional Logic if We can use if statements to only run code when a condition is met. This example will check the variable total and if it is greater than 7 (i.e. condition is TRUE) then Python will run the indented lines and print Great. If total is less than or equal to 7, Python will stop and will not produce an output. else Else is commonly used in conjunction with if statements, but it can also be used with while or for statements which we will learn about in Chapter 12. When using an if statement, code within the else statement will execute when the condition is false. In this case we store the value 18 in our variable Age. The if statement checks if Age is less than 18 and since this is false it executes the code after the else statement. A simple example - if you open a tin of soup, you can take out the soup, else, you cannot remove the soup. Page 33

37 elif When we use if and else we can only have two possible outcomes (one if the condition holds and one if not). You will often want more than two possible outcomes. You could write multiple if statements but this requires Python to check every single one of those conditions. In the example above, if we input monday, our Day variable meets the first if condition and so Python prints ":(" and the code stops. In the result above, Day is equal to saturday so Python will step through the conditions from the top and stop when it is met, in other words, at the second elif statement. When using multiple conditions, it s important to plan the order of these statements as you can actually make your code more complex than it needs to be. Compare the following example: Consider grading a test. If their score is less than 60, they will fail. A score of 60 or over, will result in a pass with Grade D. A score of 70 or greater results in Grade C, 80 or greater is Grade B and 90 or greater is Grade A. Following this pattern we could write the following algorithm: Page 34

38 This includes a lot of different comparisons at each stage. However, if we work through the problem backwards, the code is much easier to read and requires less processing from Python. An important thing to note here is that even though my score is in fact greater than 70 and 60, the condition score>=80 was met and hence our score is not compared to any of those conditions below. However compare this to the previous example. If we did not have the second condition, our elif statement would read elif score>=60: and since our score is greater than 60, we would see an incorrect Grade of D as Python would not continue to the following elif statement. Page 35

39 Nested Conditionals As problems become more complex, our code will also increase in complexity. Some-times nested conditionals are used where further conditions can only hold if the first condition is met. They generally help the readability of your code but you must ensure you maintain good coding standards such as indentations within your syntax. As you can see in this example, Python first checks if the input age is over 18, if not, it will jump straight to the last else and would print "child". If the age is over 18, it will then test this age against the nested if condition. On larger more complex problems, this could save significant processing time and allows greater flexibility in your functions. Page 36

40 Knowledge Point 10.1 Create a function which take two numbers as input and returns the diff erence between these two numbers Extend this function so that we only want non-negative answers, in other words, no matter what order you input the two numbers, Python will return the biggest minus the smallest Write a function which returns the statements: "positive integer", "zero" or "negative integer" where appropriate. Test this function using -10,10 and Extend this function by checking if the input is an integer. If not, return an error message, "That is not an integer". Test this with 3.4 and 3. HINT: Consider the order of your conditional statements - a nested statement could also be used. Page 37

41 11 Lists We have already covered a few lists when we looked at strings but we have not yet defined these data types. A list is an object that contains multiple values in an ordered sequence. It is collection of items where items could be strings, integers, variables or even other lists. The elements in a list do not have to be the same data type however multiple data types can limit the functions that can be applied to the list. When you combine lists, conditional logic and loops (in the next chapter), you have all the tools required to write quite complex algorithms. Creating Lists To create a new list all values are defined within square brackets, separating each element with a comma. We often want to save it to a variable using the same syntax as was used for strings and numbers. We can create an empty list using simply [ ] or store this as a list named x using x=[ ]. When saving a list as a variable, we must not use the name "list" as this is a function in Python which converts a string (and other iterable objects) into a list. Page 38

42 Another very useful function for creating a numerical list is range(). This becomes very useful for loops as we will see later. In the first example above, we only specify one parameter which tells the range function where to stop. The range function will count integers starting from 0 up to but not including this stop value. In the second example we tell Python where to start (2), where to end (up to 12) and the steps between each (in this case 2). The step parameter can take negative values where you want to create a decreasing list as shown in the third example. Basic functions such as printing can be applied as shown in the examples above or we could find the length of the list using len(listname). Other useful functions mentioned for strings was in and not in. This is great for lists where we can check if elements lie inside a list or are missing from a list. We can compare our variable shopping_list from the start of this section. Page 39

43 When using numerical lists, you may wish to use some of the following functions/methods: min(list) - find the minimum value of a list max(list) - find the maximum value of a list sum(list) - find the sum of all elements in the list list.index(item) - find the index for an item in the list. This finds the index of the first instance of that value in your list. (Note: If you wanted to find the indexes of all occurrences this would require more complex code.) Subsetting Lists We may want to extract only certain elements in a list and the syntax is the same as subsetting a string. Remember that Python indexing starts from 0. The lists used in these examples are from the start of Chapter 11. Page 40

44 Updating Lists Lists are mutable so we can change elements of them after definition. Changing elements of a list may not seem that useful yet however this becomes extremely useful when you start to build programmes. This example changes the second value "Bananas" (index=1) to "Pears". We may also want to delete elements of a list using the del function. We must be careful as this then changes all the indexes of the following elements. In the example below we may have repeated the letter "c" three times and we want to remove the repetitions. The extra "c" elements are found at index 3 and 4 but after deleting the first "c" all the following elements move up by one. So you must be careful when deleting elements iteratively. Page 41

45 An alternative way to remove elements from a list is to tell Python what the value of the element is you want to remove and use the method remove(). There are two functions to do add elements to a list. Append is used to add to the end of a list whereas insert is used to add elements at a specified index. Page 42

46 It can also be useful to order a list either alphabetically or in numerical order. You could for example have a list of scores from a test and you want to list them from highest to lowest. There are two ways to sort a list. Firstly, you can use the.sort() method as shown in the following example. Since lists are mutable, the sort method overwrites your current list to an ordered list. You cannot convert this back to your original list. This is suitable in some cases, but if, for example, you enter the scores relative to your class list, then you will lose track of who received which score. Page 43

47 An alternative is to use the sorted() function which will sort a list but you must store the result in a new variable if you want to re-use the sorted list. This means you could sort a list and use that to do some calculation, for example, find the median, but you will still have access to the original list and the order it was input in. You can also sort a list in DESCENDING order. The default for parameter reverse is False and so would be in ASCENDING order unless otherwise specified. Page 44

48 There is also the possibility to reverse a list. If you have a list of ascending numbers you may want to reverse this so they are descending. You can use the method.reverse(), but this is similar to.sort() above where it replaces your original list. An alternative is to use a subsetting method as shown below. Combining lists Adding two or more lists creates one long list and it can be as simple as using the + operator between each list name. An alternative approach can be to use the extend() method however there is no real benefit to doing so. Other similar data types 1. Tuples - A tuple is a sequence of immutable Python objects. Tuples are sequences but unlike lists, tuples cannot be changed. Tuples use parentheses, Page 45

49 whereas lists use square brackets. An example could be ("Claire", 23) which is a tuple of two elements. You can add tuples to a list and then access elements in a similar way to lists. This is useful if we want to keep related objects together for example name and age of each person in the class. 2. Sets - Sets are lists with no duplicate entries. Sets can become useful when we want to find elements in more than one list or elements in one list that are not in another. It s exactly the same idea as a set in mathematics where you may draw a Venn diagram to visualise where they overlap. It is also an easy way to find the unique elements in a list. Knowledge Point 11.1 Split the sentence "I love to go to the beach" into words and find the length of the result. Does this make sense? HINT: See Chapter Write a function that takes a list and returns a new list with the first and last elements removed Write a function that takes a list and modifies it by removing the first and last elements but returns None. Page 46

50 11.4 Write a function called is_sorted that takes a list and returns True if it is in ascending order and False otherwise Extend this function so that it returns True if the list is in ascending or descending order and returns False otherwise Create a function anagram which takes two strings and determines if they are anagrams of one another i.e. if they contain all the same letters (You may want to ignore the case of the strings that are input). Page 47

51 12 Loops If you want to carry out an operation many times iteratively, loops are essential. There are two important types of loops: a for loop and a while loop. For loops For loops are used when we want to iterate lines of code for a set number of iterations or in other words, repeat code multiple times. This involves looping over a list which can contain numbers or strings. In this first example we create a list and tell Python to loop over each item in that list. So Python will select "Apples", carry out all the code in the loop and then move to the next item, "Pears". It will continue to move along the list until there are no more items. The syntax is important; it begins with for x in y, where y is some list and x is a name used to specify a single item in that list. This means you create a variable x where the first item "Apples" is stored, then after one iteration, you update this variable to "Pears". Any lines of code that must be executed inside the loop should follow a colon (:) and be indented four spaces. A useful function for loops is range (see Chapter 11). As a reminder, range(0,10,2) creates a list from 0 up to (but not including) 10 in steps of 2. In this second example we use this function and update a variable x in each iteration using the looping variable i. Note that since the print statement is not indented, Python knows that this is not part of the loop. Page 48

52 While loops A while loop continues carrying out some code until our condition fails. You must be careful because while loops can continue forever if the condition can never be broken. In the example below, we continually add 7 until the answer is over 20. So Python will check the value of x and if it is less than 20, it will complete another iteration. The example below highlights where you can run into trouble with while loops. We Page 49

53 tell python to subtract 5 while x is less than 20. However since x starts at 10 and is reducing it will always be less than 20! Hence, the code never ends. The user must interrupt python if this happens (use CTRL+C /CMD+C) so be careful when writing while loops. When using an else statement with a while loop, the code after the else statement will only execute once the condition becomes false and the while loop has broken. The while loop continues to increase x by 1 until x is two (x<2 is false), then Python executes the else statements. Control Flow Statements In Python, the statements break and continue help you to control the flow of your loops. A break statement is used to tell Python to exit the entire loop once a condition is met. Page 50

54 In this example, Python loops through each letter in your string. At each iteration, it tests if the letter is equal to "c". If it is not equal to "c", Python continues with the rest of the code (hence printing "a" and "b"). If the condition is met where the letter is equal to "c", the break statement tells Python to stop the entire loop. As you would expect, it breaks the loop. If you wanted a program to run until a criteria is met, you can either use a while loop with a condition, or in other cases it may be useful to use a forever while loop and break the loop once a criteria is met. To generate a loop that continues forever, we use: The continue command is used to skip the succeeding code when a condition is met and move onto the next element in the sequence (iteration in the loop). Again, Python loops through each letter of the string, but in this case when the condition that the letter is equal to "c" is met, Python just skips all the code below the continue statement and moves on to the next iteration, using the letter "d". Note: The following knowledge points are more challenging and include using many Page 51

55 of the functions and concepts learnt across all the chapters. Knowledge Point 12.1 Create a Python program which counts the number of even numbers and the number of odd numbers in a given list Create a function that takes a list of names and returns a list of those which do not contain the letter "a" Design a game where the computer generates a random number between one and twenty and the user must guess this number. The game should respond to the input with "too high", "too low" or "well done" appropriately Extend this game so that you can guess forever until you get it correct 12.5 Change the game so you are allowed five guesses and keep track of the number of guesses the user requires to obtain the correct answer. If they still are wrong, stop the game and tell them the correct answer. Page 52

56 13 Additional Topics 13.1 Vectors/Matrices Vectors and matrices can be created in Python by using the array function from the numpy package. This allows you to add, subtract and multiply vectors, calculate the dot product and cross product and carry out matrix multiplication. A few examples of using Python for vector calculations are shown below: Page 53

57 Similarly, we can use python for matrix calculations and a few examples are: 13.2 Dictionaries We have already seen how Python uses lists and vectors to store information and a dictionary is another way to store data. Dictionaries in Python store everything in key-value pairs where the key is usually a string representing a name for the object stored as the associated value. A value can be a number, a string, a Boolean value, a list and even another dictionary. To understand this, we could think of an actual oxford dictionary. We look up the words in the dictionary to find their definitions. The keys are the words and the values are the related definitions. Dictionaries are specified using curly brackets so an empty dictionary would be {}. The key-value pairs are separated by commas and colons are used to define each pair e.g. {key1:value1, key2:value2}. Page 54

58 In the following example we have three keys (Name, Age and Hobbies) and their three associated values. It is important to know that dictionaries cannot have a specific order and hence no indices. Therefore, we cannot use the same sub-setting techniques used for lists. They are just a collection of unordered key-value pairs. So we use our keys to extract the associated values. Notice that if the dictionary contains a list we can then use list indices in separate succeeding square brackets. If you specify a key which is not defined then you will obtain an error. Dictionary Functions.keys() Returns a list of the keys in a dictionary..values() Returns a list of the values in a dictionary. del dict["key"] Deletes the specified key-value pair from dictionary Page 55

59 dict["newkey"]=value Adds a new key to the dictionary or if key is already defined, replaces the value for that key. dict1.update(dict2) This is a useful way to combine two dictionaries. Any new keys in dict2 that are not in dict1 will extend dict1. Any keys already present in dict1 will be updated with the values from dict Visualisation Python has various packages to help you create really effective graphs. Starting with more basic plots such as line graphs and bar chats, you can use matplotlib. There are plenty of resources online to outline how to create visualisations but a basic plt.plot(list1,list2) will plot elements of list1 on the x-axis against the elements of list2 on the y-axis. A simple example is shown below: Page 56

60 13.4 Exception Handling In Chapter 10 (Knowledge point 10.4), we created a function that checks if a number is an integer and then determines if it is positive, negative or equal to zero. Page 57

61 If we ask the user in input a value using input, this will automatically be stored as a string. Hence our function will always fail. If we try to convert a number entered to a string we may bump into some problems: Page 58

62 Python cannot convert our input into an integer. To overcome this problem we can use a simple exception handling technique. We tell Python to convert the input to an integer if it can, then if an error is produced, we can tell Python an alternative line of code to use (usually output a simple error message to the user). Page 59

63 14 Free Online Resources Some additional resources (as of January 2018) can be found at: Page 60

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6.

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

Chapter 1 Operations With Numbers

Chapter 1 Operations With Numbers Chapter 1 Operations With Numbers Part I Negative Numbers You may already know what negative numbers are, but even if you don t, then you have probably seen them several times over the past few days. If

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Sequence of Characters. Non-printing Characters. And Then There Is   Subset of UTF-8. String Representation 6/5/2018. Chapter 4 Working with Strings Sequence of Characters we've talked about strings being a sequence of characters. a string is indicated between ' ' or " " the exact sequence of characters is maintained

More information

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Working with Strings. Husni. The Practice of Computing Using Python, Punch & Enbody, Copyright 2013 Pearson Education, Inc. Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.

More information

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Excerpt from Art of Problem Solving Volume 1: the Basics 2014 AoPS Inc. Chapter 5 Using the Integers In spite of their being a rather restricted class of numbers, the integers have a lot of interesting properties and uses. Math which involves the properties of integers is

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Workshop 10 11 April 2017 Peter Smyth UK Data Service Accessing the course materials The code snippets used, the file needed for the final exercise, the additional exercises

More information

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

Expressions and Variables

Expressions and Variables Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology Introduction to Python Part 1 Brian Gregor Research Computing Services Information Services & Technology RCS Team and Expertise Our Team Scientific Programmers Systems Administrators Graphics/Visualization

More information

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic. Coding Workshop Learning to Program with an Arduino Lecture Notes Table of Contents Programming ntroduction Values Assignment Arithmetic Control Tests f Blocks For Blocks Functions Arduino Main Functions

More information

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1 Review Midterm Exam 1 Review Midterm Exam 1 Exam on Monday, October 7 Data Types and Variables = Data Types and Variables Basic Data Types Integers Floating Point Numbers Strings Data Types and Variables

More information

Decimals should be spoken digit by digit eg 0.34 is Zero (or nought) point three four (NOT thirty four).

Decimals should be spoken digit by digit eg 0.34 is Zero (or nought) point three four (NOT thirty four). Numeracy Essentials Section 1 Number Skills Reading and writing numbers All numbers should be written correctly. Most pupils are able to read, write and say numbers up to a thousand, but often have difficulty

More information

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops PRG PROGRAMMING ESSENTIALS 1 Lecture 2 Program flow, Conditionals, Loops https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT

LESSON 2 VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT LESSON VARIABLES, OPERATORS, EXPRESSIONS, AND USER INPUT PROF. JOHN P. BAUGH PROFJPBAUGH@GMAIL.COM PROFJPBAUGH.COM CONTENTS INTRODUCTION... Assumptions.... Variables and Data Types..... Numeric Data Types:

More information

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra

Topic 3: Fractions. Topic 1 Integers. Topic 2 Decimals. Topic 3 Fractions. Topic 4 Ratios. Topic 5 Percentages. Topic 6 Algebra Topic : Fractions Topic Integers Topic Decimals Topic Fractions Topic Ratios Topic Percentages Duration / weeks Content Outline PART (/ week) Introduction Converting Fractions to Decimals Converting Decimals

More information

Introduction to Python Programming

Introduction to Python Programming 2 Introduction to Python Programming Objectives To understand a typical Python program-development environment. To write simple computer programs in Python. To use simple input and output statements. To

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

The second statement selects character number 1 from and assigns it to.

The second statement selects character number 1 from and assigns it to. Chapter 8 Strings 8.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: The second statement selects character number 1

More information

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION

NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION LESSON 15 NESTED IF STATEMENTS AND STRING/INTEGER CONVERSION OBJECTIVE Learn to work with multiple criteria if statements in decision making programs as well as how to specify strings versus integers in

More information

C++ Reference NYU Digital Electronics Lab Fall 2016

C++ Reference NYU Digital Electronics Lab Fall 2016 C++ Reference NYU Digital Electronics Lab Fall 2016 Updated on August 24, 2016 This document outlines important information about the C++ programming language as it relates to NYU s Digital Electronics

More information

Lecture 3. Input, Output and Data Types

Lecture 3. Input, Output and Data Types Lecture 3 Input, Output and Data Types Goals for today Variable Types Integers, Floating-Point, Strings, Booleans Conversion between types Operations on types Input/Output Some ways of getting input, and

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

More information

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 4 Working with Strings 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sequence of Characters We

More information

Python Unit

Python Unit Python Unit 1 1.1 1.3 1.1: OPERATORS, EXPRESSIONS, AND VARIABLES 1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC. 1.3: OUR FIRST TEXT- BASED GAME Python Section 1 Text Book for Python Module Invent Your

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

WHOLE NUMBER AND DECIMAL OPERATIONS

WHOLE NUMBER AND DECIMAL OPERATIONS WHOLE NUMBER AND DECIMAL OPERATIONS Whole Number Place Value : 5,854,902 = Ten thousands thousands millions Hundred thousands Ten thousands Adding & Subtracting Decimals : Line up the decimals vertically.

More information

>>> * *(25**0.16) *10*(25**0.16)

>>> * *(25**0.16) *10*(25**0.16) #An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

Fundamentals: Expressions and Assignment

Fundamentals: Expressions and Assignment Fundamentals: Expressions and Assignment A typical Python program is made up of one or more statements, which are executed, or run, by a Python console (also known as a shell) for their side effects e.g,

More information

Chapter 2 Getting Started with Python

Chapter 2 Getting Started with Python Chapter 2 Getting Started with Python Introduction Python Programming language was developed by Guido Van Rossum in February 1991. It is based on or influenced with two programming languages: 1. ABC language,

More information

CME 193: Introduction to Scientific Python Lecture 1: Introduction

CME 193: Introduction to Scientific Python Lecture 1: Introduction CME 193: Introduction to Scientific Python Lecture 1: Introduction Nolan Skochdopole stanford.edu/class/cme193 1: Introduction 1-1 Contents Administration Introduction Basics Variables Control statements

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Workshop 15 December 2016 Peter Smyth UK Data Service Accessing the course materials The code snippets used, the file needed for the final exercise, the additional exercises

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

BEGINNER PHP Table of Contents

BEGINNER PHP Table of Contents Table of Contents 4 5 6 7 8 9 0 Introduction Getting Setup Your first PHP webpage Working with text Talking to the user Comparison & If statements If & Else Cleaning up the game Remembering values Finishing

More information

CS 115 Lecture 8. Selection: the if statement. Neil Moore

CS 115 Lecture 8. Selection: the if statement. Neil Moore CS 115 Lecture 8 Selection: the if statement Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 24 September 2015 Selection Sometime we want to execute

More information

MAT 003 Brian Killough s Instructor Notes Saint Leo University

MAT 003 Brian Killough s Instructor Notes Saint Leo University MAT 003 Brian Killough s Instructor Notes Saint Leo University Success in online courses requires self-motivation and discipline. It is anticipated that students will read the textbook and complete sample

More information

All programs can be represented in terms of sequence, selection and iteration.

All programs can be represented in terms of sequence, selection and iteration. Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational

More information

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017 Basic Scripting, Syntax, and Data Types in Python Mteor 227 Fall 2017 Basic Shell Scripting/Programming with Python Shell: a user interface for access to an operating system s services. The outer layer

More information

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution

More information

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras

Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Privacy and Security in Online Social Networks Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 08 Tutorial 2, Part 2, Facebook API (Refer Slide Time: 00:12)

More information

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2 Python for Analytics Python Fundamentals RSI Chapters 1 and 2 Learning Objectives Theory: You should be able to explain... General programming terms like source code, interpreter, compiler, object code,

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented

More information

Topic 2: Introduction to Programming

Topic 2: Introduction to Programming Topic 2: Introduction to Programming 1 Textbook Strongly Recommended Exercises The Python Workbook: 12, 13, 23, and 28 Recommended Exercises The Python Workbook: 5, 7, 15, 21, 22 and 31 Recommended Reading

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

Python Games. Session 1 By Declan Fox

Python Games. Session 1 By Declan Fox Python Games Session 1 By Declan Fox Rules General Information Wi-Fi Name: CoderDojo Password: coderdojowireless Website: http://cdathenry.wordpress.com/ Plans for this year Command line interface at first

More information

CS 1301 Exam 1 Fall 2010

CS 1301 Exam 1 Fall 2010 CS 1301 Exam 1 Fall 2010 Name : Grading TA: Integrity: By taking this exam, you pledge that this is your work and you have neither given nor received inappropriate help during the taking of this exam in

More information

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Statistics Case Study 2000 M. J. Clancy and M. C. Linn Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below. Name: Date: Instructions: PYTHON - INTRODUCTORY TASKS Open Idle (the program we will be using to write our Python codes). We can use the following code in Python to work out numeracy calculations. Try

More information

Project 2: How Parentheses and the Order of Operations Impose Structure on Expressions

Project 2: How Parentheses and the Order of Operations Impose Structure on Expressions MAT 51 Wladis Project 2: How Parentheses and the Order of Operations Impose Structure on Expressions Parentheses show us how things should be grouped together. The sole purpose of parentheses in algebraic

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Mathematics. Name: Class: Transforming Life chances

Mathematics. Name: Class: Transforming Life chances Mathematics Name: Class: Transforming Life chances Children first- Aspire- Challenge- Achieve Aspire: To be the best I can be in everything that I try to do. To use the adults and resources available both

More information

Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions.

Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions. 1.0 Expressions Dr. Scheme evaluates expressions so we will start by using the interactions window and asking Dr. Scheme to evaluate some expressions. Numbers are examples of primitive expressions, meaning

More information

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates Chapter 3 : Informatics Practices Class XI ( As per CBSE Board) Python Fundamentals Introduction Python 3.0 was released in 2008. Although this version is supposed to be backward incompatibles, later on

More information

Computational Programming with Python

Computational Programming with Python Numerical Analysis, Lund University, 2017 1 Computational Programming with Python Lecture 1: First steps - A bit of everything. Numerical Analysis, Lund University Lecturer: Claus Führer, Alexandros Sopasakis

More information

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

More information

Introduction to computers and Python. Matthieu Choplin

Introduction to computers and Python. Matthieu Choplin Introduction to computers and Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ 1 Objectives To get a brief overview of what Python is To understand computer basics and programs

More information

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0 VISUAL GUIDE to RX Scripting for Roulette Xtreme - System Designer 2.0 L J Howell UX Software 2009 Ver. 1.0 TABLE OF CONTENTS INTRODUCTION...ii What is this book about?... iii How to use this book... iii

More information

Real Python: Python 3 Cheat Sheet

Real Python: Python 3 Cheat Sheet Real Python: Python 3 Cheat Sheet Numbers....................................... 3 Strings........................................ 5 Booleans....................................... 7 Lists.........................................

More information

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

9. Elementary Algebraic and Transcendental Scalar Functions

9. Elementary Algebraic and Transcendental Scalar Functions Scalar Functions Summary. Introduction 2. Constants 2a. Numeric Constants 2b. Character Constants 2c. Symbol Constants 2d. Nested Constants 3. Scalar Functions 4. Arithmetic Scalar Functions 5. Operators

More information

Math Day 2 Programming: How to make computers do math for you

Math Day 2 Programming: How to make computers do math for you Math Day 2 Programming: How to make computers do math for you Matt Coles February 10, 2015 1 Intro to Python (15min) Python is an example of a programming language. There are many programming languages.

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Week 03: Data Types and Console Input / Output Introduction to Types As we have already seen, 1 computers store numbers in a binary sequence of bits. The organization

More information

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information