Notes On Python Course
Notes On Python Course
Notes On Python Course
2
Math Functions............................................................................................................................................2
Variables......................................................................................................................................................2
Functions.....................................................................................................................................................3
Saving scripts...............................................................................................................................................3
Strings..........................................................................................................................................................4
Ignoring Control characters.....................................................................................................................4
Concatenate strings.................................................................................................................................4
Concatenate strings and integers........................................................................................................4
Sequences and Lists.....................................................................................................................................5
Slicing or grouping...................................................................................................................................5
Searching strings......................................................................................................................................5
Other functions in Python for sequences and lists..................................................................................6
Len.......................................................................................................................................................6
Max, Min.............................................................................................................................................6
List.......................................................................................................................................................6
Replacing a value in a list.....................................................................................................................6
Example of using the above commands..............................................................................................6
Methods......................................................................................................................................................7
Various Programming Statements...............................................................................................................8
If and Else Statement...............................................................................................................................8
Nested If Statement................................................................................................................................8
While and For Loops................................................................................................................................9
Infinite Loops...........................................................................................................................................9
Comments.............................................................................................................................................10
User Defined Functions.............................................................................................................................10
Parameters............................................................................................................................................10
Return................................................................................................................................................11
Multiple Parameters..........................................................................................................................11
Class, Object, and Methods.......................................................................................................................12
Defining a class......................................................................................................................................12
Notes on Python Course
Installation
Go to python.org and download the latest version. Install.
After installation, what looks like a command prompt window will open, but the prompt
have three chevrons: >>>
This is the python interpreter. But we’re going to use the python shell, which is called
IDLE. This allows us to have a menu where we can access things like File (save, new,
etc.), edit, shell, debug, etc.
Math Functions
Basic math functions can be typed in simply: 2 + 2, which will output 4, or 2-2. But
when you use the percent sign, it gives you the remainder. So 21%7 results in 0, but
21%8 results in 5 (the remainder).
Multiplying works as expected (2*2), and so does 2*2*2. But you can do a shortcut for
powers or exponentials by using double asterisk. So 2**3 is the same as 2*2*2. 2**5
results in 32.
Variables
Variables are names used to store a value. So we can begin with:
X=2
Upon hitting enter, that is now stored. If you then type x+2, it will give a result of 4.
But what if you want the user the enter a number? Then you would type:
Why int? Because if you just type: input(“Enter the number: “) it will be treated as a
string, not a number. If you were to do that and then type: x (and hit enter), the result
would be: ‘5’ instead of 5. It is looking at it as a string value, not a number.
Functions
Functions are instructions that can be used as many times as necessary. Some come
with the package, others you can define yourself.
An example would be the pow function. Instead of typing 2*2, or 2**2, we can use:
pow(2,2)
The first number is the actual number, the second is the power.
There are whole libraries of functions you can use. In order to do so, you have to import
them. This just involves the function “import” and the name of the library. We’ll use
math, so the command is: import math There is no response other than a new line. But
we can try using a math function, so let’s use:
Math.sqrt(81)
In graphical interfaces, you can type math.f(or g, or q, or whatever) and get a dropdown
list of the possible functions.
Other libraries include: base64, calendar, cmath, code, codecs, crypt, fractions,
functools, gzip, and macpath.
Saving scripts
Let’s type a simple script. Click “File - new” and a new window opens. We’ll type:
print(“hey there”)
and then save it as a .py file (File-save). The .py means it gets treated as a python
script.
Now we can go to “run” and the result (hey there) will appear in the main program
window.
Let’s close that window, then in the main window use File-Open and select it. It opens
in a new window.
If you just click on the saved .py file, it will open up in a Python window and execute,
then close. You can stop it from closing automatically by adding:
Input(“Press enter”)
Strings
A string is a set of characters that are together. For example, “hey there” is a string.
Now Python knows the apostrophe is part of the string. It’s basically telling Python to
ignore the following character if it would otherwise be interpreted as a control character.
Concatenate strings
To concatenate strings, we use the plus sign:
A = “first name “
B = “last name”
“he is “ + a won’t work, because you can’t mix strings and integers. To do this, we have
to convert the integer into a string. We use the “str” command for this:
a = str(18)
“he is ) +a
Notice you don’t put anything after the last item in the list. Also, there is a space after
each comma - without it, you will get an error. So if we put this into the shell, or a
program, it will now have that list. The items are numbered from zero, so lion would be
given the number 2. We’ll need this to pick it out of the list. If the next line says:
animals [2]
Oddly, you can also use a negative number. [-2] will also give the result of lion. Minus
counts from the right side, so tiger would be [-1].
Slicing or grouping
Say you have a lot of data in your list. Let’s use:
example= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, to get a subset, we can use: example [2:8] The result is:
2, 3, 4, 5, 6, 7
Notice it DOESN’T include 8, although it’s in the 8th place. If we use negative numbers,
such as: example [-5:-1], we get:
5, 6, 7, 8. We don’t get 9, which is place zero. You can’t have negative zero, so you
will not be able to use minus number with the last item in a list.
If we just use: example [:], we get the complete list. If you leave the first number blank:
example [ :5] or the last number blank: example [5: ], you get (respectively):
0, 1, 2, 3, 4 and 5, 6, 7, 8, 9
a + b gives the result [0, 1, 2, 3, 4, 5, 6, 7] However, you can’t combine strings with
sequences: a + “name” will give an error as a result.
Searching strings
If we use: name = “guatam” and then type:
‘k’ in name
the result with be false. But if we type ‘g’ in name, the result will be true.
Use the command “len” and it gives the number of elements in the list:
len(numbers)
Max, Min
“max” gives the maximum value within the list. So in numbers, max(numbers) would
give a result of 87.
“min” does the same, but for minimum. The result would be 21.
List
Using “list” breaks down a string. Typing list “guatam” would give the result:
Numbers [2] = 40
Now, when we type numbers the result is [21, 30, 40 (instead of 51), 87, etc.]
Now typing example will give each letter of simplebook. Let’s use the method we
learned already to replace book with mike:
example = list[6:] = []
example = example[::-1]
Methods
Methods are a certain type of function. It has to be related to an object to carry out its
function, as shown below:
example. Once you type “example.” a dropdown list opens up showing the methods
you can attach to it. We’ve already created the sequence “example” with three entries.
Let’s use the first option in the dropdown list, “append”. It now reads:
example.append (you can also just type append). Let’s add “random2” to the
sequence. Notice you use parenthesis, not brackets, after “append”:
example.append (‘random2’)
Let’s use a numbers example (note that they aren’t counted as actual numbers because
they’re part of a sequence which is treating them like a string):
numbers = [1, 1, 2, 2, 3, 3, 3, 4, 5]
numbers.count(1)
It gives the response of “2” because “1” occurs two times in the sequence.
Because it’s being treated like a string, we can concatenate the two by typing:
numbers = example + numbers
numbers.extend(example)
So methods are built in functions, but they need to be “tied” to an object that has been
defined.
The % operator is mostly to find the modulus of two integers. a % b returns the
remainder after dividing a by b. Unlike the modulus operators in some other
programming languages (such as C), in Python a modulus it will have the same sign as
b, rather than the same sign as a. The same operator is also used for the "old" style of
string formatting, so a % b can return a string if a is a format string and b is a value (or
tuple of values) which can be inserted into a.
In this case, the gobbledeegook above means the number is divided by 2. If there is no
remainder (“==0”), then it’s even. If there is a remainder, it’s an odd number.
Nested If Statement
In this case, we have more than one “else”:
item = "fruits"
fruit = "apple"
if item == "fruits":
if fruit == "apple":
print("this fruit is an apple")
else:
print("this fruit is not available")
else:
print("this is not a fruit")
If we run this, we’ll get the response “this fruit is an apple”. If we change item to
“animal”, we get “this is not a fruit”. If we change item back but change the definition of
fruit (to strawberry, for example) we get the result “this fruit is not available”.
a=1
while a<=10:
print(a)
a = a+1
This will result in a printout numbered (on separate lines) from 1 through 10.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).
This is less like the for keyword in other programming language, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Infinite Loops
This has no condition to stop it from running:
while True:
text = input("type something: ")
If you want to put in something that will break the loop, use :break
if(text == "quit"):break
Also notice the word True is capitalized, otherwise it will be considered a variable.
Comments
Use a hash for one line comments:
#this is a comment
Def simple():
Print(“I am a function”)
simple()
Let’s get a bit more complicated. We’ll use Great Britain Pound (gdp) and US Dollar
(usd). Let’s call the function gbp_to_usd. Let’s say it’s 1.5 dollars to the pound.
def gbp_to_usd():
usd = gbp*1.5
print(usd)
Parameters
Looks good, but how do we know how many pounds to convert? There’s no user input,
or definition of gbp. Here’s where the parameter come in. We place “gbp” in the
parenthesis. This tells python that, when we call that function, we’re going to put
something in the parenthesis that will be the value of gbp:
def gbp_to_usd(gbp):
usd = gbp*1.5
print(usd)
gbp_to_usd(5)
When saved and run, this gives us the result of 7.5
Return
We can store the value by using “return(usd)”. This will take the calculation
“usd=gbp*1.5 and store it. But we have to give it something to be stored to! So our
next line will be:
Usd = gbp_to_usd(5), followed by “print(usd)”. The result is the same as before, but
now the value (1.5) is stored in usd. We can revise the function with new parameters,
and still have the correct results:
def gbp_to_usd(gbp):
usd = gbp*1.5
return(usd)
usd = gbp_to_usd(5)
print(usd)
usd = gbp_to_usd(5.5)
print(usd)
usd = gbp_to_usd(10)
print(usd)
Multiple Parameters
If we type:
def printname(name):
print(name)
it will print out Russell. But we can’t type: printname(“Russell”, “Joe”) using the
definition we did. In order to use multiple parameters, we have to define the function as:
def printname(*name)
We can also define WHICH value will be used by adding parameters to the print
command:
def printname(*name):
print(name[0])
This will give an output of only the first name (the zero position).
print(name)
print(age)
printname(“Russell”, 60)
Note that we can only use one value per parameter. So printname(“Russell”, 60, “Joe”,
45) won’t work. It gives the error:
class calculator:
def add(a,b):
return a+b
In python, we have to reference the parent class with “self”. It’s just a method python
uses, other languages use different methods. Because we’re defining a class, and
putting options below it, we use “self” for each one. So the actual code is:
class calculator:
def add(self,a,b):
return a+b
def sub(self,a,b):
return a-b
When we define a function using the class (which we called “calculator”), we might do
something like:
calc = calculator
Now we can add the period and bring up the options we’ve defined:
calc. will bring up a choice of add and sub. It will do the same thing if we DON’T put
“self” in, but then we’ll get an error message when we try to run:
calc = calculator
calc.add (2,3)
If we include self:
def add(self,a,b):
it works. Notice there is a comma after self and no space before the parameter.
Extending Classes
Classes can reference other classes, not just variables:
class class1:
var1="i am a class1"
class class2:
var2="i am a class2"
Now, after saving this as “extended class.py” and running it, we get this response in the
main window:
example = class3()
example. brings up the selection of var1, var2, or var3. If, for example, we choose var1
and hit enter, we get the response:
I am a class1
This file is empty (I created a blank file), we can now write something into it:
This gives a response of 21, which is the number of bytes (actually, that’s the number of
characters, which seems to also be the number of bytes.)
Now we have to close the file (file.close) and open it again in read mode in order to read
it:
file.read(10)
file.read()
it will respond “first file”, because it picks up from where you left off - after the 10 th byte.
If we close and reopen the file and just type “file.read()”, it will show the whole line.
file.seek(0)
file.readline()
and it will read the first line. If we want to read everything, we use the command
“file.readlines()”. This will give us the lines with “\n” appended, like this:
[‘this is my first file\n’, ‘this is my second line\n’, ‘third line\n’, ‘fourth line\n’]
Editing data
He suggests taking the data and creating a list with it:
file.seek(0)
listdata = file.readlines()
Now we have a variable with those lines in it. Let’s edit it by typing:
We can now close the file, and open it in write mode, and that variable will still have
those original lines in it.
File.writelines(listdata)
And then closing the file. Note that we didn’t put “/n” into it, so now the third and fourth
line are concantenated: