FREE Python worksheets in Word 2010

advertisement
Page | 1
Introduction to Python – things
you need to know
1. Open Python from the ICT menu
2. You want the Python GUI which has a white background. If it is black
close and try again.
3. This is for creating text based coded programs and the name comes from
the Monty Python series. The Python GUI (graphical user interface or
gooey) is called the Python shell when it opens up. This is a word
processing program that you will use to code in.
4. As soon as you hit the enter key it will run the program and you do not
want it to do that as you may want to open several lines of code. This is a
pain so you have to find a way to stop it doing this…
5. Click file new then file save as and set up a Python folder to keep all
your programs (and you will make lots). It will open a new window – in this
window you can type lines of code and it will not run your program or try
to do anything with it until you hit F5.
6. Do this every time you start a new program: 1) open Python GUI, 2) File
save as name the program before you start.
1 Your First
Page | 2
Program
1. Type this into Python
print ("hello world")
2. Run the program in F5 it will prompt you to save – call it prog1
The word print will come up in purple which means it is a COMMAND
The Hello world will come up in green which means it is a TEXT STRING
STRINGS need speech marks so the computer knows it is a string and not a
command. (How do we know when someone is staff? Maybe they wear a top that
says staff so we can identify them. It’s the same with code we use “” as
identifying marks so the computer program recognises that you want that to be
seen as a text string.)
Brackets will be black which means they are a variable – more on that later.
Exercise 1a
Change the program so that it says “pleased to meet you”
Exercise 1b
Change the program so it says “This is Lucy’s first program” but
change the name to yours.
New Vocab:




