Notes On Python Course

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Installation...................................................................................................................................................

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:

X = int(input(“Enter the number: “)

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)

This gives us the result of 9.0

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.

Let’s improve it:

Name = input(“enter name: “)

print (“Hey there “+name)


and now run it. It will run in the main window. Notice that you have to put the space in
the part within the quotes. You can also run it by hitting F5.

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”)

It won’t close until you press enter.

Strings
A string is a set of characters that are together. For example, “hey there” is a string.

Ignoring Control characters


However, there are some characters that you can’t use in a string. “He’s a good fellow”
has the apostrophe, which messes it up. So we use the back slash:

“He\’s a good fellow”

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”

A + B gives the result first name last name

Concatenate strings and integers


a = 18

“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

The result is: “he is 18”


Sequences and Lists
Lists are similar to arrays in Javascript. We define a name, and then in a bracket (which
is the same in Javascript) we list the members of that list:

animals = [“dog”, “cat”, ”lion”, ”tiger”]

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]

the result will be lion.

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

Sequences can be concatenated. a = [0, 1, 2, 3] b = [4, 5, 6, 7]

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.

Other functions in Python for sequences and lists


Len
Let’s type:

Numbers = [21, 30, 51, 87, 65, 40]

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:

[‘g’, ‘u’, ‘a’, ‘t’, ‘a’, ‘m’]

Replacing a value in a list


We can replace a number in a list by specifying the place of the number we wish to
change, and the new value:

Numbers [2] = 40

Now, when we type numbers the result is [21, 30, 40 (instead of 51), 87, etc.]

Example of using the above commands


Let’s use the following:

example = list (“simplebook”) - note we use parenthesis, not brackets.

Now typing example will give each letter of simplebook. Let’s use the method we
learned already to replace book with mike:

example [6:] = list(“mike”)

Now, if we type example, it gives each letter of simplemike.


Even if the replacement word is longer (like “balloon” instead of “mike”), it will still work.

If we wanted to delete “mike”, we can just use empty brackets:

example = list[6:] = []

Notice we aren’t using “= list()”, just “= []”

If we wanted to reverse it, we can type:

example = example[::-1]

This results in: [‘e’, ‘l’, ‘p’, ‘m’, ‘i’, ‘s’]

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 = [‘computer’, ‘random’, ‘keyboard’]

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’)

Now, when we type: example

We get the response: [‘computer’, ‘random’, ‘keyboard’, ‘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]

Now let’s use “numbers.count”:

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

Now if we type “numbers” we get the result:

['computer', 'random', 'keyboard', 'random2', 1, 1, 2, 2, 3, 3, 3, 4, 5]

We can also do it by using “numbers.extend”. In this case, we’ve already concatenated


it, so we’ll extend it by adding “example” again at the end:

numbers.extend(example)

So methods are built in functions, but they need to be “tied” to an object that has been
defined.

Various Programming Statements


If and Else Statement
First we define a variable (n = something). Next we make a condition where if that
variable meets it, you get one response. If not, you get a different response:

number = int(input("Enter the number:"))


if number%2==0:
print("The number is even")
else:
print("The number is odd")

input("Press enter to exit.")

The definition of “%” is:

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”.

While and For Loops


We can use while loops to have something happen until it reaches a certain condition:

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.

example = ["book", "pen", "water", "notebooks"]


for item in example:
print("I have "+item)

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

Use “”” for multiline comments


””” This would be a multiline comment
in Python that spans several lines and
describes your code, your day, or anything you want it to

“””

User Defined Functions


To create a function, we use the def command:

Def simple():

Print(“I am a function”)

To use that function, just call the function:

simple()

When saved and run, it prints out “I am a function”.

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)

The results will be 7.5, 8.25, and 15, respectively.

Multiple Parameters
If we type:

def printname(name):
print(name)

and then run: printname(“Russell”)

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)

*name now becomes a pointer for the list of names we create:

printname(“Russell”, “Joe”, “Pete”, “Fred”)

Now it will print out all of them.

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).

We can also define specific multiple parameters:

def printname(name, age):

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:

Traceback (most recent call last):


File "<pyshell#14>", line 1, in <module>
printname("Russell", 60, "Joe", 30)
TypeError: printname() takes 2 positional arguments but 4 were given

Class, Object, and Methods


Defining a class
First, we give the class a name. We’ll call it calculator:

class calculator:

Next, we define functions as we’ve done before:

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)

Traceback (most recent call last):


File "<pyshell#21>", line 1, in <module>
calc.add(2,3)
TypeError: add() takes 2 positional arguments but 3 were given

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"

class class3(class1, class2):


var3="i am class3"

Now, after saving this as “extended class.py” and running it, we get this response in the
main window:

RESTART: C:/Users/Russ/Desktop/Python course/class extended.py

We can now create an object:

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

Reading And Writing Into A File


We start by writing the object name - in this case, “file”. Then an equal sign, then
“open” which has two parameters: the full path and name of the file, and is the mode we
want to open it in (read, write).

file = open(‘g:/test.txt’, ‘w’)

This file is empty (I created a blank file), we can now write something into it:

file.write(“this is my first file”)

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 = open(‘g:/test.txt’, ‘r’)

Now we can read, and set parameters:

file.read(10)

which gives the response “this is my”

If you then type:

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.

Moving around the file


Once we read or write, the pointer is at the end of the line. To move it back to the
beginning of the file we type:

file.seek(0)

This is the first byte of the file. Now, we can type:

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:

Listdata[2] = “third line edited”

We can now close the file, and open it in write mode, and that variable will still have
those original lines in it.

We can then write that variable into the file by typing:

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:

third line editedFourth line

I fixed this by typing the following:

>>> file = open('c:/Users/Russ/Desktop/Python course/test.txt', 'w')


>>> listdata[2] = "third line edited 2\n"
>>> listdata[3] = "fourth line fixed\n"
>>> listdata
['This is my first file\n', 'This is my second line\n', 'third line edited 2\n', 'fourth line fixed\
n']
>>> file.writelines(listdata)
>>> file.close()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy