MENU
- Introduction/Basic skills plus artwork/sound
- Installing and testing Python
- Acknowledgements
- Variables, comments and operators
- Functions
- Conditions and Loops
- Input and output
- Graphics
- Sound
- Logical calculations
- Computers, Programs and Python
- PYGAME
- Other Links
- Local files
1. Introduction/Basic Skills
Introduction:
- My idea is to introduce the topics in a logical order but of
course you choose the topics from the menu. I hope the titles
are self-explanatory except perhaps 10. (Logical calculations).
This is about methods of counting.
- Is Python a good starting point if you are new to computer
programming? YES
- You may have deduced this file is called "py2.html": please ignore the 2 (!)...
it is not about Python2 but rather the current version Python3.
- If you want to know if I've changed anything since you last looked
see the tiny
writing after the word "MENU" which gives the date of updating
the Web site.
- If you spot any mistakes find someone who might know my e-mail address and write to me.
Python is a language
not an app. or graphics program. Therefore we need a
blank screen for text and a text editor. For a Microsoft Windows
computer the blank screen is variously called a terminal or DOS
prompt. A clear account is in the excellent
Computer HopeWeb site.
In general:
Get to a Command Prompt in Windows 10
Click
Start
Type
cmd and press
Enter.
With a DELL Windows 10 computer the method is described in
DELL support and the screen should actually look something like this
C:\WINDOWS\system32>cd
C:\dir/w
Volume in drive C is OS
Volume Serial Number is 7205-36E5
Directory of C:\
[Dell] [Intel] [logs]
[Perflogs] [Program Files] [Program Files (x86)]
[Users] [Windows]
9 File(s) 0 bytes
8 Dir(s) 192,4981,542,144 bytes free
C:\>
The
computer is waiting for you to type in an instruction. it will be something like
C:\name>
(Don't worry about it!).
Now we need a proper text editor not a word processor. The Microsoft
text editor is notepad or
Basic Text Editor
Any problems: install Notepad++ from
https://notepad-plus-plus.org/ (it's free).
I have another suggestion in footnote 0.
I have produced copies of python programs etc. and to avoid a lot of typing
just copy them into your text editor. Here is a video
about how to do that. In this tutorial I have highlighted material to copy with a
pale yellowbackground.
Now we need to learn how to use your PC as a "real
computer" not as a games and e-mail terminal (!).
You should see a black box and now (as a test) type in dir. This is
roughly what it should look like.
Directory of Z:\.
COMMAND COM 20 01-10-2002 12:34
AUTOEXEC BAT 32 01-10-2002 12:34
KEYB COM 20 01-10-2002 12:34
IMGMOUNT COM 20 01-10-2002 12:34
BOOT COM 20 01-10-2002 12:34
INTRO COM 20 01-10-2002 12:34
RESCAN COM 20 01-10-2002 12:34
LOADFIX COM 20 01-10-2002 12:34
MEM COM 20 01-10-2002 12:34
MOUNT COM 20 01-10-2002 12:34
MIXER COM 20 01-10-2002 12:34
CONFIG COM 20 01-10-2002 12:34
12 File(s) 252 Bytes.
0 Dir(s) 0 Bytes free.
I typed in dir for directory to list the files. On your computer it will not
ha the prompt Z:\> but rather
C:\>
Now I typed in another command and here
is the result:
Z:\
Z:\cd /?
Displays/changes the current directory
CHDIR [device][path]
CHDIR [..]
CD [device][path]
CD [..]
.. Specufies that you want to change to the parent directory
Type CD drive: to display the current directory in the specified drive.
Type CD without parameters to display the current drive and directory.
Z:\>
It shows if you add "/?" to a command you can receive some help.
A list of such commands can found
HERE but I think all you need to do is to type in
python3
or py
.
I have provided a few pictures etc. HERE so you
can alter (and hopefully improve !) my programs. Also on that page are
links to my python programs but you should get used to copying the text
(yellow background) as explained HERE.
Finally in this section, if you run into the problem of lines of text running together see
footnote 5.
BACK
2. Installing and testing Python
Python is included in the distribution of Ubuntu LINUX and therefore I have
never had to install it. However the details are on
the Python and i strongly recommend this rather than
an *app store*.
.
You can test Python by typing py OR
python3 . It should reply with the Python prompt
>>>
to leave python type in
exit()
Try both commands so see which works. I always use "python3"
so remember to change this to "py" if necessary.
Now try something else.... give it some commands:
python3
>>>
x = "Donald "
y = "Duck"
print(x+y)
>>>Donald Duck
exit()
Now put that into you 1st python program copy the following
into a new file
called quack.py
#
x="Donald "
y="Duck"
print(x+y)
#
python3 quack.py
IMPORTANT: my version of Python insists on
python3<file.py> but if yours
requires or prefers py<file.py>
always use that.
Donald Duck
That's your own Python Program!
You should find the program is faster then the examples in (for example)
W3schools and
programiz
. Why do you think this is so?
At some point you will need the "Python Packet Manager" called
pip (? Python Installation package) written in Python. On my LINUX
computer
you simply type in 2 commands in a terminal
sudo apt update
sudo apt install python3-pip
For other types of computer see this
THIS
PIP is easy to use
LINK. The only problem is it doesn't always work!
Answer: type into a search engine (e.g. Google)
install <package-name> <operating-system>
Also make sure your pip is up-to-date. If you give pip a harmless (but
very useful) command
pip list
it will tell you how to update it. Be careful with such lists. Most of the
packages have lower case letters but sometimes capital letters pop up
unexpectedly and your computer probably thinks "python" and
"Python" are different words. If pip asks you if you
would like to update pip itself, the answer is "YES".
The other thing you will need to is to do is to import modules in
your python program. There are several examples in what follows. If you
want to look like a real python programmer you write your own modules - it is
really simple
LINK.
BACK
3. Acknowledgement and copyright
I have followed the course from W3schools because I have used them in
the past.
All my text and code is covered by
COPYLEFT.
BACK
4. Variables, comments and operators
Variables have names which must start with a letter or underscore _ and have
no punctuation or spaces, e.g. num1, num3, fred, _name. Note they
case-sensitive so fred is different from Fred. You can use _ or capital
letters to make the meaning more obvious, e.g. youngMan or old_lady. There
are two ways of inserting comments and we can see these in my next program
to try out.
This program which you should call prog1.py is the next thing for you to
copy and run. Note that Python has familiar looking mathematical
operators + (plus), - (minus), / (divide) and * (times). Note we
do not use "×". It looks too much like x. Also avoid
saying "4 and 3" if you mean "4 plus 3"
"and" means something else in computing.
Make changes to prog1.py and run it
(python3 prog1.py) to become familiar with Python.
#prog1.py
# Variables, comments and operators
"""
You can produce comments like this....
use 3 quotes in a row to insert a long comment
3 more quotes in a row to end the comment
"""
#or like this (hash) for a line or last part end of a line
s1="Welcome to Ulan Bator; "
s2="xxxxxxxxxxxxxx\
yyyyyyyyyyyyyyyyyyyy" #the backslash (\) quotes the end of the line
print(s1+s2)
initial='H'
print(initial)
print(initial+'oward')
z=14
y=23
x=y+z
print(x)
x+=3
# this means "x = x+3"
print(x)
x *=127
print(x)
x -= 23
print (x)
x /= 2
print(x)
#
#Multiple variables "tuples!" have several parts e.g.
boys=("Tom","Dick","Harry")
girls=("Sue","Daisy","Alice","Lucy")
children=boys+girls
print(boys[1]) # 1 is the "index" ... we start at 0
print(girls[0])
print(children)
print(children[4])
see footnote 1
BACK
5. Functions
We have already used the function print(). In that case,
"print" is the function name and for example
print(x) print("Goofy"): x and Goofy are
arguments. How do we write
our own function? It is simple with def.
Copy the following into prog2.py. This ia the first time we come
across the fact that Python uses spaces as an indentation for blocks of
code.... the contents of a def in this case. I have used 2
spaces but that is up to you.
# prog2.py
# note the indentations in the def. of the function
def greetings(name):
print("HELLO "+name)
print("Help yourself to a carrot")
x="Roger Rabbit"
greetings(x)
#
Typically functions do rather more than that. They may take several
arguments and return a result.
# prog3.py
def average(n1,n2):
x=(n1+n2)/2
return(x)
y = average(67,69)
print(y)
#
There are other methods that can be used in functions, e.g.
functions that can take any number of arguments
and "recursive functions" that call themselves.
BACK
6. Conditions and loops
Conditions
We have seen integer, float and string variables. We need to think
of a fourth type Boolean. There is more about this
LATER
Here is a short python session with computer's responses as comments (#)
#prog4.py
x = 6
y = 8
z = (y >= 6) #1
print (z)
if (z):
print("y greater/equals x") #2
if (y < x): #3
print("x is not greater than y ")
else: #4
print("y is greater than x")
#
z is a Boolean variable that can take 2 values, True and False.
RUN this program and it will say:
True (calculated in line #1
y greater.... (because z is true #2
note the colon (:) after the if()
and the indented text))
(we do not need to calculate z #3
there is no output because the if() is false)
y is greater.. (the if() was true in this case.)
>, >=; < &l;=; == ;|= mean greater than; greater than or equals;
less than; less than or equals; same; not equals..
Mistakes with == is one of the commonest errors among people programming
for the first time.
x = 7 means s is given the value of 7. if(x=7) is always
true and the value of x will have changed to 7.
y == 7tests whether y and 7 have the same value.
Loops (for)
We use conditions if we want the program to do the same kind of
operation over an over again. Here is a program with such a loop:
#prog5.py
for x in range(1,6):
print(x*17)
#
The program works out the 1st six numbers in the "17 times table".
Edit the program so it performs another group of mathematical calculations.
Here is another program illustrating a different "for loop"
#prog6.py
names = ["Alice","Florence","Daisy","Tom","Fred","Bruce"]
for x in names:
print(x,end=" ")
print("\nI don't like Tom:")
for x in names:
if x == "Tom":
continue
print(x,end=" ")
print("\nI don't like boys:")
for x in names:
if x == "Tom":
break
print(x,end=" ")
print("\n")
The result should look like this:
Alice Florence Daisy Tom Fred Bruce
I don't like Tom:
Alice Florence Daisy Fred Bruce
I don't like boys:
Alice Florence Daisy
Here we see how to work along a tuple. Notice the two ways of interrupting
the loop: continue which goes to the next round without actually
doing anything (e.g. removing the display of Tom) and break (stopping
after Daisy). Another detail not specifically to do with loops is the
tidying up of print(): see footnote
Loops (while)
There is a different way of writing a loop in Python. This is to carry on doing
something while some condition remains true. Without writing
a lot of theory of this let us look at and run(!) prog4a.py which is a
"while version" of the 17 × table program.
# prog7.py
x = 1
while x<7:
print(17*x)
x+=1
#
BACK
7. Input and output
So far we have used the keyboard as the input
(called stdin "standard in"in Linux/Unix)
the screen as the output
(called stdin "standard out"in Linux/Unix).
However (a) file(s) can be used in place of stdin and
stdout. Let us start with the top of this file (py2.html)
whicj I have saved as header.text and do
something with it. We need s variable to act as a file
handle. Let's call it f (see prog8.py).
prog8.py and prog9.py both assume there is a file called "header.text" in the
currenr directory. So you have to do one of 3 things.
1, Reokacw "header.text" with another file name that is there.
2. Download "header.text" from jhpsoft.co.uk/py
3. Go to my LINK
HERE
# prog8.py
f=open("header.text","rt")
for x in range(0,6):
y=f.readline()
print(y,end=" ")
f.close()
The file handle f is associated with a file "header,text"
(i.e. this
one) to be read (the r) to be regarded as text (t).
Alternatives to these include w (write) and b
(binary i.e. not text).
TRhe next one does much the same but (trivial) we are reading a different part ofthe
file and (more important) we introduce the with< method.
# prog9.py
with open("header.text","rt",encoding="utf-8") as f:
for x in range(0,6):
y=f.readline()
for x in range(0,8):
y=f.readline()
print(y,end=" ")
f.close()
#
Notice the indentation after "with...." and indentations for the
two for loops. Study code and run it. I don't claim to be much of a poet!
Now we can demonstrate the use of a file for output. Be careful with this
one: I am not using your computer and the new file will appear in
whatever directory you are working in. Fortunately the resulting file
will be short.
#proga.py
sig="Your Friend"
f = open ("myFile", "w")
f.write("\nBye for now")
f.write("\nSee you again soon!")
f.write("\n"+sig+"\n")
f.close()
Input from the keyboard
Look at prog9K.py.
#prog9K.py
n = input("what is your name ? ")
nt = type(n)
a = input("what is your age ? ")
# a is type str
ai = int(a) # ai is type int
print(n+": your age 2 years from now will be....")
wrong=a+"2"
correct=ai+2
print("wrong: ",end=" ")
print(wrong)
print("correct: ",end=" ")
print(correct)
... and run it.
Here is the output when I ran the program.
what is your name ? Sammy
what is your age ? 13
Sammy: your age 2 years from now will be....
wrong: 132
correct: 15
Explanation: input() returns astring so the answers to the 2 questions were
"Sammy" and "13" but to add the "13" to
2 we have to convert it into number 13 with the function int()
(integer meaning whole number).
BACK
8. Graphics
Theory
Imagine you have a pencil and paper and you want to draw a picture. You
have to start somewhere. We shall call this place the origin (O).
Having established where the origin is we need two numbers to describe a
position on the paper. In the Cartesian system, named for the French
philosopher René Descartes, they are two distances along
lines called axes that cross one another at right angles at the origin.
Most computer graphics
use this system. Let us call the horizontal axis the x-axis and the
vertical one the y-axis. Note it is conventional for plotted graphs
to have the x-axis increase from left to right and the y-axis to go
from bottom to top but computers have the y-axis going from top to bottom
(to be consistent with text in European languages. A point in Cartesian
geometry is represented thus (x,y)... i.e. the origin (bottom left) is (0,0).
In Python these are called points not tuples. In the diagram below
a * is at (6,2)in the Cartesian (black) and computer (red)
systems.