String
Command
Variable
GUI
2 Using
Page | 3
syntax
Syntax is how we describe the way the words are arranged on the page.
Sometimes you might not want all the words to run from left to right, you may
want line breaks.
1. Type the following into Python:
print("this is")
print("the way to")
print ("print words on several lines")
2. Press F5 and call it prog2
Exercise 2a
Sometimes we want a space between lines that print out. Try this code:
print("this is \n")
print("\n")
print("the way to")
print("\n")
print ("print words on several lines")
New vocab: syntax
Page | 4
3 Variables
We can assign or store data in a variable so that it can be used in the program.
For example we may tell the computer that x=6 or that a=3 and we can assign
names as a string variable.
name = "Sarah"
print ("hello " +name)
The first line tells the computer that name is a variable – in this case a text
string. In that text string is the name Sarah. The second line then tells the
computer to print the word hello and whatever is in the name variable. This is
very handy with really long bits of code that you don’t want to type over and
over again – you can pop it into a variable and call it up every time you need it.
Handy eh?
Note the syntax that the second line has a space after the hello. Without the
space it just runs the two words together helloSarah.
Exercise 3a
Type this program and run it – what does it do?
name="sarah "+"hilton"
print ("hello " +name)
Page | 5
4 Annotations
As you move along your program writing it you may wish to add some annotations
so you know what you were thinking or what the program was trying to do. This
will help you when you are writing a longer program.
#we use a hashtag symbol to indicate that we are annotating our own work and
it should appear in red.
#I am going to write a program which will print the
cat sat on the mat.
word1="the"
word2="cat"
word3="sat"
word4="on"
word5="the"
Word6="mat"
#what do I need to type in now to get the program to
work?
If you want to type more than this it will just keep typing across the page and
will not move down like a normal word processing program will do. So to stop it
being strange like that we can use three “”” speech marks to make a block of
text in an annotation.
Page | 6
5 Interactive programing
A TV programme is not the same as a computer program or programing. The
spelling is different. Just thought we should mention this at this stage.
Anyway coding is creating programs for other people to use. There are two
people in this relationship:
You:
Someone else:
The program coder
The program user
So let’s make a program for someone else to use. First decide in the class who
will be your user. Now you can create some code for them and when you have
finished ask them to try out your program to see if it works.
name=input("what is your name?")
print("hello "+name)
Did your user try your program?
Did it work? If it didn’t work look carefully at the spacing (syntax) you may be
putting too many spaces in. Coding is like learning to type in a different way all
over again.
Exercise 5a
Now code a program to ask what their favourite kind of music is and to output
that you really like that kind of music too.
Page | 7
6 Calculations with variables
Python also can carry out calculations using arithmetic operator symbols that
you would find in a maths lesson or on Excel.
+ (plus)
– (minus)
/ (divide)
* (multiply)
Try this simple program
print(3+7)
print(8-3)
print(7*4)
print(9/6)
Python will do the maths for you, impressive eh?. We can now use operators and
variables in the same program:
a=11
b=3
x=a/b
print(x)
Notice that everything you want printed will need to be in brackets. That is so
the program knows what to do with it.
Exercise 6a
Create a program where a=10 b=7 and x=17
Page | 8
7 Using the Python libraries
Python has a group of libraries of information that you can call on to help with
your calculations. For example it has a maths (or math) library which contains
values such as pi so you so not have to put it in.
Open Python IDE
Click on Help>open Python Docs > Left hand bar open Python Standard Library
You can scroll through and see all the libraries
To call a library we use an import math, note in the program below that a would
be radius of a circle and the surface area formula is π r2. To get a square we
use two stars, and we use the variable a to stand in for r. So the finished
formula looks like this; pi*a**2
import math
pi=math.pi
a=float(input("enter radius: "))
c=math .pi*a**2
print("this will give surface area: ",c)
We can round the result to 3 decimal places by adding the code to the above
program:
C = round(pi*a**2,3)
Page | 9
8 The IF statement
A CONSTRUCT is an item of programming like a loop, it is a chunk of code which
does something. The IF statement is a construct.
The IF statement can be Boolean which means that it is either true or false.
So in programming:
== means is equal to
!= means is not equal to
Create the following program, the indents are important for how the computer
organises the program. Some of the indents it will put in correctly some you will
need to force with tab key.
You can only run this program once, each time try typing different letters and
resetting and running the program each time.
letter=input("letter?")
if letter =="a":
print("this prints out if the letter typed in was an a")
print ("this prints as well")
elif letter =="b":
print("this prints if the latter typed in was a b")
else:
print("this prints if something other than an a or b was typed")
print("this always prints out at the end of all the other printouts")
Exercise 8a
Now try re-writing the program so that if orange is typed a funny joke appears
and if banana is typed it gives a warning message.
Page | 10
9 Using the random module from the
library
The library in Python as well as having math also has a random number generator
which you can use in a number of programs. So have a go at calling up the
random module from the library.
First code a dice:
import random
print (random.randint(1,6))
Now expand this program:
import random
min=1
max=6
print ("rolling the dice...")
print ("the values are...")
print (random.randint(min,max))
print (random.randint(min,max))
input("roll the dice again?")
To get the dice to
roll
again we will need to
create
a loop and that comes later.
Page | 11
Page | 12
9 continued using the random library
We can use the random to give us a different random number every time – ideal
if you are coding a game that needs a random outcome each time or trying to
pick numbers from a hat.
#First we import the random library into the program
Import random
#Then we identify our variable and how this should relate to the random
library, the randint just means it’s a random integer rather than a fraction or
decimal
X=random.randint(1,100)
#Then we request that the program prints out the variable – which if we have
done it right should be a random number from 1 to a 100
Print (x)
Exercise 9a
Can you code the above program?
Page | 13
9 continued - Longer random
program – magic 8 ball…
A magic 8 ball is a toy that you can shake and it will give a
random answer to a question. Answers include; yes, no,
maybe, go for it! You can edit this as you code.
#first call the random library
import random
#now add the answers as variable strings
ans1="go for it!"
ans2="no way don't do it"
ans3="I'm not sure ask again"
ans4="You are afraid I sense that"
ans5="It would be madness to do that"
ans6="Only you know the true answer"
ans7="Maybe wait until tomorrow"
ans8="Yes I think on balance that is the right choice"
#now add a welcome message to your user
print("welcome to magic 8 ball")
question = input ("Ask me for advice then press enter to shake me.\n")
print("shaking\n"*4)
#now use the randint function to generate a random number between 1 and 8 we are then going to assign the
result to a variable we will call choice.
choice=random.randint(1,8)
if choice == 1:
answer=ansl
elif choice ==2:
answer=ans2
elif choice ==3:
answer=ans3
elif choice ==4:
answer=ans4
elif choice ==5:
answer=ans5
elif choice ==6:
answer=ans6
elif choice ==7:
answer=ans7
else:
answer=ans8
#now print the answer to the screen
print(answer)
10 Iteration
Page | 14 Iteration is another coding terminology that means repeat. You may have heard
someone say “I will reiterate what I said earlier about not leaving your
folders….” This means they are repeating what they said at an earlier point in
time.
Let’s look at a simple iteration code – make sure your indents are right (see the
big arrow)
x=0
while x<5:
print("this code will loop this string of text down the
page")
#to end this program you will need to kill it which
means close the top window
Why does the program keep going forever? How often does x meet the
condition x<5, if this is always the case then the program will continue to run
until you kill it.
Exercise 10 a
Fix the program, by adding the following code; x=x+1, print(“finished”)
Exercise 10 b challenge
Write a program to ask for a password, and when the word apple is input then it
should say that the password is accepted.
Exercise 10 c Dragon Realm
Page | 15
Game
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
The coding for this
program is
continued over
the page…
displayIntro()
Page | 16
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
Download