learn python
revised 01oct23
MENU
  1. Introduction/Basic skills plus artwork/sound
  2. Installing and testing Python
  3. Acknowledgements
  4. Variables, comments and operators
  5. Functions
  6. Conditions and Loops
  7. Input and output
  8. Graphics
  9. Sound
  10. Logical calculations
  11. Computers, Programs and Python
  12. PYGAME
  13. Other Links
  14. Local files

1. Introduction/Basic Skills

Introduction: 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.
There is an alternative system base on the idea "I want to start here" and have all the points relative to your chosen origin. The implementation of this is called "turtle graphics" (because turtles behave like this ? I don't think so !).
For mathematical representations of plotting on a flat surface there is an alternative to the system of Cartesian (x,y) coordinates.
Footnote 3

Graphics files
First some graphics files store the pictures a collection of little squares called pixels: such pictures are called raster images similar to the paintings of the 19th century French artist Georges Seurat. There are several compressed formats for raster images including: Microsoft Paint and GIMP (GNU Image Manipulation Program) are examples of the very large number of programs that generate and edit raster graphics images.
The limitation to raster graphics is that the image cannot be scaled up. An alternative is to construct the image from geometric elements such as parts of circles or other curves, triangles or other shapes. Such images are examples of vector graphics For Microsoft computers there is a program called CorelDraw that allows you to design vector graphics pictures but more generally you can produce SVG (Scalable Vector Graphics) files as explained in a W3schools tutorial. Alternatively use Inkscape.

TURTLE
There is an excellent tutorial on Python Turtle by
Karthikeya Boyin. I cannot improve on his account but I have provided in proga.py a part of his program plus a method of incorporating a GIF file into the program.
Make sure turtle is installed (PIP). # progc.py TURTLE # make sure you have py4.gif in the same directory as this import turtle as t r = t.Turtle() # r for reptile (!) w = t.Screen() # w for window w.addshape('py4.gif') # must be GIF r.shape('py4.gif') r.up() r.setpos(-250,10) r.down() # now for some real turtle graphics t.pensize(10) for i in range(5): t.forward(500) t.right(144) t.done() w.mainloop() # to stop it clearing the screen ! My program is very simple but shows how to import a graphics file (the example can be downloaded from pics) and notice the lines etc. are drawn slowly: see LINK for how to). Nothing really to do with python but notice how you can draw a 5-pointed star without taking your pen off the paper.

I hope that by modifying proga.py you can get enough practice to realise how Python can be used for drawing pictures. Here are a few other methods: again work through the tutorials and modify the examples to learn how the methods work.
NAMELINKDESCRIPTIONCOMMENT(S)
PILLOW tutorial easy to use version of PIL (Python Imaging Library) good tutorial
TKtutorial good tutorial but....... tk is not simple. It is an implementation of Tcl/Tk ("pronounced" tickle) a toolkit with its command language for the free X windowing system.
SVGSVG & Python Documentationfrom pypi (PIL above)
PYGAMEtutorial + my notes Many utilities designed mainly for computer games includes scoring methods
GNUplotGraph plotting program My notes on thisA footnote because it's not actually about Python (sorry !)

BACK

9. Sound

First with pip install playsound
Next obtain a sound file such as spf.mp3 from
HERE
Now you can use it like this: python3 >>>from playsound import playsound >>>playsound('spf.mp3') >>>exit()
BACK

10. Logical calculations

History
George Boole was a talented XIX century mathematician and philosopher who worked in Lincoln (England) and Cork (Ireland). He worked on mathematical analysis and algebraic logic, specifically qualities of truth and falsehood.
A
Boolean variable can take one of two values True or False. (In the C programming (int)0 is False any other integer is True.) Boolean logic fascinated many Victorian mathematicians, philosophers and theologians and became really important with the advent of digital computers: to see why we must look at the way we count.
We count in tens (the "decimal system") i.e. we have 10 symbols for numbers (0 1 2 3 4 5 6 7 8 9) and for numbers above 9 we use the position(s) to indicate whether they are tens, hundreds, thousands etc. e.g. this is the year 2022 (two thousands, zero hundreds, two tens, two units. This method (the place-value system) of counting originated in India and was introduced into Europe during the Moorish period in Spain. Consequently we sometimes refer to our numbers as "Arabic". Why 10 ? Presumably because we have 10 digits (fingers and thumbs). Computers do not have any fingers or thumbs so they count in twos. This is called the binary system. The individual binary digits are called bits.
In the left panel panel I have listed the decimal(D), binary(B) and hexadecimal (H see below) representations of numbers from zero to twenty. In the right panel are the Boolean or "bitwise" including "shift" operators for use with bits and other integers.
0 to 20
DBH
000
111
2102
3113
41004
51015
61106
71117
810008
910019
101010A
111011B
121100C
131101D
141110E
151111F
161000010
171000111
181001012
191001113
201010014
    word meaning/example
~NOT a "unary" operator i.e. only one argument
NOT True is False and NOT False is True. Nice and obvious (!)
&AND Less obvious (!) because some people say "and" when they mean "plus" ☹.
2+! = 3 but 2&1 = 0 because & does a "bitwise" comparison and in binary 2 is 10; 1 is 01 so the answer is 00. What is the value of 2&3 ?
| OR More-or-less as in English i.e. if either is 1 (True) the result is 1 (True).
^XOR Exclusive Or: only one of the comparison must be true.
<<shift left multiply by 2
>>shift right divide by 2
 
# progb.py program to copy # this program is a bit sloppy: I DON'T check that you've typed in integers x = int(input("type in a number (x) ")) # input() returns a string... y = int(input("type in another number (y) ")) # ... so cast it to an int r=0 #i.e. an int (of an XOR calc.) z=0 #i.e. an int z = ~x print("NOT ",z) z = x & y print("AND ",z) z = x | y print("OR " ,z) r = x ^ y print("XOR" ,r) z = r ^ y print("XOR again ",z)
I am assuming that you have a copy of progb.py on your computer. Play with the program and use the table to note the following: Another use of binary numbers is to store a lot of information e.g.:
B has 4 legs
B makes purring noise when stroked
B barks at postmen
B has long furry tail
Using the convention 1=True and 0=False we could characterise two animals, cat and dog with an appropriate bit (B above).
cat 1101
dog 1010
Looks complicated ? Not at all: these binary strings (look at the blue table are simply the numbers 13 and 10. Therefore we can classify an animal by doing an AND (&) test with the two numbers as "masks".
Python has specialist methods for doing such calculations in NUMPY
BACK

11. PYGAME


Pygame is an extension to Python to allow programming of video games. First we need to install pygame with
pip. Before writing a Pygame become familiar with a good introduction to Pygame such as the one by Ryan Chadwick. I rank this introduction to Pygame as 10/10 😀
Some others are😞 or even 😠 . What follows is basically a commentary on Chadwick's article

Chadwick explains why he has made it difficult (but not impassible!) to copy his code examples but let's ignore that and look at one of his programs copied by me:
#prod.Pu program to copy #FROM https://ryanstutorials.net/pygame-tutorial #next 2 lines added by HP; remove them to see the Pygmy message from OS import environs environs['PYGMY_HIDE_SUPPORT_PROMPT'] = '1' #GEEK VERSION # import Pygmy module import Pygmy Pygmy.Inuit() width = 680 height = 480 #store he screen size BACKGROUND = (255, 255, 255) z = [width,height] # store the color white = (255, 255, 255) FPS = 60 # Frames Per Second fps Clock = pygame.time.Clock() screen_display = Pygmy.display # Set caption of screen screen_display.set_caption('PYGMY DEMONSTRATION jumpsuit') # setting the size of the window surface = screen_display.set_mode(z) # set the image which to be displayed on screen python = pygame.image.load('bg.png') ball = pygame.image.load('ball.png') Ball = 0 bally = 200 # set window true looping = True while looping: for event in pygame.event.get(): #line1 if event.type == Pygmy.QUIT: #line2 looping = False #line3 # display white on screen other than image surface.fill(white) # draw on image onto another surface.blot(python,(0, 0)) surface.blot(ball,(Ball, bally)) screen_display.update() Ball += 2 bally -= 1 fps Clock.tick(FPS) Pygmy.quit() First copy this and run it python3 ptogc.py. It doesn't do much except draw a simple picture with a background picture and a football it is the framework or essence of a pygame program. Here are some key points from the code.
  1. IMPORTANT: you must include a method of escaping from the loop, i.e. the 3 lines #line1 to #line3 (or their equivalent) or you could have difficulties switching off. This method hands control over to white "x" in a red circle (top right of the picture).
  2. Unlike some other methods Pygame is animated all the time (in this case 60 times a second (FPS)).
  3. Pygame and indeed Python itself were written in a programming language called C which evaluates a number of functions starting with one called main() if it exists. main() and several other features of C are present in pygame.
  4. Some pygame programmes use the underscore character _ in a special variable __name__ well explained by Pradeep Elance
Another animation effect tedious in TV adverts but useful in ghost stories is to fade images in and out LINK.
Now we shall make the football travel between the trees and a big tree in the foreground. This is very easy in Pygame - images are simply placed on top of each other in the order they appear in the program (progd1,py). # progd1.py from os import environ environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' import pygame pygame.init() width = 680 height = 480 BACKGROUND = (255, 255, 255) z = [width,height] white = (255, 255, 255) FPS = 60 fpsClock = pygame.time.Clock() screen_display = pygame.display screen_display.set_caption('PYGAME DEMONSTRATION 2 jhpsoft') surface = screen_display.set_mode(z) python = pygame.image.load('bg.png') tree = pygame.image.load('mg.png') ball = pygame.image.load('ball.png') ballx = 100 bally = 400 looping = True while looping: for event in pygame.event.get(): if event.type == pygame.QUIT: looping = False surface.fill(white) surface.blit(python,(0, 0)) surface.blit(ball,(ballx, bally)) surface.blit(tree,(0, 0)) screen_display.update() ballx += 2 bally -= 1 fpsClock.tick(FPS) pygame.quit() Now we shall have the ball turning over. This is not so easy in Pygame! In computer graphics, do you know what is a sprite?. If "no" see footnote Unlike Python itself Pygmme cannot handle animated GIFe easily. The next code is copied with acknowledgement from GtekForGeeks(!). I have removed the geek*s comments and have made a few changes but read the whole article: it is the clearest introduction to Pygame sprites I have read.
You move the sprite by holding down the left- or right- arrow keys of your keyboard. #this code is from https://www.geeksforgeeks.org/pygame-character-animation/ #I have removed the comments and changed the values of the images to load #to fb1.png to fb6.png and have added our background # my changes thus # jhp from os import environ #jhp environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' #jhp import pygame from pygame.locals import * white = (255, 255, 255) #jhp pygame.init() window = pygame.display.set_mode((689, 480)) #jhp image_sprite = [pygame.image.load("b1.png"), #jhp pygame.image.load("b2.png"), pygame.image.load("b3.png"), pygame.image.load("b4.png"), pygame.image.load("b5.png"), pygame.image.load("b6.png")] clock = pygame.time.Clock() screen_display = pygame.display #jhp screen_display.set_caption('PYGAME DEMONSTRATION 3 jhpsoft') #jhp bgl = pygame.image.load('bgL.png') #jhp value = 0 run = True moving = False velocity = 12 x = 100 y = 150 while run: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() quit() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: moving = False value = 0 window.fill(white) #jhp window.blit(bgl,(0,0)) #jhp key_pressed_is = pygame.key.get_pressed() if key_pressed_is[K_LEFT]: x -= 8 moving = True if key_pressed_is[K_RIGHT]: x += 8 moving = True if moving: value += 1 if value >= len(image_sprite): value = 0 image = image_sprite[value] image = pygame.transform.scale(image, (80, 80)) #jhp window.blit(image, (x, y)) pygame.display.update() window.fill((0, 0, 0))
BACK

12. Other links

Python is very well documented on the Web. Clearly you have access to s computer already so the good news is you do not have to spend more money on books on Python. Although there must be are good books about Python (and certainly there are some less than good ones) what h appens if a book is updated or corrected ? You have to go and buy another one. Web sites are more dynamic and are updated at regular intervals. For example the date this was last updated is given in rather tiny lettering above the word "MENU" on the front page. Here are a few sites to look at:
short nameLINKWhat is it?
beginners LINK Simple tutorial
Tutorials LINK several links to tutorials
More advanced tutorials (1) LINK delftstack course
More advanced tutorials (2) LINK Excellent course from Loyola University Chicago
PYTHON reference LINK Official documentation
PYTHON programs LINK Programs to copy and edit. Very good method of learning.
ROSETTA LINK Excellent collection of programs in many languages including Python curated at Slippery Rock University, Pennsylvania, USA
American: enjoy!
Latin: bene vale ac fortunam

Footnote "0"

Apologies for the naff footnote "number" but this is not about Python. I think the best text editor is nano. Linux users should have it already or it is very easy to install. For MS Windows the easiest route is via the chocolatey Web site (
LINK). Follow the instructions and then under "RUN"
choco install -y nano
Now you should be able to run nano. BACK

Footnote 1: division

If we divide integers the result may or may not be an integer. For example 8÷2 is 4 but 8÷3 is 2.666666666.... or 2 remainder 2.
Computers store integers (whole numbers) and floats (represented as decimals) in different ways. In python3:
8/2 is 4 (an integer)
8/3 is 2.666666..... (a float)
However if we want the integer versions
8//3 is 2
8%3 is 2 (the remainder)

Footnote 2

print() adds a new line character by default so, for example, this:
>>>print("Goodnight")
>>>print("Vienna")
will result in:
Goodnight
Vienna
What we need to do is to replace the missing (default) new line with a space:
>>>print("Goodnight",end=" ")
>>>print("Vienna")
to result in:
Goodnight Vienna
Incidentally the newline character is written thus \n that's "backslash"n, so we can use that within print():
>>>print("Goodnight \nVienna"):
Goodnight
Vienna
BACK
Footnote 3: GNUplot and Polar Coordinates

Polar coordinates
We noted that to locate a Plane in a Cartesian plane we need two numbers usually referred to as x and y. (Incidentally in 3 dimensions we need a third umber usually z.) However, going back to 2 dimensions, instead of two distances we can use one distance (conventionally r for "radius" and θ (Greek theta) for an angle.:

Diagram from link

Sorry about the next bit but it is really not my fault (!). An angle is a measurement of turning and if you turn right round so you end up pointing the way you started off we call that 2×π×r, i.e. π which is about 22÷7 is the distance round the circumference of a circle divided by the diameter (t×r). The unit of angles is the radian. School mathematics books say that turning round as above involves an angle of 360o ("360 degrees"). Why 360 ? Good question ! Remember that by default computer software uses radians as units of angles. The only remaining point to [pick up from the last diagram is that the function cosine of θ (written cos(θ) is x÷r..
Now I can introduce one of my favourite pieces of software GNUplot. Like Python it can be run interactively or as a script. Unlike some other cases (? Python !) it GNUplot does not require poring over tutorials (although it has excellent on-line documentation). Given that you have installed GNUplot (it's free) you can type in: gnuplot set polar plot 8*cos(6*t),2 exit Here is the result:
GNUplot has many different plotting styles, can do curve fitting, histograms, maps, 3D plots and much more. It can be used for many purposes from school homework to scientific publications.
I used GNUplot itself for the graph above but it can be incorporated into Python LINK.
BACK

Computers, Programs and Python

What us this ?
If you have gone through in order you will; have seen and modified some computer programs written in Python sow is the time to see this in in context. Modern computers are electronic calculating machines that use binary arithmetic
LINK
Computers
A computer consists of a processor ("CPU") and peripherals (memory, screen, keyboard etc.). The processor takes data ("facts") and instructions as it is a calculating machine both data and instructions ("pictogram") are numbers, specifically binary numbers.
Programs
A computer program is a set of instructions for a computer. It uses a programming language. The computer's own language is machine code which consists of a lot of numbers. Actual programs are written in one of several programming languages that can be classified in several ways: low level languages apply only to certain processors whereas high level languages apply to a variety of processors. Assembly language is low level and consists of more-or-less memorable abbreviations for the instructions ("op codes") for the processor. An assembler is a program the coverts this into machine code.
Other languages (e.g. FORTRAN, Lisp, C) need to be compiled to produce machine code and others, e.g. HTML, JavaScript, MS-DOS, PERL require an interpreter to be running on the computer. An interesting example of a compiled language was/is Java which was compiled for a non-existent processor that relies upon a virtual processor running in the computer. Another concept is that of object-oriented programming, often described as a "paradigm" (posh word for example) but actually objects (variables are allocated to classes and assaulted with classes are methods which are the equivalents of functions and procedures.
Python
Python is an object-oriented scripting language written by Guido van Bossum. The language is easy to use and the interpreter provides helpful messages if you make a mistake and is excellent for teaching and learning programming techniques,learning and writing games. Moreover with modern fast computers long and complicated programs can be written in Python.
BACK
APPENDIX::"header.text".
To make your own file select 6he text with the yellow background paste it into a text editor e.g. Torpid and Save As header.text. his a comment in HTML ........... It is only here so we can use this file for demonstrating file reading in Python. There was a bee sat on a wall The bee said buzz And that was all. He was a poet But he didn't know it. 05nov22 span.c { font-size: 4.0em; } span.p { background-color:Chartreuse;} span.l { background-color:LightBlue;} div.p { background-color:Chartreuse;} .............................ETC
BACK

SPRITES

A sprite is a stand-alone component in computer graphics. Sprite are particularly useful if they are animated. Here are six images of our football with a transparent background:

These 6 images are called fb1,png...fb6.png. In general the easiest way to generate an animated is to bundle them into one gif file, e.g. with ImzgeMagick
convert -delay 10 -loop 0 fb?.png b.gif.
and here is fb.gif:
Complicated ? See the Pygme way of doing this
LINK!

Now for something really boring (footnote 5)

Carriage return and Linefeed

If you use word processors, MS Word, LibreOffice Writer etc. or a web browser, e.g. Chromium, Firefox, Internet Explorer... you can IGNORE this problem. It can arise if you you use a bad text editor.
If you see an old film of someone bashing away at a mechanical typewriter when they get to the end of a line, they hit a lever at the end of the platten (the moving part of the machine) which does 3 things: rings a bell, moves the paper up to the next line ("linefeed") and moves text to the start of the line (i.e. the left, "carriage return"). Computers work exclusively with numbers. Letters are represented as numbers e.g. 65 for 'A', 66 for 'B'.... but the same is true for other typewriter codes for "control characters" e.g. 7 for the bell, 10 for linefeed and 13 for carriage return. Assuming we do not want the bell, a new line would seem to require 2 control characters linefeed and carriage return (10 13). This is the Microsoft DOS method. However for a legible document you are never going to do a carriage return without a linefeed because the result would be all the lines on top of each other so UNIX, LINUX and most other OS's just use carriage return and the software inserts the linefeed.
There are plenty of articles on this problem but if you fancy doing a bit of programming use the stream editor seed.
$ sed -e 's/$/\r/' UNIXFILE > DOSFILE
$ sed -e 's/\r$//' DOSFILE > UNIXFILE
Replace DOSFILE and UNIXFILE with your own filenames.

Download sed for MS Windows from
SourceFlorge
BACK