Python Instruction Booklet v7.2

Size: px
Start display at page:

Download "Python Instruction Booklet v7.2"

Transcription

1 In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, see In 2001, the Python Software Foundation (PSF, see was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF. Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI,) in Reston, Virginia where he released several versions of the software. Python Instruction Booklet v7.2 Learning to use Python at Stanground Academy Name

2 Contents Contents... 1 Using the IDLE in Interactive Mode... 3 Hello World... 4 Session 2 - Using IDLE and Saving Programs... 5 Session 3 - Interactive Programming Session 4 - Introduction and storing variables Storing Data in Variables Session 5 Calculations and different variables Calculations Another look at Variables Session 6 - Initiating Variables Data Types used in Python Assessment; Sessions 1 to 7 Target 7 Secure Session 7 - Selection: The if statement Control structures A Note on Indentation Session 8 Iteration: Condition Controlled Loops Python Libraries and Random Session 9 Iteration: Count Controlled Loops Session 10 - Subroutines: Procedures and Functions Session 11 - ARRAYs and LISTS Creating arrays in code Session 12 - String Handling String constants Upper and lower case ASCII characters Trace tables Session 13 - File Handling Creating one program to create, store and access values Session 14 Creating a menu Session 15 Robust code and error checking Create a function to check data entry Session 16 Error messages Parse error Type error Name error Value error Import error Indentation error Index error Session 17 Turtle Graphics Session 18 - Classes, TkInter and a GUI A Graphic User Interface using TkInter Building a GUI Session 19 Sorting Bubble sort Insertion sort Appendix 1 Flowchart symbols and examples Appendix 2 - Cheat sheets Python Instruction Booklet v5.1

3 Session 1 Introduction to Python Open the IDLE Python GUI which is the Integrated Development Environment (IDE) (called IDLE after Eric Idle who is a Python). First, you will have to open Virtual Box. You will find it in your All Programs Menu under ICT. Figure 1: Eric Idle Virtual box Virtual box is a temporary computer within the real computer that you are using so that you can use additional software such as Python. Accept all of the messages by pressing OK until a new copy of Windows is loaded. Key terms Key terms will be explained or described in the boxes on the right hand side of the page such as this one. Progress Always record your progress on the back page of this booklet as you work through each of the exercises. 2 Python Instruction Booklet v5.1

4 From the new start button in the virtual version of Windows you can select Start All programs Python 3.2 and then IDLE. Using the IDLE in Interactive Mode Open Python as described above and you will see this: This is the Python Shell where you can type in instructions to Python that will be carried out immediately. 3 Python Instruction Booklet v5.1

5 Hello World All programmers start with the program Hello world. It s very much of a rite of passage. Exercise 1 Copy and run the following program in Python in interactive mode (first Window in IDLE). print( Hello World ) (case sensitive, as are all commands in Python) You will hopefully see the message Hello World as shown below. print ( xxx ) will work as will print ( xxx ) (N.B. speech marks) But Print ( xxx ) won t because Python does not accept capitals in commands such as print Exercise 1a Change the program so that it prints out: Pleased to meet you Student answer Exercise 1b Write a program to display using apostrophes rather than speech marks: This is Paul's first program The apostrophe makes this trickier than it first may seem. Use a combination of and characters try it and see. Is there a difference? 4 Python Instruction Booklet v5.1

6 Session 2 - Using IDLE and Saving Programs When using the IDE (IDLE) in Script Mode IDLE is in effect a word processor for Python programmers. Using interactive mode is fine if you want to look at one line programs or use notepad to write programs and copy them into IDLE but for real programs you need to write and save your program and then run it. Open Python and you will see the IDLE window Now select File and then select New Window. A new window will open looking just like the one below. It is slightly different from the interactive window as it is currently untitled and has no Shell menu tab. This window is called a Script Window and a new one is opened for each new program you want to write. You can only write programs in the Script Window and not in the Shell. 5 Python Instruction Booklet v5.1

7 Now type into this new window: print ( Hello New World ) and press enter. Hopefully nothing will happen except the cursor moves to a new line. Now go to the Run Menu and the select Run Module (you can just press F5 at any time to run your program). You will be asked to save the program save it into a folder as shown below. You are working in a Virtual computer so take care when you save. If you save to drive C: then when you exit all your work will vanish. Any work lost in this way cannot be recovered so it is up to you to make sure that all your work is saved correctly. You must select Computer 6 Python Instruction Booklet v5.1

8 and then Drive H: I saved it into a Folder I made in My Documents that I called Python. Filenames Make sure that you include the.py extension in a filename. It is very important that you do not save files with the same names as the main Python libraries. This will affect the way that Python works for you when you are creating code. 7 Python Instruction Booklet v5.1

9 Name your files with the name of the exercise that you are attempting so that you can keep a close check on your progress. Note that the PC is supposed to save it as a type.py this means the PC recognises it as a Python File. When you run Python on your PC at school you will have to add the.py yourself. You will know if you need to do this as your program in IDLE will change from multi coloured to all black if it doesn t have the correct extension suffix. Syntax Syntax is simply the rules of the language. Once you have saved it, if necessary press F5 again and the program will run. Below you should see what happens. Exercise 2a Try typing in the following program: Remember the syntax is important and be careful when you use capitals. Type in the following Run the program by using menu: Run Run Module (or F5). Save to your Python folder when prompted and you should see what is shown below. Case sensitive It is very important to know that Python is case sensitive. Print() is not the same as print() and only print() works correctly to put text on the screen. 8 Python Instruction Booklet v5.1

10 Exercise 2b Try this; the \n command at any point in a line of text will force a new line: Academy Address You should see something like this: The Stanground Academy Peterborough Road Peterborough PE7 3BY Exercise 2c Write a program to correctly display the address of the academy in a single line of code. Student answer Extension - Exercise 2d Write a program to correctly display exercise 2a in a single line of code. 9 Python Instruction Booklet v5.1

11 Session 3 - Interactive Programming We have run some simple programs now we will look at how to make the programs interactive. By interactive we mean making a program wait for a user to input some data and then respond in some way. The first command we will look at is the input command (note; this is still lower case). Copy in the following program (note; variables are not normally given capital letters in Python e.g. we use name not Name. This is just a convention and has no effect on the way the program runs.) Comments Comments are used to allow a programmer to add notes to the program so that others will understand what he is doing. I have done this below with some comments using the # sign. Students will be asked to add comments to their programs when you do the controlled assessment. The example below also demonstrates that too many # comments can actually make a program harder to read Run the program (F5) and when prompted save to your Python Folder; it should look like the example below. I used the name John when asked; you can use what you like. 10 Python Instruction Booklet v5.1

12 Exercise 3a Write a program that asks for your favourite type of music and then replies I love {your choice} as well. e.g. Printing a response Start Music = What music do you like? Music = music + I love your choice. Print music Student answer stop Exercise 3b Write a program that asks for your first name, then asks for your last name and finally prints out a greeting including your full name. e.g. Flowcharts From time to time flowcharts will be included so that you can see what an algorithm looks like as code and as a flowchart. There are two ways to achieve this one uses a blank space the other involves investigating the difference between using the + (concatenating) and the, to separate the variables. Try both of these now. We will look into the both these methods in more detail in later lessons. Extension: (exercise 3c) get Python to ask for your favourite subject as well. Student answer 11 Python Instruction Booklet v5.1

13 Session 4 - Introduction and storing variables Storing Data in Variables We need a mechanism for tracking values and changes of values in a program. We do this in high level programming by using what we term as variables. A typical variable usage would be a = 6 which assigns the value of 6 to the variable a In programming we try and assign meaningful variable name e.g. name, age, or postcode. Be a little careful here as I have seen variable names that are so complex in order to simplify understanding they make the program hard to follow. For example: student_inititial_id_parameters which is neither meaningful nor easy to use. Another issue with variables when students learn is they forget that a variable is only a name i.e. it has no meaning to a computer. e.g. a variable called date could be written dote or dite. To the program it is just a variable and has no special significance but students can forget this and try and read special meaning or believe they must use specific names for variables. This is particularly a problem understanding a concept and using variables such as result or value Data Types Every variable has a name, a data type and a value. The most common data types are: string Text made up of numbers, letters and characters. integer Whole numbers. (e.g. 1, 78, 0 and -54) float/real Decimal numbers (e.g , , -6.3). Float comes under the umbrella of what we often refer to as Real numbers. Boolean True or False Variables. Variables in a computer program are to be thought of as "Buckets" or "Envelopes" where information can be stored and referenced. On the outside of the bucket is a name. When referring to the bucket, we use the name of the bucket, not the data stored in the bucket. Inside the bucket is its value. In some programming languages we have to tell the computer what data type a variable is going to be. E.g. in VB we say DIM name as string = or DIM age as Integer = 0 12 Python Instruction Booklet v5.1

