A brief introduction to python at frome college

Page 1

For GCSE Computing

Based on Python Version 3.2


2|Page

A Brief Introduction to Python at Frome College Contents

/mnt/tmp/rs/131211224711-50e292a1aa798f0e11c905e76dd1754c/original.file


3|Page

Introduction to Python You can write Python code in any text editor (such as notepad or notepad++) but Python comes with a free editor called IDLE. This will help you with things like indentation and debugging (finding errors in your code). In school, you can find IDLE by going to Start > All Programs > ICT > Python > IDLE

(NOTE: some screen shots are taken from Ubuntu Linux and may look a little different under Windows) You can start typing code straight into IDLE here. Try typing in the following at the prompt (>>>): 2+2 5*5 21/3 1-2 We can also create simple programs here, try the following: >>>print(“Hello, world!”)

The print command is for basic text output in Python.

Saving programs for later Creating programs at the >>> prompt is great for really simple short programs but for anything we want to save and use later we must save them into their own file. Go to “File > New Window” and a new blank IDLE window will open. Retype your print(“Hello, world!”) program then go to “File > Save” navigate to your Computing Python folder and save it as “HelloWorld.py”. Add the following lines to your program:


4|Page name = input(“What is your name? “) print(“Hello “ + name) Save it again (“File > Save” or use the keyboard shortcut Ctrl + S). Now press the F5 key on your keyboard to run it and make sure it works correctly

Throughout your classwork it’s really important that you get into the habit of saving programs with sensible names that describe what they do so you can find them later when you need to (think of it as creating your own textbook of programs to help you create more interesting programs later rather than a task that you just need to do and forget about). Datatypes in Python The reason we need to think about what types of data we’re using is because all computers work using only binary numbers (e.g. 10100 is 20) and there can be no exception to this because of the way they are designed and built. This isn’t much good for us when writing programs (think very difficult and time-consuming) so they need to translate data such as text, Boolean (true/false) data for us. We do need to help them do this by making it clear what type of data we want to use. Here are the main datatypes you need to know about. Datatype

Description

Examples

String

This is any kind of text input. When you declare a string, you have to use single or double quote marks.

Bob C Hi there 01373 828 887 (NOTE: leading zero and spaces not suitable for a numeric types)

Integer

Whole numbers without decimal places. All numeric types are declared without any quote marks.

1 2 8484

Float

Decimal numbers (not quotes remember)

0.1 3.14

Boolean

Use to indicate when something is true or false (can only be one or the other) and never have quote marks round them.

Datatype Challenge Write out the following program. Save and test it to make sure it works using the F5 button. Once it’s working, extend it to ask for the length of a cylinder and print out the volume of

True False


5|Page the cylinder. Print screen it (Alt + Print Screen keyboard shortcut) and put this into a Word document with title “Data Types Annotated” then annotate it with textboxes and arrows to show what each data type is.