14 Python, on the other hand, is able to decide the data type of the variable according to what value it is first given (or to use the correct term; with what it is initialised). e.g. age = 23 will automatically initialise a variable called age as an integer variable and assign a value 23 to age and define the variable as an integer Exercise 4a Open Python and you will see the IDLE window Now select File and then select New Window. A new window will open looking just like the one below. Copy in the following program note variables are not normally given capital letters in Python e.g. we use name not Name. This is just a convention and has no effect on the way the program runs. name= Bob print( hello + name) Do not copy and paste from MS Word as it will not work because MSWord/IDLE mismanage the apostrophes. Students will always try and do this so feel free to try later to see examples of the error messages. Run the program (F5) and when prompted save to your Python Folder and it should look like the example below. 13 Python Instruction Booklet v5.1

15 Exercise 4b Try another program IDLE puts the colours in automatically so if your program does not run check the syntax by comparing the colours on the screen shot and the colours in the code you have written. language= Python print( This program is written in [YOU FINISH OFF THE PROGRAM AND RUN IT] Student answer Exercise 4c We can change the value of a variable within the program. Try running this program this and explain the result: 14 Python Instruction Booklet v5.1

16 Student answer Exercise 4d Here is another one Now explain the outcome. Student answer Whereas, if we use the program: The secret is in the use of the + symbol in the program which is used to connect the two strings together. This joining is called concatenation in programming Now explain difference between the outcomes of the two programs (Hint: again the + symbol is the key). 15 Python Instruction Booklet v5.1

17 Student answer Finally, using the following variables word1='the' word2='cat' word3='sat' word4='on' word5='mat' write a program to print the cat sat on the mat. The trick is the use of spaces in the print command. You don t want a space in the variable so you need it in the command. For example: will output Student answer 16 Python Instruction Booklet v5.1

18 Session 5 Calculations and different variables Calculations We can carry out calculations in Python. The arithmetic operators we use to do this are: + addition - subtraction * multiplication / division DIV = Dividend (integer only) MOD = Modulo = remainder (integer only) In interactive mode try the following program: divmod (6, 4) <enter> which should return (1, 2) 6 divided by 4 is 1 remainder 2 Run the following program: What was the output? Student answer Another look at Variables Variables aren t just used for words (strings), they are also used to store the value of numbers. 17 Python Instruction Booklet v5.1

19 We can put the results of any calculations into variables that we choose. These variables will not be strings but will be integers (whole numbers) or float (decimal). Exercise 5a Copy and run this program: Arithmetic in Python (Alternative to Exercise 5a) Start A = 25 B = 7 X = a / b Print X What does Python make the answer? Stop Student answer Exercise 5b Complete this program below so that it adds the two variables a and b to make x equal to 16 then prints out the result: Change the values of a and b and see if Python can do the maths. Student answer 18 Python Instruction Booklet v5.1

20 Session 6 - Initiating Variables Every variable has a name, a data type and a value. In Python when a value is assigned to a variable, Python automatically assigns the data type Data Types used in Python The most common data types are: string Text made up of numbers, letters and characters. integer Whole numbers. (e.g. 1, 78, 0) and negative numbers (e.g. -54) float boolean Decimal numbers (e.g , , -6.3). Float are also often referred to as Real numbers. True or False (meaning the variable is assigned a value of either 1 or 0) (Boolean is named after George Boole ( ) who developed the mathematics of logic.) In some languages we have to tell the computer what data type a variable is going to be. Python, on the other hand, is able to decide the data type of the variable according to what value it is first given (or to use the correct term, with what it is initialised). This can cause problems when we try to do something with the wrong data type. See example below: Exercise 6a Copy and run the following program: If you enter the numbers 5 and 4 the program will output 54. This is because Python treats anything received through the input function as a string. We need to tell Python we want to convert this string to an integer before putting it into the variable. This is done using a something called type casting (we use the term cast but it just means change or turn). To turn (cast) the strings 5 and 4 into integers we use the int() function 19 Python Instruction Booklet v5.1

21 There are two ways of doing this variable = input( prompt ) or Which does the same thing and is the way we will normally do it in our programs. The function input() requests a value from the keyboard as a response to the prompt or question and stores the result in a variable. Exercise 6b Try this program: Exercise 6c Write a program that asks for a length and width and outputs the area of a rectangle. e.g. Exercise 6e Using exercise 6b as a start, write your own program to find the area of a triangle of height h and width w. Exercise 6d If you want to print out the result with 2 decimal places you can use the round() command. I used a variable a for the area and this line of code to round down or up just before printing the output: e.g. a = round( a, 2) try this: Area of a rectangle Start Input height Input width Area = height * width will print out 2.87 Print Area Stop 20 Python Instruction Booklet v5.1

22 Whereas the int() command round down any floating point number. In actual fact Python merely truncates the number back to its decimal point. Using a library. will print out 2. Exercise 6d - Converting integers into real numbers (float) The formula for the volume of a cylinder is: π r 2 h and for its surface area is: 2π r 2 + 2π r h. where r is the radius and h the height. π is the value (to 5 decimal places) Assume that the user may enter the radius and height as real numbers. To turn (cast) these into real numbers for the calculation you will need to use float() command. Write a program that asks you for the radius and height of a cylinder then calculates the volume and area. Python has access to lots of additional functions grouped together in libraries. There is a library called math that contains many exciting maths functions. PI is one of them. To access the math library add the line of code import math and to use pi use math.pi Student answer Include the value of pi in your program so that you do not have to enter it when the program is running Here is my result after running the program: Constants. Some values are constant and never change, such as pi. Using a programming constant means that you can reduce programming errors and speed up the creation of good code. 21 Python Instruction Booklet v5.1

23 Assessment; Sessions 1 to 7 Target 7 Secure Select the correct answer by ticking the box from the 4 options given for each question. 1. IDE is short for: a) Integrated Development Engine. b) Impossibly Difficult Engine. c) Integrated Development Environment. d) Improved Design Environment. 2. Printing Hello World Which of the following Python statements will print Hello Word on the screen? a) Print Hello World b) print Hello World c) Print ( Hello World ) d) print ( Hello World ) 3. Saving files We have to add the.py file extension when saving Python files. What happens if this is missed out? a) The file will not save. b) The file will not run. c) The colour coding of the text in the IDE disappears. d) The file will vanish when virtual box is shut down. 4. Syntax The meaning of the word Syntax is: a) A library in Python. b) Microsoft s rules for programming. c) The rules of any programming language. d) The tax charged by the government on beer and cigarettes. 5. New line The code to get Python to print on a new line is: a) /n b) newline c) \n d) \n 22 Python Instruction Booklet v5.1

24 6. Errors in the code. Copy and run this code; use your experience and the IDE to help you to find the five deliberate errors. Write one error in each box a) b) c) d) e) 7. Writing code. The formula for the area of a sphere is 4πr 2 and the formula for the volume of a sphere is (4/3)πr 3. Write a program that will ask the user for a radius and then work out the area and volume of a sphere. Copy the program neatly here. If you test it with a radius of 10 then the answer should be 23 Python Instruction Booklet v5.1

25 Session 7 - Selection: The if statement Control structures Programs written in procedural languages such as Python, are like recipes, having lists of ingredients and step-by-step instructions for using them. The three basic control structures in virtually every procedural language are: 1. Sequence combine the liquid ingredients, and next add the dry ones. 2. Conditional if the tomatoes are fresh then simmer them, but if canned, skip this step. 3. Iterative beat the egg whites until they form soft peaks. Sequence is the default control structure; instructions are executed one after another. They might, for example, carry out a series of arithmetic operations, assigning results to variables, to find the roots of a quadratic equation ax2 + bx + c = 0. The conditional IF-THEN or IF-THEN-ELSE control structure allows a program to follow alternative paths of execution. Iteration, or looping, gives computers much of their power. They can repeat a sequence of steps as often as necessary and appropriate repetitions of quite simple steps can solve complex problems. You may remember the IF function in Excel. In all high level programming languages (including Python) there is an IF function to test for certain conditions. A Boolean condition is one that can have only two values true or false (1 or 0, yes or no). The Boolean comparison operators used in python are as follows: Operator Meaning = = Equal to! = (<> is out of date now) Not equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to 24 Python Instruction Booklet v5.1

26 Exercise 7a Try this as a program. Checking the value of a variable Start Letter = a The indent and the colon are important as Python uses them to manage the if statement. This program doesn t really do much it s just an example. yes If letter = a no Stop Print statement Note we are using the apostrophe ' rather than speech mark " as we said earlier they are interchangeable but can cause problems if you are using apostrophes in your print statements e.g. can't. Run the program above and save when prompted. We can add as many statements we want inside the if statement. Each should be indented. At the end of an if statement, we remove the indentation. In effect the colon in the expression is the word THEN. So in the example if the letter is a then it will print everything that is indented. If the letter is not a then the indented lines are never executed. See below: We can tell the computer to do something different when the condition isn t true using the else keyword. 25 Python Instruction Booklet v5.1

27 Exercise 7b Now extend your program to include the option of the letter not being a. Exercise 7c You can extend the IF statement by using an abbreviation of the ELSE IF function in Python this is written elif. (Elif is short for Else if ) A Note on Indentation When you start a new line after a colon (if you re writing it using IDLE) you should find your code indented). Lines will keep indenting until you press backspace. Python knows that anything indented is inside the structure with the colon - in this case the if. Indenting is considered good practice in all programming languages as it makes code easier to read but in Python it is even more important as it affects the code s meaning. For more complex conditions we can use and, or and not. A common mistake would be to write the IF line as if x>=1 and <=100 missing out the second x. This is wrong and will generate an error. 26 Python Instruction Booklet v5.1

28 Exercise 7d A slightly more complex task; enter the code below and run the program Thought? When you ran the program and answered with paris what happened. This snippet of code might help you in future. Student answer Truth tables We use truth tables to make sure that when logical statements are combined we know the effect on the truth of the combined statement. If statement A is True and Statement B is True then the truth table for And says that the statement A And B is True. If statement A is True and Statement B is False then the truth table for Or says that the statement A Or B is True. If statement A is False and Statement B is False then the truth table for Or says that the statement A Or B is False. Truth Tables A B AND OR T T T T T F F T F T F T F F F F Exercise 7e On your own, extend the program to ask two questions about different cities. 27 Python Instruction Booklet v5.1

29 Exercise 7f Below is a program that asks for three numbers and outputs SNAP if they all match. The examiner is very keen on making the code that you write more efficient. You need to show both versions and explain what you have done to make the code more efficient and explain how the code is more efficient that the first version. Use your knowledge of the and, or and not operators to make the program more efficient. Student answer 28 Python Instruction Booklet v5.1

30 Session 8 Iteration: Condition Controlled Loops One of the things that makes computers so useful is the speed at which they do things. This makes them useful for when we want them to do something over and over. We call this iteration or looping. We will look at two types of loop, the first of which is a condition controlled loop. These are loops which continue to repeat code while a condition is true. These are exactly the same type of conditions we looked at when using if. Exercise 8a We want a program that will print the word looping 5 times A WHILE loop printing Looping 5 times Start Set X = 0 Print Looping X = X + 1 (increment X) X = 5? no yes Print Finished If we run the above code you will find it goes on forever printing looping. that is because x remains 0 and so is always less than 5. You can try this if you wish but you will need to go to File/exit to stop it. Stop Let s fix the program will this work? As we know the indentation is very important so it should really look like this. Flowchart for asking for a password Start Exercise 8b Password = input password Write a program that asks for a password and keeps asking until the correct password, apple is entered and then says Password Accepted. Password = apple Yes No Wrong passwrod This will revise your knowledge of the input command. Try and use a sensible variable (e.g. pass) when it is running use the print command to print meaningful hints like "Wrong Password" and Correct password Stop 29 Python Instruction Booklet v5.1

31 "Correct" Student answer Exercise 8c The sequence 1,4,9,16,25 is made up of square numbers (i.e.1=1 2, 4 = 2 2, 9=3 2 etc.). Write a program that writes out all the square numbers under You have done squares in an earlier task keep doing the square and test for greater or equal to Print out the squares and print finished when completed. Python Libraries and Random The following code will create an integer x that is a random number between 1 and 100. The line import random has to be put at the very top of the program but does not need putting in the program again. You can use the random.randint() command wherever you want after that but remember to assign it to a variable e.g. numb = random.randint(1,10) This will give a random integer value between 1 and 10. Exercise 8d Write a program in which the computer thinks of a number between 1 and 100 (i.e. picks number at random). It should then ask the user to guess what number it is thinking of. It should then say whether the number the computer is thinking of is higher or lower than the one guessed. If the user guess correctly it should say well done and say how many guesses it took them, if not it asks them to guess again. 30 Python Instruction Booklet v5.1

32 It might help to write this in rough using Pseudo code (almost Python but in plainer English) this will help sort out the sequence. Pseudo code is another form of algorithm. We are not worried about elegance, just getting into the habit of writing complex problems in a simpler form before writing the program Required Output I am thinking of a number between Can you guess what it is? 50 No, the number I am thinking of is higher than 50. Can you guess what it is? 80 No, the number I am thinking of is lower than 80. Can you guess what it is? 60 No, the number I am thinking of is higher than 60. Can you guess what it is? 64 Well done! The answer was 64 and you found it in 4 guesses. Using a library. Python has access to lots of additional functions grouped together in libraries. There is a library called random that contains a number of random number functions that you can use. To access the random library add the line of code import random and to use random numbers use x = random.randint(1.100) Here is the code. To paraphrase the late great Eric Morecombe, here are all the right lines of code, not necessarily in the right order guesses = 0 answer = False while answer == False: guess = int(input("can you guess what it is? ")) import random if guess > number: print("no, the number I am thinking of is lower than ", guess) guesses = guesses + 1 else: print("i am thinking of a number between ") print("well done! The answer was ", number, " and you found it in", guesses, "guesses.") answer = True number = random.randint(1,100) elif guess < number: print("no, the number I am thinking of is higher than ", guess) guesses = guesses + 1 Figure 2: Eric Morecombe 31 Python Instruction Booklet v5.1

33 Student answer Python Instruction Booklet v A flow chart to guess a number Student answer Start Number = random number between 1 and 100 Guesses = 0 Print I am think of a random number between 1 and 100) Input player s guess; stored as Guess If Number = Guess? If number > Guess Too low Print Well done Too high Stop 32 Python Instruction Booklet v5.1

34 Session 9 Iteration: Count Controlled Loops As we said in the last session one of the things that makes computers so useful is the speed at which they do things. This makes them useful for when we want them to do something over and over. We call this iteration or looping. We will look at the second type of loop, which is a count controlled loop. This is when a program carries out a set of instructions a certain number of times. To do a count controlled loop we use the for command. Exercise 9a Notice how anything inside the loop is indented. will output Iteration. Iteration is repeating segments of code either until a condition is met or for a fixed number of repetitions. Unlike a WHILE loop a FOR loop does not need code to change the looping variable. In the loop for i in range(x,y), 0 is the starting value of i and 5 is the amount of times it will loop that is to say the final value of i. So above it runs with i equal to 0,1,2,3 and 4 (not 5 because the loops stops when I = 5) Traditionally loops tend to use the variables i, j and k and you will see lots of code that conforms to this convention. There is, however, no reason why you can t use any other variable name especially if it makes your code more readable. Try this program as an extension of 9a: As with the if statement the indent and the colon are important as Python uses them to manage the for statement. It will print out looping for each value of i as the program goes around the loop and adds 1 to i each time. 33 Python Instruction Booklet v5.1

35 Exercise 9b A slightly more complex task; enter the code below and run the program Change the program below so that it outputs the word computing 15 times. Student answer Exercise 9c Using the input command you learnt earlier, write a program that asks for a number then outputs it s times table up to 10. Example Output. Please enter a number: 7 1 times 7 is 7 2 times 7 is 14 3 times 7 is 21 4 times 7 is 28 5 times 7 is 35 6 times 7 is 42 7 times 7 is 49 8 times 7 is 56 9 times 7 is times 7 is Python Instruction Booklet v5.1

36 Student answer 35 Python Instruction Booklet v5.1

37 Session 10 - Subroutines: Procedures and Functions We are in new territory now as Procedures and Functions are very much aspects of higher level programming. It is possible to write a whole program as one big block but where possible we want to break it down into subroutines chunks of code. There are several advantages to this: The program becomes easier to read. The program becomes easier to test. If you have tested a subroutine you don t have to worry about it when you subsequently use it. Subroutines can often be re-used meaning code does not need to be rewritten. We will start off with a procedure (subroutine) that prints out This is a subroutine 3 times. In Python for ease of reading the subroutines come before the main program. The line: def mysub(): defines the subroutine; the name is just for show and convenience in understanding. The brackets are a part of Python Syntax and cannot be missed out. Having defined the subroutine we now go to the main program. Both parts (the subroutine and the main program) are required for the program to work. 36 Python Instruction Booklet v5.1