Integer Arithmetic Create a new python program in IDLE and enter the following code: firstNumber = int(input(“Please enter a number (1-100): “)) secondNumber = int(input(“Please enter another number (1-100: “)) result = firstNumber + secondNumber print(“firstNumber + secondNumber = “ + str(result)) Save it as addition.py in your Python folder then test it using the F5 key Basic Arithmetic Challenge Create 3 more programs which repeat the last program but instead they should: •

Subtract 2 numbers (call it subtraction.py)

Multiply 2 numbers – give it a suitable name

Divide 2 numbers – give it a suitable name also

Now create a word document and give it a title “Working with Numbers”. Write a short paragraph explaining what the int() and str() functions do in the programs you have written (think back to datatypes). If you’re not sure think book, brain, buddy, boss.

Extension: write another program to work out the area of a triangle which the user enters the width and height for (use the Internet to find out how to find the area of a triangle if you don’t remember)

Print off all your work now and put it in your programming task wallet

A short introduction to comments Comments are notes that programmers make while their writing code helps them and other programmers know what they have done when they have to come back to or look at a bit of code for the first time. In Python, we use the # symbol to indicate a comment.


6|Page

The computer will ignore these and not try to use them as code. You will need to add comments to your code in the next section so ask someone to help you if you don’t understand how to use them.

Commenting on Datatypes This program uses only integer and string datatypes as these are probably the most commonly used. You can also see examples of : • input(“Message”) - to get string input from users • int(input(“Message”)) – to get integer input from users • IF statements to check what the user has input. • Casting str(myAge) to convert an integer to a string (e.g. to print it along with a message)

This is the error message from the

line


7|Page


8|Page String handling Working with text (string) data is something you will have to do a lot of! For example, when you ask the user a question you will have to know what to do with the answers (input) they type. You have already done a little of this in the arithmetic challenge but here we’ll look at what it means. In Python, whenever you want to indicate that a variable is a string (text) datatype, you must use the single or double quote marks to set the value.

String basics A string is just a piece of text or a collection of characters that have been joined together (e.g. “abc”, “b23”, “&hello”) Declaring an empty string: myString = “” Giving a value to the string myString = “Hello” Changing the value of a string: myString = “world” Adding to the string (left hand side): myString = “Hello, “ + myString Adding to the string (right hand side): myString += “!!!” Displaying the string: print(myString) This would print: Hello, world!!!

String arithmetic Try the following program: firstName = input("Please enter your first name: ") surname = input("Please enter your surname: ") print("Hello " + firstName + " " + surname) String Arithmetic challenge Obviously it doesn’t miraculously do some kind of weird addition with the text, what does it do? Add a comment to your program to say what this + operator does when applied to a bit of text. Add the following line to your program: print(firstName * 5) Explain what you think this one does? Add a comment to your program to explain what this * operator does when applied to a


9|Page bit of text. print(firstName / 5) What should this do??? This is a trick question, see what happens when you try it (pay particular attention to the very last line which is Python ’s way of telling you something is wrong). Add a comment to your program to explain what you think Python is trying to tell you about the / operator. Print off all your work now and put it in your programming task wallet Formatting strings What happens if you want to print a string with quotes inside it (remember quotes are used to show the start and end of a string. Try entering the following line in interactive mode: print(“I didn’t do quote marks until my teacher said “But you must!”.”) To get round this problem, we have a special escape character \ which tells Python not to treat whatever follows it in the usual way, but instead to print it as a piece of text. print(“I didn’t do quote marks until my teacher said \“But you must!\”.”) Other special formatting escape sequences that you might want to use are the newline sequence \n and the tab sequence \t. Try the following print statement (don’t worry about the exact number of \n or \t): print("I \n\tdidn’t \n\t\tdo \n\t\t\tquote \n\t\t\t\tmarks until my teacher said \n\"But you must!\".") Here’s the most commonly used escape sequences for reference Escape Sequence Description \\

Print a single backslash

\”

Print a double quote mark

\n

Print a newline

\t

Print a tab character (indents the text

What about really long strings? You can split them across multiple lines using the ‘+’ operator (more on this later) like this: print("This is a " + "really long string" + " and it makes good sense" + " to split it across multiple lines") Whoever is using your program won’t even know this is happening but it can make it easier as a programmer if you have a really long bit of text and you don’t want to have to scroll way over to the left of your screen. Formatting Strings Challenge Here is some output from a print statement (you can only use ONE print statement for this challenge). Your job is to recreate it using Python with the formatting that you see by using the


10 | P a g e appropriate techniques discussed above. You should also customise it to tell me something about you!

Hi there, my name is Mr MacNeil and I love teaching computing. I think it’s a challenging, useful and creative subject.

My favourite quote is from someone who used to work for IBM who in 1973 said that there was:

“a world market for maybe five computers.”

I don’t think he saw the PC and mobile phone revolution coming!!! That’s all from me, I hope you are enjoying playing with string!

Don’t forget to print! String Methods You’ve already used methods before. The print() statement is an example of a method. Think of these as built in commands that do something really useful so Python does it for you, by providing a method, so you don’t have to worry about doing it yourself (especially good when it would be complicated to do anyway!) message = “there are 10 types of people in the world: “ \ + “those who understand binary, and those who don't.” print(message) print(message.upper()) In this program, you have called the upper() string method on the string variable message. As you will have seen, this coverts the whole sentence to upper case. String Methods Challenge

Add lines to your program to use the string methods: •

title()

capitalize()

replace(“e”, “E”)

Add the following line next: message = message.replace(“e”, “E”)


11 | P a g e Now print out your message with this method •

swapcase()

Finally, print your message one last time to see if it’s changed at all. Put a comment after the line you think changed the content of the original string. Explain why you think this use of the method was special

Don’t forget to print your work!

Selection with IF-ELSE Statements – Testing what’s happened IF statements are one of the most useful programming features you will come across. They allow you to control what happens in response to different input or values depending on what’s going on in your code. They follow this structure IF <condition> then

IF weather is sunny then

For example:

Do something

Wear a t-shirt

ELSE

ELSE Do something different

Don’t forget your jacket

In Python, this might look like this:

This can be represented in the following flow-chart: Input: What is the weather like outside?

IF statements - Simple Guessing Game Try copying out the following simple game. This introduces the use of an IF Statement to carry out tests in your code (e.g. did someone type the letter A?). Remember, when your setting values of variables you use a single equals sign. When you’re creating a test to see if 2 things are the same you use double equals sign.

Assign a value: x = 8

Compare values: 7 == 5

Remember to use the “F5” button to run and test your program!


12 | P a g e

o Simple Quiz Challenge Extend this program by adding your own questions. You will need to remember to add 1 to the score variable for each correct answer. Once you have completed this: •

Get some else to test your program and give you feedback on it (especially if something doesn’t work as expected)

Run your program by pressing F5 and answer all the questions (try to get some right and some wrong to test the IF and ELSE parts) o

Print your program out

o

Print out the results of running your program

o

Fill in the relevant sections of a program evaluation cover sheet

Put everything together in your programming folder

More IF (IF-ELIF-ELSE) Statements – Testing different types of data Copy this program out and change the values of name, age and height to your own information. Pay extra attention to where the program indents and dedents (opposite of indent). Avoid the temptation to use the space key to indent, always use the TAB key!


13 | P a g e


14 | P a g e Notice the use of different comparison operators in your IF statements. Here’s most of what you’ll ever need. Operator s

Description

Examples

Tests to see if 2 values or variables are the same

“fish” == “fish”

-> True

“fish” == “kangaroo” -> False

==

5 == 6 -> False 5 == 5 -> True Greater than

>

Less than <

Greater than or equal to >=

Less than or equal to <=

Not equal to !=

5>6

-> False

5>5

-> False

5>4

-> True

5<6

-> True

5<5

-> False

5<4

-> False

5 >= 6 -> False 5 >= 5

-> True

5 >= 4

-> True

5 <= 6 -> True 5 <= 5

-> False

5 <= 4

-> False

5 != 5

-> False

5 != 4

-> True

“fish” != “fish”

-> False

“fish” != “kangaroo”

-> True

More IFs Challenge Test your program to make sure it work (F5). If it doesn’t, the most likely reason is that you have misspelt something. Go back and check for this (ask for help if you can’t see it). 1. Add your name at the top with a # character in front of it (this is used to declare comments which are not run as part of the program). 2. Print your code then run the program and print the output. Now adapt your program to meet the following scenario: A program that checks that someone called Lee is old enough (greater than 15 years) and tall enough (4.10) but not too tall (less than 6.10) to on a fair ground ride 1. Run your program to check it makes sense (are the input and outputs meaningful?)


15 | P a g e 2. Print your revised code 3. Run the program through and print the output to show it works. Complete a program evaluation record for you program and hand in all pieces of work Extension Look back at your last bits of work on IF statements. Can you change the program above to ask someone to enter their personal details and use these details in the IF statements instead of writing them into the program as done in the example. Here’s some hints: variable = input(“What?”) user

# Gets a string response from the

variable = int( input(“What?”) ) number (no decimal places)

# Converts a string to a

variable = float( input(“What?”) ) with decimal places

# Coverts it to a number

Print any extension work also!

Loops A loop is a program structure that you use when you want to repeat a set of actions. Imagine you want to find ace of hearts in a random deck of cards. If they aren’t in any order, you will have to go through each card and check to see if it’s the right one. This is what loops do, but they can be used for lots of different things. In any programming language there is more than one way to set up a loop. Python has 2 main types of loop, FOR and WHILE. We usually use for loops when we want to deal with a list of values or do something a number of times. While loops are similar because they repeat a section of code but are more commonly used when we want to do something until a certain condition is met. To put this in context, imagine these 2 scenarios 1. You want to count the number of people in a list called Allan. You will need to go through the entire list and keep a note of the number of times you see the name Allan. This is most obviously done using a FOR loop. 2. You need your user to enter one of a number of options and can’t be sure that they will stick to the ones allowed. A WHILE loop could keep prompting them until a valid option is entered This isn’t a hard and fast rule but it’s a good starting point!

While Loop – Doing something until you want to stop Guessing Game Try writing out the following guessing game:


16 | P a g e

If True If false Go past the loop block to here Go inside the loop block to here Guess not equal to number Go back to start of while

This game does the following: • Picks a random number between 1 and 20 • Asks the player to guess the number • Checks to see if the guess is different from the number


17 | P a g e • Tells the user if their guess was too high or too low • Asks them to guess again • Prints well done when they guess correctly.

Guessing Game Challenge Tasks: •

Add a variable to keep track of how many guesses the player has o

Think about what your going to call this variable

o

You will need to increment this by 1 each time the player has a go (e.g. myVar += 1), where’s the best place to do this?

o

Tell the player how many goes they have had each time

Extension Quit the game when the player has had 5 attempts: •

You can use the “break” python keyword to exit a while loop

OR you can change the start of the while loop to make sure that the number of guesses is less than or equal to 5

Remember to print any work to show what you have done. Check if you need to fill out a program evaluation record.

For loops – How many times? Searching in lists We will frequently have to work with lists of data when programming. To make it possible to search through lists we can use a loop. This is statement which repeats a particular action until you tell it to stop.


18 | P a g e The program above uses a type of list called an Array. Arrays store a single data type only. We can imagine the above array as a group of similar (string) cells as follows: Index Contents 0 Alan 1 Bernard 2 Colin 3 Fran 4 Helen 5 Ian 6 Julie 7 Sylvia 8 Tom 9 William When we search through it we have to access each row and compare the contents to the value we’re searching for. Enter the program above and compile / test it. See if you can work out how to create a 2 nd array, which holds type Integer so that each students can be given a score (e.g. from their most recent test). Remember: • The array will have to be declared and setup in the same way as the StudentList array • Integers don’t have quote marks around them • Use a sensible name for array (e.g. StudentGrades or StudentScores) • You don’t need to use a 2nd loop for this array as once you find the student’s array index you can print their details using the following bit of code:

because if you know Colin as at position 3 of the StudentList list then you know his grade is at position 3 of the StudentGrades list (the index will be n

Working with Lists Lists, often referred to as arrays, are a very important data-structure in all programming languages. It’s important that you are happy with handling different types of data before you start trying to work with lists. This is because we can have string, integer, float and Boolean type lists. In the example above (the student list) you were working with a string array and possibly a 2nd integer array if you managed the extension (well done if you did!) The reason that these are so important is that programs often have to deal with a set of values rather than a single value. Sometimes, we don’t know how many values we’re going to have until someone uses it in the real world when it’s too late for you to track them down and update it because they want to be able to make it handle just one more piece of data which means it could stop working or become useless.

Defining a list When working with list, the values it holds are entered one after another separated by a comma. Copy out the first part of this program below:


19 | P a g e

Depending on what you’re doing, it can be impossible to know how many items are in a list. We can find out easily with the len() function. Add this to the program above:

Printing a List There are different ways to print list values, depending on what you’re trying to do. This is the most basic, but also the least powerful way to do it (it also takes a lot of typing when working with long lists!), add it to your program:

This way is much shorter and more useful:

In this example, we create a variable called student, it takes on the value of the first item in the list which allows us to print their name, before looping back to the FOR line to take the next value and so on to the end of the list.

Multiple lists Sometimes we need to know which index items in our list are at (the numeric position). Add this to your program:

The above format is most useful when working with more than one list of related items. In the following addition we’ll add a list of Boolean values to say whether this person was present at an exam:


20 | P a g e And finally, just to show off, we’ll add their test scores which are stored in a third list:

If we were actually writing this as a program the final code would probably look like this:

We could, of course, have created a program with a separate variable for each name (x6), a separate variable for present (x6) and a separate variable for their score (x6). This would give us 18 separate variables (18 lines of code to declare) instead of just 3. Imagine we had a whole school of students and lots more data to store (e.g.: parent’s names, addresses etc) and how long it would take?!?

Strings as lists Most programming languages deal with strings as lists (or arrays) on some level and Python is not different. Python does have some clever features that allow you to take advantage of this. Try the following code: #Print each character s = “This is some text.” for c in s: print(c) String as List Challenge: Look back at the work you did on lists. Change the “printing each character” program so that it prints out as follows:

Character 1 is T Character 2 is h Character 3 is i etc...

Extension


21 | P a g e Make the string print in reverse order so that the output looks like this:

Character 17 is . Character 16 is t Character 15 is x etc...

What if we want to only deal with vowels? Lists make this really straight forward using a combination of a loop with an IF statement inside it’s code block:

Dealing with alternate characters We can use another arithmetic operator (which is the percentage sign %). What it does is: •

Think back to how you did division when you first learned how to divide (but not how to work out decimal numbers) o

o

Work out the following: 

4÷2=2

9÷3=3

9÷2=?

The answer would have been 4 remainder 1


22 | P a g e In python we can do a similar thing and it can be quite useful as we’ll see in a minute. Try this to see the modulus operator (%) in action.


23 | P a g e Dealing with odd / even numbers:

Creating Methods You’ve used different methods that come as part of the Python language all through your work so far (some examples are print(), range(), len(), upper() etc). You can create your own methods which comes in handy when you find yourself repeating large amounts of code or when you want to break code down into more manageable chunks. There are two distinct kinds of method which are known as procedures and functions. They have a slightly different purpose even though they look very similar in lots of ways. The way to think of it, in very simple terms, is that: •

Procedures do stuff and then quit to go back to where they were called from. After this there is nothing left of them

Functions do stuff and then give you back a value before they go back to the place they were called from. You can then use this value elsewhere in your code.

Creating Procedures Things to look out for: •

Methods (both kinds) should go at the start of your program. If they don’t, any code that wants to use them will not know about them yet.

Methods always o

start with the def keyword

o

then the method name

o

then any arguments in (brackets)

o

any code within a function must be indented

Try entering the following program:


24 | P a g e

Creating Functions


25 | P a g e

Validating User Input Validation is something that we have to do a lot. This leads to 2 main questions: 1. What is it? 2. Why do we do it? To deal with the first question, it is a way of checking that user input is sensible (don’t mistake this as being correct as that’s almost impossible to achieve in most cases). Sensible here means that fits a number of criteria: •

Is it of the type of data that we were expecting o

If we want a number we have to make sure that the user didn’t accidently enter text

o

If we want one of a number of responses (e.g. yes or no), we have to make sure that the user entered one of the allowed values

o

If we need a number in a specific range (e.g. 1 – 10) that the user didn’t enter 11 instead

There are loads of possibilities depending on just what our program is trying to do at any moment but it’s usually quite obvious!

The second question is much easier to answer. We do it to make sure that our program works properly (as we intended) and that it doesn’t misbehave or even crash!!! Let’s look at some examples.


26 | P a g e

Checking for Allowed Choices Python is great for this and it’s much easier to do it here than in some other languages. In this program we want the user to choose from 3 options – a, b or c.

The important part here are the 2 lines of the WHILE loop which will continue to prompt the user to choose a valid option from the list ["a", "b", "c"]. This would read as: While the user hasn’t entered a, b or c Ask them to choose a valid option again The following IF statement simply does something with the choice, it isn’t required to check that they have entered something sensible.

Range Check This only really applies to numeric (integer or float) data-types. It is useful when you want to check that a number is BETWEEN two other numbers: if age > 12 and age < 19: print(“That’s the age of a FCC student.”) By combining it with several checks we can then make quite precise decisions without nesting IF statements in complicated ways.


27 | P a g e

Notice also the use of >= and <= which simplifies working with ranges significantly in some cases. Here’s another version of the same program that only uses > and <, not >= and <=.

These programs do EXACTLY THE SAME THING but in the 2nd version you have to start adding or subtracting 1 from the different ages. If we didn’t use the >= <= operators and didn’t change the age (>=13 is the same as >12 as they would both include 13 and above) then we would frequently get strange behaviour inside our programs.

Presence Check Sometimes we just need to know “Did anyone do anything?”. Here are some examples:

This checks to see if someone failed to enter a required value, their name in this case. This would commonly happen if they just pressed the enter key without typing anything first. What about for numeric data-types?


28 | P a g e

For boolean datatypes,

Notice there’s no inbuilt way to convert a string to a boolean, we have to do this ourselves but assigning a value to the appropriate variable. In this example, we’ve set happy = None on the last line which could be useful for checking that some kind of useful conversion has taken place, we might also be happy just to set it to False depending on how it would be used later (e.g. if happy not equal to True then you’re not happy so happy = False)


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.