38 Now we put this all together as a program Exercise 10a The # comments are optional but good practice. We can use parameters to make subroutines even more useful. Parameters are a way of taking some values (numbers or strings of text) to be used by the subroutine. For example the parameters in the subroutine below are text and times: Exercise 10b Try this program. Procedures. The function mysub() now has two parameters text and times that are passed from the main program to the function, The parameter text in MySub has the value My name is Jack and the parameter times has the value Python Instruction Booklet v5.1

39 The subroutines we have looked at so far are called procedures. The other type of subroutine we use is a function. A function is a subroutine that returns a single value. That means we can use it within other statements. We use the return keyword to send the value back to the main program. Exercise 10c Try this and see if you can make it work correctly. Include the comments. Parameter passing. In this example the variable a is used as the parameter number in the function double. The result of the calculation is then sent back to be used in the print statement. Exercise 10d Write a function called convert that converts degrees Celsius to Fahrenheit, where F = C * 9 / In the main program input a value and then call the function. Student answer If you feel really keen use input and if to offer the choice between F to C or C to F. There are quite a few ways to do this try writing a flow diagram first. To help here is the re-arranged formula C = ( F - 32) x 5/9 38 Python Instruction Booklet v5.1

40 Session 11 - ARRAYs and LISTS Arrays are common to all programming languages but in Python the restrictions that normally apply to arrays have been removed and the result is referred to as lists rather than arrays. If we think of a variable as a box, we can think of a list as a collection of boxes containing data. Each box has an address (called an index) starting at 0. For example a list called Names might look like this: Names Contents Alf Betsy Charlie David Box Number (Index) Arrays. An array is a data structure that contains a group of similar elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched. The following snippet of Python code produces the list called Names. Names Alf Betsy Charlie David Box Number (Index) Exercise 11a We can then access any element of the list by giving its index in square brackets. will print Charlie 39 Python Instruction Booklet v5.1

41 What statement will output Betsy? Student answer We can also alter the contents of the list by referring to the elements by their index. Changes the list to: Names Alf Betsy Bob David Box Number (Index) and the program will print: Bob. If we start off with our list empty we can create it with just two empty square brackets. To add entries to the list we then call the append function which will automatically manage the index and put the names in order in the list. Exercise 11b Try this: 40 Python Instruction Booklet v5.1

42 will output To remove an item from the list we use the pop method if we want to remove by index will output (The first item is index 0 so item 1 is Sebastian ) If we know the item we want to remove we can use the remove function which deletes the first instance of it. Exercise 11c Try this: will also output To get the number of items in a list we use the len command. Makes x the number of names in the list. 41 Python Instruction Booklet v5.1

43 Exercise 11d Try this: We can cycle through a list with a for loop as shown below: will print Exercise 11e Write a program that keeps asking for names until the word END is entered at which point it prints out the list of names as shown below. Please enter a name: Sebastian Please enter a name: Quincy Please enter a name: Sam Please enter a name: Susan Please enter a name: Julie Please enter a name: END You have entered 5 names. [' Sebastian ', ' Quincy ', 'Sam', 'Susan', 'Julie'] Student answer 42 Python Instruction Booklet v5.1

44 Exercise 11f Write a program that asks the user to enter 5 names which it stores in a list. Next, get it to pick one of these names at random and declare that person as the winner. e.g. Please enter a name: Sebastian Please enter a name: Quincy Please enter a name: Sam Please enter a name: Susan Please enter a name: Julie You will need to generate random numbers using import random and random.randint(1,5) Well Done Susan you are the winner! Student answer Two Dimensional Arrays/Lists List\array index Row Row 1 Sam Tom Tim 43 Python Instruction Booklet v5.1

45 Exercise 11g Enter the code below: Will output when run: Here is another example: Results in: Exercise 11h Now write a python program to ask for a person s first and last names and the year that they are in and it will output their school username. Student answer 44 Python Instruction Booklet v5.1

46 Creating arrays in code It is frequently important to create arrays of a set size in code. Here is an example that shows how to create and use 1 and 2 dimensional arrays in a Python program. I have highlighted the two important parts of the code that you may wish to make use of in your own projects. This is the code to create an array. Image is 2 dimensional and answer is a 1 dimensional array. This code will print out a 2 dimensional array as a grid. The format instruction '{:4}'.format(item) allocates exactly 4 spaces for each item in the array in the array. The first highlighted line of code creates a two dimensional array, in this case it is a 6 x 6 array called image. Note that it is a nested loop that has a counting variable x. The second highlighted line creates a 1 dimensional array of 6 values. The highlighted print statement is a clever way of printing a 2 dimensional array in a single statement that you may wish to use. This is the result. 45 Python Instruction Booklet v5.1

47 Session 12 - String Handling There are many ways of handling text (called strings) in high level programming languages and Python is no exception. Often we want to perform operations on strings. This may involve cycling through letters in the string. This is particularly easy in Python as we can do it in a for loop. Exercise 12a Copy and run the following program. Sometimes we might just want part of the string. We can do this by treating the string as a list of characters. E x a m p l e s We can then refer to letters by their index (remembering that a list starts at index 0). So will output: If you want a group of letters this is done using the following commands. String name [position of first letter : position after last letter] For example: outputs: and 46 Python Instruction Booklet v5.1

48 outputs: If we want the length of a string we use len just like we did with lists. So: outputs: If you need to find if one string exists in another then the use of in is very helpful as in the example below. outputs: String constants There are a number of useful functions built into the string library that you can use. For example there is a constant that contains all the letters of the alphabet. This works equally well for the uppercase characters. The alternative would be to create your own variables. 47 Python Instruction Booklet v5.1

49 Exercise 12b Change the previous program so it counts the number of occurrences of the lowercase letter a in the word admirable. Student answer 48 Python Instruction Booklet v5.1

50 Exercise 12c Write a program that takes in a word and says whether or not it is a palindrome. (A palindrome is a word that is the same backwards as forwards like noon and radar). How would you make python count backwards? A for loop with a twist. Student answer Testing a palindrome Start Word = Input word to test Reverse Word and store result in Reverse If Word = Reverse? no Print Word is not a palindrome yes Print Word is a palindrome Stop 49 Python Instruction Booklet v5.1

51 Upper and lower case There may be a time when you will need to convert letters to all upper case or all lower case. The use of upper() and lower() will do this. gives ASCII characters As you know there is an ASCII code for each letter and symbol that you can use. The functions that convert from ASCII to the character or the character to ASCII are chr() and ord(). For example this program will print out all of the characters in the extended character set. Using the program you will note that the digits 0 to 9 are values 48 to 57, the lower case letters are values 97 to 122 and the upper case letters are values 65 to 90. Trace tables Now that the code that you are writing is getting more complicated how do you know that the code you write will produce the results that you want? Use a TRACE TABLE to record the changes in a variable as the program works from one line to the next. First of all work out all the variables that are in the program: name letter count 50 Python Instruction Booklet v5.1

52 i Now create a table based on the number of variables like this (one column for each variable): Iteration Name Letter Count i (Note: iteration is the number of times that the program has been round the loop.) Now work through the program one line at a time writing down each variable s value as you go. I am going to search for the letter e in the name Evangeline. The trace table will be: Iteration Name Letter Count i 1 Evangeline e 0 E 2 Evangeline e 0 v 3 Evangeline e 0 a 4 Evangeline e 0 n 5 Evangeline e 0 g 6 Evangeline e 1 e 7 Evangeline e 1 l 8 Evangeline e 1 i 9 Evangeline e 1 n 10 Evangeline e 2 e It is now clear to see where the program makes the change to the variable count. 51 Python Instruction Booklet v5.1

53 Exercise 12d Here is a program based on a GCSE examination question. Write and test the program and then complete a trace table in your own notes. Iteration Carriages Total Passenger Max Index Index starts at 0 and increases by one, every iteration. The program tells you what values to use at the start for the other variables. 52 Python Instruction Booklet v5.1

54 Session 13 - File Handling Files are for permanent storage of data What are files and why do we need them? Around the average classroom you will see piles of folders with all sorts of information in them. Some will be just piled in a corner in no particular order perhaps just by class, some will be in order (perhaps alphabetical and class) and some will be in a nice cabinet in order and clearly identified for easy retrieval of information. All of these are filing systems in the real world some being more sophisticated than others In computers we can also store information in folders and files with the level of sophistication being dependent on how organised we are on our PC. However in high level computer programming languages (and Python is no exception) we have the capability to construct sophisticated filing systems (a bit like a virtual filing cabinet) and then add and retrieve information from the filing system. Variables and Lists allow you to store and access data when a program is running; however the data is lost when you close the program. If you want to store data and access it at a later date, you need to save the data in such a way that it can be retrieved later. We do this in Python by storing the data in a text file. To create or open a file Most real world programs need to be able to read and write data to files. Fortunately Python makes this process extremely easy to do. To get Python to write to a file we first open it, write what we want to it and finally close it. The clever thing about Python is that you do not need to build your virtual filing cabinet first. As soon as you write to a file and give it a name Python will automatically build you virtual filing system and start putting files of documents in it. Exercise 13a This is the first line of the program. This line of code creates a logical file called myfile Python will create this and save it as an actual text file with the name subjects File storage. Your files that you make will be stored in the same folder as the Python files that you write. w means we are allowing the program to write to this file write to the file If the file already exists any details already in the file will be overwritten (replaced). If there is no such file as myfile stored as subjects.txt Python will create an empty file which we can write to later in the program. 53 Python Instruction Booklet v5.1

55 Writing to our file Now extend the program to include these lines. When you are finished with a file you must close it. Checking to see if your new file exists Check to see if this text file exists and what it contains by looking in the folder where your Python programs are saved. Now open the file using any word processor e.g. Notepad, WordPad, MSWord and you will see the contents of that file. Copy the contents here: Student answer Reading data from a file Exercise 13b Now write the file to import the text file into python. r tells Python you are going to read the file There are two ways this can be done. Read the whole file like this 54 Python Instruction Booklet v5.1

56 Or, read the file line by line like this Try these lines of code and you should see the contents of the files Exercise 13c - Adding to a file (appending) Opening the file: a means we are going to add (append) to the file. Put all the parts the parts together When you run this complete program what is the result on the screen? 55 Python Instruction Booklet v5.1

57 Student answer Files only contain text Txt files can only contain text so any numeric data has to be converted to text by using str, either using the same name or a new name: Exercise 13d Write a program that allows you to enter 4 numbers and stores them in a file called Numbers Exercise 13e Write a program that reads a list of numbers from your file then outputs the average. So if your file contained Your program would output: 38 Then save this result to a new file called Result. 56 Python Instruction Booklet v5.1

58 Student answer Exercise 13f Write a program that opens a text file, reads the contents and then prints out the text file backwards. Student answer 57 Python Instruction Booklet v5.1

59 Creating one program to create, store and access values. Here is a problem to solve; you have created a username and password that will exist while the program is being run but what happens when the program is finished? What happens if you want to run the program again and use the same username and password that the program already knows? This is the program that creates a password and checks that it has been entered correctly. How can we make use of this and the knowledge of files to get the program to ask the user for a username and password (check that the password is correct by asking twice (verification)) and then get the program to store these two values as part of a text file called passwords.txt. (I agree that it is not very secure but there may be a way to improve security later.) This snippet shows how the password can be saved to the text file called passwords.txt. You will note that the name of the connection string is link in this case. The a appends the data to the file. A comma has been added to each value as each value must be separated by a comma so + concatenates the, to the password or username. The next part would be to read the file back into the program so that it can be used to check the user s log on credentials (username and password). This snippet of code shows the two stages involved in doing this. Firstly, reading the file using myfile.read where this time I have used myfile as the connection string. The data from the file is now stored in a string called detail. Secondly, this is then changed to be a list called credential by reading in the string one character at a time and starting a new string value every time there is a comma. The print statement was used for testing and has been remarked out. Credentials In computer security, logging in (or on) is the process by which an individual gains access to a computer system by identifying and authenticating themselves. The user credentials are typically some form of "username" and a matching "password. 58 Python Instruction Booklet v5.1

60 The variable word grows one character at a time until a comma is reached and then the whole word is saved as a string value in the list credential. The final step is to use the file to test a username and password entered by the user. This final snippet borrows from SQL practice and the use of error messages to tell the user what is happening. Firstly set the message (that I have called Access ) to have the default value of Password or username not found. so that if the values typed in do not match any values in the passwords file then this will be the message printed by the program. The code then checks each word in the credential list and if the username is found then the error message is changed to be Access denied. If the next word in the list is the password then the error message is changed to Access granted. Finally the message is printed. All that is left is to add a suitable user interface and test the program. This program wants to know if the user wants to add a new username / password combination to the file. (The unwritten assumption is that n will allow the user to use existing credentials. Perhaps in this case the interface needs work.) Using code from the previous session the program asks for a username and then a password twice. Then it asks of the user wants to write or append the credentials. If the user chooses w (for write) then a new file is created whereas if the user selects a (for append) then the credentials are added to those that already exist. The password.txt is this Done properly the password field should be obscured in some way. 59 Python Instruction Booklet v5.1

61 The credentials have been stored successfully and now can be used as part of a login process. As you can see the credentials that have been supplied are successful. Testing this is really important. You have to show what happens when the data input is incorrect. For example when the credentials are appended by the program do they exist in the file? If you supply incorrect credentials will the program detect what is wrong and give the correct response? This is the program appending a new user Jim Jones. The password.txt is now this 60 Python Instruction Booklet v5.1

62 Session 14 Creating a menu Frequently in coursework tasks you will be asked to create a menu. This will be a list of choices on the screen and the user can then make their selection. Depending on their choice the program then executes different segments of code. Use a procedure called show_menu to show the menu choices It is customary to give the menu a title. Use print statements to put the menu choices on the screen. Ask the user to make a choice and store their answer in a variable. Use an IF statement to choose an option, if 1 is selected it will run the procedure option_1. The third option to quit runs the keyword Exit which terminates the program. This is the code for option 1 as a procedure. show_menu() is the instruction to run the procedure to put the menu on the screen. The anykey line is simply a placeholder; it will pause the program waiting for a key to be pressed. You can use this as the basis for any menu system that you will have to write. You should edit it to suit the circumstances of the problem that you have been given to solve. You should always test the menu when you have written it to make sure that it works as you want it to. 61 Python Instruction Booklet v5.1

63 Session 15 Robust code and error checking While the menu works, it only works if the user types in 1, 2 or 3. If they type other characters such as r, the program will crash, as shown below. Note the name of the error given by Python: ValueError Invalid literal means that the value r is the wrong data type for int(). You need to write code that is robust. Robust code will collect or trap user input that would otherwise break the program and redirect the user to try again. In the example above any non-digit will crash the program and any number other than 1 or 2 will exit the program. Ideally we want the program to trap these input errors and then ask the user to try again. Robust code. Python has the keywords try and except that can be used to trap errors. Place try at the start of the data entry and selection process and except at the end. If there is any error generated by inaccurate data entry than it will be captured by this change to the code. This technique can be used almost anywhere where data is being input by a user. Robust programming, also called bomb-proof programming, is a style of programming that prevents abnormal termination or unexpected actions. Basically, it requires code to handle bad (invalid or absurd) inputs in a reasonable way. The code that follows the except is the code that you want the program to execute if there is an issue with data entry. 62 Python Instruction Booklet v5.1

64 The keyword Try lets the program execute some code as far as the except. If the user has input a value that would cause a ValueError then the except condition is applied. A message is shown on screen and the show_menu() line displays the menu again. What about the other issue of typing in a number that is outside the range of the accepted values. In this case typing 6 has the same effect as typing 3 as the else is a catchall selection. In this example I have added a while statement that will run until a valid input value has been entered by the user. None does have a capital N. This line Choice = None is necessary to give the variable no choice at the start to make the program ask for an input. The code following the while statement will be executed again and again until choice has the value 1 or 2 or Python Instruction Booklet v5.1

65 Create a function to check data entry. There may be an occasion when you have to check specific numeric data that is being entered to make sure that it is in a set range of values. You can use a function for this. For example setting the range for an input value to be say, between 5 and 25 The function has 3 input parameters, the prompt that asks the question, the minimum value and the maximum value. Selection is set to -99 at the start to force the while statement to be executed. The while statement ensures that the selection made by the user is in the range between the minimum value and the maximum value and the try except instruction will capture any non-numeric values. The minimum and maximum values have also been used in the error comment. Here you can see the function in use. A value r has been used without the program crashing, a value (3) below the minimum and another (30) above the maximum have been rejected and the final value 12 has been accepted. Testing is always a crucial part of program development. 64 Python Instruction Booklet v5.1

66 Session 16 Error messages Here are some of the error messages that you might see and how you can approach finding solutions to them. Parse error The process of a compiler moving from instruction to instruction through a piece of code and checking that the rules are unbroken is called parsing. Python calls this invalid syntax and will probably be the most common error that you might find in your code. Here is an example of code containing a parse or syntax error: You could copy the code (with the mistake in it) and get the same response (provided you don t add another error by mistake) or you could take my word for it. This is the usual response from Python of a parse error. This is the classic invalid syntax message. A parse error is created when there is an error (usually of omission) in the code that is found when the compiler is checking the code to see that none of the code rules have been broken. Python highlights where the error has an effect, rather than where the error actually occurred. This is the aspect that creates confusion. Look at the code, the error happens before the highlighted portion. You would think that the error was something to do with the variable current_time_int but it doesn t. One of the classic mistakes in writing Python code is not balancing brackets, Look at the third line it contains an input statement that has an opening bracket for the prompt. Is there a bracket at the end of the line? There should be. Add the missing bracket and the code works. 65 Python Instruction Booklet v5.1

67 Type error A type error can happen when you try to make use of two different data types in an expression or when the code is expecting one data type and you provide it with a different data type. Here is an example where the user has forgotten that an input statement returns a string value and then makes use of the string value in a calculation. This produces this error message: Height is a string variable as it contains the result of an input statement. The code then wants to subtract 50 from the value and python will not allow a string to be added to an integer. Clearly casting is the solution to this problem as shown below. Name error Name errors almost always mean that you have used a variable before it has a value. Often name errors are simply caused by typos in your code. They can be hard to spot if you don t have a good eye for catching spelling mistakes (copying and pasting variable names can be a solution to this as it will ensure that variables are spelt correctly). Mixing the case can also cause issues with variable names. 66 Python Instruction Booklet v5.1

68 This is the error: Look carefully at the code, every time you introduce a new variable it must be on the left hand side of an equation. The first time new_height was used it was to the right of the = sign. Python assumes that new_height already has a value but as it does not yet exist, it returns a NameError. Here is the solution. New_height is used on the left of an equation and so has a value Value error This is an error where data types do not match and conversion has not been effective. Here is a very simple example which has this result: The program wants an integer and the user has entered a real (or float if you will). This creates a value error. The solution is to use Try Except to catch such user-centric errors like this Python Instruction Booklet v5.1

69 which has this effect: In this way the program will continue without crashing. Import error This is usually a spelling mistake. Here is a program that prints out some random numbers using the random library. This is the error message: The error message states that there is No module named Random and Python is correct, all libraries are all lower case and there is a library called random. This is the corrected code and this is the result: 68 Python Instruction Booklet v5.1

70 Indentation error As you are aware, each programming language has its own peculiarities and Python is no exception. It is indentation that Python get all hot and bothered about. Here is an example: The actual code is perfect, it is the indentation that is the problem. This is the error: You can see that Python has indicated where the unexpected indent has taken place. This is the corrected code with the extra indentation removed 69 Python Instruction Booklet v5.1

71 Index error An index error occurs when using lists and arrays. As you know the index is the pointer that tells Python which value in the list is selected. Here is an example that contains an error. This is the error message: This has happened because when i has the value 4, i+1 has the value 5 and there is no 5 th item in the list; the pointer i+1 has nothing to point to. This is the corrected version and this is the result: 70 Python Instruction Booklet v5.1

72 Session 17 Turtle Graphics Turtle graphics were first used in Logo in 1969 (the book Mindstorms is still worth a read if you are interested in coding, although it is a shame that Seymour Papert died recently). All of the turtle drawing functions are invoked by importing the turtle library; import turtle and are prefaces by the library name; turtle. To draw a line 100 pixels long try: Filenames Exercise 17a Drawing a square combines moving forward and turning right a number of times (below left). Do not save a file with the name turtle ; it will seriously affect the performance of your code. A short name for a library Exercise 17b Drawing a number of squares combines drawing a square and turning right a number of times (below right). Instead of import turtle you can write import turtle as t then turtle.forward() becomes t.forward() Note that you can speed up the turtle using turtle.speed( fastest ) 71 Python Instruction Booklet v5.1

73 Write the code that makes these two patterns. (All you have to do is to change some of the numbers and the patterns will change.) We can use the idea of functions in Python to make spiral patterns; try this: Simply by changing the numbers see if you can make these patterns. What other patterns can you make? 72 Python Instruction Booklet v5.1

74 Exercise 17c; Making a window. Here is the code for making a window in python. It is a function which makes use of the TK elements in the turtle library. The first set of statements is pretty much mandatory; although you can change the size of the window. This is the only part to change, everything else must stay the same. All of this prints the text on the screen; apart from the text that you want on the window, you could edit the line height or the text style if you wish. In the code help_t is the name given to the window as far as the Python code is concerned. This is the help_t window; it can be called anything you wish. So help_t.penup() tells the help_t window only to have the pen not draw. Any other window will still draw as normal. you can comment out this line. The line help_t.hideturtle() tells the help_t window only to hide the turtle so that it cannot be seen. If you need to see how it is drawing This example makes use of the turtle s ability to draw text to place text on the screen using help_t.write(). There are alternatives to this that I will explain later. The program shown below makes use of the TKinter library to put a window on the screen, ask for values and send the values to the shell. The actual window it makes is also shown (below right). In this example, Master is the name of the window. You would need to use the get() function to extract the data from the window. For example x = e1.get() would enable you to make use of the value (as a string) in the first data entry box in your own program should it be required. 73 Python Instruction Booklet v5.1

75 Exercise 17d; Drawing a grid in a window. In this example there is a requirement to draw an 8 x 8 grid in a new window. In this example, scr is the name of the window. turtle.tracer(0,0) makes the screen just show the result of the drawing and not the drawing process which speeds up the image in the window. This section of code draws a square. The local variables i and j are used to move through the two dimensions of the grid. The variable I is used for the y co-ordinate and the variable j is used for the x co-ordinate. The variable CELL_SIZE is a global variable set outside of this function and stores the size of the side of one square in the grid. In this example the grid size has been set to 40 so that the 8 x 8 grid fills the screen. Exercise 17e; using global variables. If you wish to arrange your code as a series of functions where each function is a process given by an examiner to act on some data structure then you will be constructing some seriously well-structured code; which is a good thing. However, you will have noticed an issue with the function not passing the results to the data structure as your code moves from function to function. The solution is to make the variable that will be used in each of the functions a global variable. When you use a variable in a function it only exists within that function, as far as python is concerned. In this example the variable words has been made global so that it has some existence outside of the function shuffle. Shuffle is a very simple random shuffling algorithm that you may find useful in other tasks as well. 74 Python Instruction Booklet v5.1

76 Session 18 - Classes, TkInter and a GUI I shall explain classes with an example of a pet. Here is the code that creates the class Pet. Line 1 This is the basic incant for creating a class. The first word, class, indicates that we are creating a class. The second word, Pet, indicates the name of the class. The word in parentheses, object, is the class that Pet is inheriting from. We ll get more into inheritance below, so for now all you need to know is that object is a special variable in Python that you should include in the parentheses when you are creating a new class. Lines 3-5 When we create a new pet, we need to initialize (that is, specify) it with a name and a species. The init method (method is just a special term for functions that are part of a class) is a special Python function that is called when an instance of a class is first created. For example, when running the code polly = Pet("Polly", "Parrot"), the init method is called with values polly, "Polly", and "Parrot" for the variables self, name, and species, respectively. The self variable is the instance of the class. Remember that instances have the structure of the class but that the values within an instance may vary from instance to instance. So, we want to specify that our instance (self) has different values in it than some other possible instance. That is why we say self.name = name instead of Pet.name = name. You might have noticed that the init method (as well as other methods in the Pet class) have this self variable, but that when you call the method (e.g. polly = Pet("Polly", "Parrot")), you only have to pass in two values. Why don t we have to pass in the self parameter? This phenomenon is a special behaviour of Python: when you call a method of an instance, Python automatically figures out what self should be (from the instance) and passes it to the function. In the case of init, Python first creates self and then passes it in. We ll talk a little bit more about this below when we discuss the getname and getspecies methods. 75 Python Instruction Booklet v5.1

77 Lines 7-11 We can also define methods to get the contents of the instance. The getname method takes an instance of a Pet as a parameter and looks up the pet s name. Similarly, the getspecies method takes an instance of a Pet as a parameter and looks up the pet s species. Again, we require the self parameter so that the function knows which instance of Pet to operate on: it needs to be able to find out the content. As mentioned before, we don t actually have to pass in the self parameter because Python automatically figures it out. To make it a little bit clearer as to what is going on, we can look at two different ways of calling getname. The first way is the standard way of doing it: polly.getname(). The second, while not conventional, is equivalent: Pet.getName(polly). Note how in the second example we had to pass in the instance because we did not call the method via the instance. Python can t figure out what the instance is if it doesn t have any information about it. A Graphic User Interface using TkInter TkInter is the library that enables a Graphic User Interface (GUI). There are some good notes here. This class is application so self has the value application The function say_hi(self) prints to the shell. This line creates the button. You can see the features of the button, text = QUIT and the foreground colour is to be red. self.quit closes the window. The command for the button runs the function written earlier. When you run it, it does this It creates a window with two buttons, Quit (which quits the window) and Hello which prints Hi there, everyone! in the shell. 76 Python Instruction Booklet v5.1

78 Building a GUI Here is the basic code to create a window on the screen. Try it, it simply draws an empty window on the screen; the close box works perfectly. Here you can see the additional command for a button. This is the function executed by the button. The pack instruction combines all the parts of the window into a Clicking the Hello button will print Hello Python Hello World in the shell. Next the Label command can be used to add text to the window. Note that each of the objects is packed separately. 77 Python Instruction Booklet v5.1

79 Combining these ideas leads to this 78 Python Instruction Booklet v5.1

80 Session 19 Sorting There are four main sorting solutions that can be coded in Python; Bubble sort and Insertion sort. Bubble sort The BBC website says that the bubble sort is a simple algorithm used for taking a list of jumbled up numbers (or words) and putting them into the correct order. The algorithm runs as follows: 1. Look at the first number in the list. 2. Compare the current number with the next number. 3. Is the next number smaller than the current number? If so, swap the two numbers around. If not, do not swap. 4. Move to the next number along in the list and make this the current number. 5. Repeat from step 2 until the last number in the list has been reached. 6. If any numbers were swapped, repeat again from step If the end of the list is reached without any swaps being made, then the list is ordered and the algorithm can stop. This is an unsorted list of names. This is the length of the list less one. There is no need to compare the last item as there is nothing to follow it. Each iteration will bring the largest item to the last position, so this whole process must be repeated the length of the list less one times. This line compares item i with the next item and if item i is larger than the next one, they are swapped over. These three lines swap the two items. After each iteration, the largest value will have been moved to the right hand end of the array. 79 Python Instruction Booklet v5.1

81 It is possible to use a flag instead of counting, like this Each cycle through the list the flag swapped is set to be True and if a swap takes place then the flag is set to False as long as the flag stays False the process will continue. This uses fewer swaps and is quicker with larger lists. Insertion sort The insertion sort looks at the list and considers that all items below the pointer are in order and inserts the next item into the sorted part of the list in the correct place. The example below shows that items 17 to 93 are sorted and 31 is to be considered next. Each item is moved to the right until 31 is in the right place. 80 Python Instruction Booklet v5.1

82 Here is the code to make this happen. This algorithm only cycles though the list once. currentvalue is the item being moved. This moves a value one place to the right. This inserts the currentvalue in the right place. Here is the output of the program. At the start only 26 and 54 are sorted, next 26, 54 and 93 are in the correct order, then 17 is inserted in the right place to make 17, 26, 54 and 93. Next, 77 is added before the 93, then the 31 before the 54 to make 17, 26, 31, 54, 77 and Python Instruction Booklet v5.1

83 Appendix 1 Flowchart symbols and examples Flow chart symbols A 3 choice menu Start A terminator, start or stop Display menu choices A process Choice - 1 yes Subroutine for choice 1 no A decision Choice = 2 yes Subroutine for choice 2 no no Choice = 3 A subroutine Stop yes Subroutine, saving a file with a txt extension Subroutine Reversing the characters in a word Start Start Ask for filename Word = input the word to reverse Filename included.txt extension? yes no Add.txt filename extension NewWord = (set up destination variable) Open file with filename for writing NewWord = NewWord + last character of Word Save file using filename Remove the last character of Word Close file Word =? no yes Stop Stop 82 Python Instruction Booklet v5.1

84 Appendix 2 - Cheat sheets 83 Python Instruction Booklet v5.1

85 84 Python Instruction Booklet v5.1

86 85 Python Instruction Booklet v5.1

Python Instruction Booklet v5.1. Learning to use Python at Stanground Academy. Name

Python Instruction Booklet v5.1. Learning to use Python at Stanground Academy. Name Python Instruction Booklet v5.1 Learning to use Python at Stanground Academy Name Contents Contents... 1 Session 1 Introduction to Python... 2 Using the IDLE in Interactive Mode... 3 Hello World... 4 Session

More information

Python Programming Challenges

Python Programming Challenges Python Programming Challenges Name Complete the tasks enclosed and complete a self review for each task. Eg: Yes or no errors? Yes syntax errors (write in the error) or No your errors/solve the problem?

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

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

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

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

More information

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

More information

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

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

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

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

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

Chapter 2.6: Testing and running a solution

Chapter 2.6: Testing and running a solution Chapter 2.6: Testing and running a solution 2.6 (a) Types of Programming Errors When programs are being written it is not surprising that mistakes are made, after all they are very complicated. There are

More information

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5 Computing Science Software Design & Development (Part 1 Computer Programming) National 5 VARIABLES & DATA TYPES Variables provide temporary storage for information that will be needed while a program is

More information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials Fundamentals We build up instructions from three types of materials Constants Expressions Fundamentals Constants are just that, they are values that don t change as our macros are executing Fundamentals

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

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

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1 Pupil Name Year Teacher Target Level Spelling Test No 1 Spelling Test No 2 Spelling Test No 3 1) 2) 3) 4) 5) 1) 2) 3) 4) 5) 1) 2) 3) 4) 5) Spelling Test No 4 Spelling Test No 5 Spelling Test No 6 1) 2)

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Civil Engineering Computation

Civil Engineering Computation Civil Engineering Computation First Steps in VBA Homework Evaluation 2 1 Homework Evaluation 3 Based on this rubric, you may resubmit Homework 1 and Homework 2 (along with today s homework) by next Monday

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Python Programming for GCSE Computing Python 3 Programming For GCSE Computing

Python Programming for GCSE Computing Python 3 Programming For GCSE Computing Python 3 Programming For GCSE Computing - 1 - Contents Introduction 3 1. Output to the screen 5 2. Storing Data in Variables 6 3. Inputting Data 8 4. Calculations 9 5. Data Types 10 6. Selection with IF

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

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

National 5 Computing Science Software Design & Development

National 5 Computing Science Software Design & Development National 5 Computing Science Software Design & Development 1 Stages of Development 2 Analysis 3 Design 4 Implementation 5 Testing 6 Documentation 7 Evaluation 8 Maintenance 9 Data Types & Structures 10

More information

Activity: page 1/10 Introduction to Excel. Getting Started

Activity: page 1/10 Introduction to Excel. Getting Started Activity: page 1/10 Introduction to Excel Excel is a computer spreadsheet program. Spreadsheets are convenient to use for entering and analyzing data. Although Excel has many capabilities for analyzing

More information

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you

More information

EXCEL BASICS: MICROSOFT OFFICE 2007

EXCEL BASICS: MICROSOFT OFFICE 2007 EXCEL BASICS: MICROSOFT OFFICE 2007 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

T H E I N T E R A C T I V E S H E L L

T H E I N T E R A C T I V E S H E L L 3 T H E I N T E R A C T I V E S H E L L The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. Ada Lovelace, October 1842 Before

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

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

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

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

Introduction to Programming with JES

Introduction to Programming with JES Introduction to Programming with JES Titus Winters & Josef Spjut October 6, 2005 1 Introduction First off, welcome to UCR, and congratulations on becoming a Computer Engineering major. Excellent choice.

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

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014 Lesson 6A Loops By John B. Owen All rights reserved 2011, revised 2014 Topic List Objectives Loop structure 4 parts Three loop styles Example of a while loop Example of a do while loop Comparison while

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

EXCEL BASICS: MICROSOFT OFFICE 2010

EXCEL BASICS: MICROSOFT OFFICE 2010 EXCEL BASICS: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites What You Will Learn USING MICROSOFT EXCEL PAGE 03 Opening Microsoft Excel Microsoft Excel Features Keyboard Review Pointer Shapes

More information

Animations involving numbers

Animations involving numbers 136 Chapter 8 Animations involving numbers 8.1 Model and view The examples of Chapter 6 all compute the next picture in the animation from the previous picture. This turns out to be a rather restrictive

More information

An Introduction to Python for KS4!

An Introduction to Python for KS4! An Introduction to Python for KS4 Python is a modern, typed language - quick to create programs and easily scalable from small, simple programs to those as complex as GoogleApps. IDLE is the editor that

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

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

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

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

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

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES Unit 6 - Software Design and Development LESSON 3 KEY FEATURES Last session 1. Language generations. 2. Reasons why languages are used by organisations. 1. Proprietary or open source. 2. Features and tools.

More information

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class:

BB4W. KS3 Programming Workbook INTRODUCTION TO. BBC BASIC for Windows. Name: Class: KS3 Programming Workbook INTRODUCTION TO BB4W BBC BASIC for Windows Name: Class: Resource created by Lin White www.coinlea.co.uk This resource may be photocopied for educational purposes Introducing BBC

More information

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018 Python Input, output and variables Lecture 23 COMPSCI111/111G SS 2018 1 Today s lecture What is Python? Displaying text on screen using print() Variables Numbers and basic arithmetic Getting input from

More information

Variables and Constants

Variables and Constants 87 Chapter 5 Variables and Constants 5.1 Storing Information in the Computer 5.2 Declaring Variables 5.3 Inputting Character Strings 5.4 Mistakes in Programs 5.5 Inputting Numbers 5.6 Inputting Real Numbers

More information

[ the academy_of_code] Senior Beginners

[ the academy_of_code] Senior Beginners [ the academy_of_code] Senior Beginners 1 Drawing Circles First step open Processing Open Processing by clicking on the Processing icon (that s the white P on the blue background your teacher will tell

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

Python Input, output and variables

Python Input, output and variables Today s lecture Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016! What is Python?! Displaying text on screen using print()! Variables! Numbers and basic arithmetic! Getting input from

More information

Excel Basics: Working with Spreadsheets

Excel Basics: Working with Spreadsheets Excel Basics: Working with Spreadsheets E 890 / 1 Unravel the Mysteries of Cells, Rows, Ranges, Formulas and More Spreadsheets are all about numbers: they help us keep track of figures and make calculations.

More information

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable STUDENT TEACHER CLASS WORKING AT GRADE TERM TARGET YEAR TARGET Pseudocode Python Description BEGIN END Identifies the start of a program Identifies the end of a program READ X, Y, Z input() Identifies

More information

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:

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

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide VBA Visual Basic for Applications Learner Guide 1 Table of Contents SECTION 1 WORKING WITH MACROS...5 WORKING WITH MACROS...6 About Excel macros...6 Opening Excel (using Windows 7 or 10)...6 Recognizing

More information

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016 Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016 Today s lecture u What is Python? u Displaying text on screen using print() u Variables u Numbers and basic arithmetic u Getting input

More information

Introduction to the C++ Programming Language

Introduction to the C++ Programming Language LESSON SET 2 Introduction to the C++ Programming Language OBJECTIVES FOR STUDENT Lesson 2A: 1. To learn the basic components of a C++ program 2. To gain a basic knowledge of how memory is used in programming

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

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation.

TABLE OF CONTENTS 2 CHAPTER 1 3 CHAPTER 2 4 CHAPTER 3 5 CHAPTER 4. Algorithm Design & Problem Solving. Data Representation. 2 CHAPTER 1 Algorithm Design & Problem Solving 3 CHAPTER 2 Data Representation 4 CHAPTER 3 Programming 5 CHAPTER 4 Software Development TABLE OF CONTENTS 1. ALGORITHM DESIGN & PROBLEM-SOLVING Algorithm:

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #44 Multidimensional Array and pointers In this video, we will look at the relation between Multi-dimensional

More information

SCRATCH MODULE 3: NUMBER CONVERSIONS

SCRATCH MODULE 3: NUMBER CONVERSIONS SCRATCH MODULE 3: NUMBER CONVERSIONS INTRODUCTION The purpose of this module is to experiment with user interactions, error checking input, and number conversion algorithms in Scratch. We will be exploring

More information

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES

Unit 6 - Software Design and Development LESSON 3 KEY FEATURES Unit 6 - Software Design and Development LESSON 3 KEY FEATURES Last session 1. Language generations. 2. Reasons why languages are used by organisations. 1. Proprietary or open source. 2. Features and tools.

More information

Boolean Expressions. Is Equal and Is Not Equal

Boolean Expressions. Is Equal and Is Not Equal 3 MAKING CHOICES Now that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer

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

APPM 2460 Matlab Basics

APPM 2460 Matlab Basics APPM 2460 Matlab Basics 1 Introduction In this lab we ll get acquainted with the basics of Matlab. This will be review if you ve done any sort of programming before; the goal here is to get everyone on

More information

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop

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

PYTHON YEAR 10 RESOURCE. Practical 01: Printing to the Shell KS3. Integrated Development Environment

PYTHON YEAR 10 RESOURCE. Practical 01: Printing to the Shell KS3. Integrated Development Environment Practical 01: Printing to the Shell To program in Python you need the latest version of Python, which is freely available at www.python.org. Your school will have this installed on the computers for you,

More information

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. Plan for the rest of the semester: Programming We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems. We saw earlier that computers

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

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

Boolean Expressions. Is Equal and Is Not Equal

Boolean Expressions. Is Equal and Is Not Equal 3 MAKING CHOICES ow that we ve covered how to create constants and variables, you re ready to learn how to tell your computer to make choices. This chapter is about controlling the flow of a computer program

More information

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

Scheme of work Cambridge International AS & A Level Computing (9691)

Scheme of work Cambridge International AS & A Level Computing (9691) Scheme of work Cambridge International AS & A Level Computing (9691) Unit 2: Practical programming techniques Recommended prior knowledge Students beginning this course are not expected to have studied

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

(Refer Slide Time: 01:12)

(Refer Slide Time: 01:12) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

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

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

The first thing we ll need is some numbers. I m going to use the set of times and drug concentration levels in a patient s bloodstream given below.

The first thing we ll need is some numbers. I m going to use the set of times and drug concentration levels in a patient s bloodstream given below. Graphing in Excel featuring Excel 2007 1 A spreadsheet can be a powerful tool for analyzing and graphing data, but it works completely differently from the graphing calculator that you re used to. If you

More information

Divisibility Rules and Their Explanations

Divisibility Rules and Their Explanations Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although

More information

UNIT 5. String Functions and Random Numbers

UNIT 5. String Functions and Random Numbers UNIT 5 String Functions and Random Numbers DAY 1 String data type String storage in data String indexing I can.. Explain the purpose of the string variable type and how it is stored in memory. Explain

More information

Programming for Engineers in Python. Autumn

Programming for Engineers in Python. Autumn Programming for Engineers in Python Autumn 2011-12 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016 Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada Under Supervision of: Dr. Richard Kelley Chief Engineer, NAASIC March 6th, 2016 Science Technology Engineering

More information

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1 Chapter 2 Input, Processing, and Output Fall 2016, CSUS Designing a Program Chapter 2.1 1 Algorithms They are the logic on how to do something how to compute the value of Pi how to delete a file how to

More information

4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list?

4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list? 1 Practice problems Here is a collection of some relatively straightforward problems that let you practice simple nuts and bolts of programming. Each problem is intended to be a separate program. 1. Write

More information

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute Module # 02 Lecture - 03 Characters and Strings So, let us turn our attention to a data type we have

More information

Loop structures and booleans

Loop structures and booleans Loop structures and booleans Michael Mandel Lecture 7 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture07final.ipynb

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

9. MATHEMATICIANS ARE FOND OF COLLECTIONS

9. MATHEMATICIANS ARE FOND OF COLLECTIONS get the complete book: http://wwwonemathematicalcatorg/getfulltextfullbookhtm 9 MATHEMATICIANS ARE FOND OF COLLECTIONS collections Collections are extremely important in life: when we group together objects

More information

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F

Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F PROGRAM 4A Full Names (25 points) Honors Computer Science Python Mr. Clausen Programs 4A, 4B, 4C, 4D, 4E, 4F This program should ask the user for their full name: first name, a space, middle name, a space,

More information

Chapter 2.4: Common facilities of procedural languages

Chapter 2.4: Common facilities of procedural languages Chapter 2.4: Common facilities of procedural languages 2.4 (a) Understand and use assignment statements. Assignment An assignment is an instruction in a program that places a value into a specified variable.

More information

Post Experiment Interview Questions

Post Experiment Interview Questions Post Experiment Interview Questions Questions about the Maximum Problem 1. What is this problem statement asking? 2. What is meant by positive integers? 3. What does it mean by the user entering valid

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python + Condition Controlled Loops Introduction to Programming - Python + Repetition Structures n Programmers commonly find that they need to write code that performs the same task over and over again + Example:

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