Python 101 notes
False, class, return , is, finally, None, if, for , lambda, continue, True, def, from, while, nonlocal, and, del, global, not, with, as, elif, try , or, yield, assert, else, import, pass, break, except, in, raise
x = 2
print(x)
=2
x = x + 2
print(x)
=2
x = 5
if x < 10;
print('Smaller')
if x > 20;
print('Bigger')
Print('Finis')
=Smaller
=Finis
n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
=5
=4
=3
=2
=1
=Blastoff!
A named place in memory where a program can store data and later retrieve the data using the variable "name" You can change the contents of a variable in a later statement. You must start with a letter or underscore. But underscore mainly used when communicating with python itself.
Constants are fixed values, aka their values do not change
Python follow left to right: Parenthesis -> Power -> Multiplication/Divsion -> Addition/Subtraction
- Addition
- Subtraction
- Multiplication / Division ** Power % Remainder
You cannot add different types together You can check type like this
x = 1
y = 92.3
type(x)
=<class 'int'>
type(y)
=<class 'float'>
When you put an integer and floating point in an expression, the integer is implicitly converted to a float. You can control it with int() and float()
x = 1
y = float(x)
print(y)
=1.0
type(y)
=<class 'float'>
Integer division produces a floating point result
print(10/2)
=5.0
Python can pause and read data from the user using the input() function input() returns a string
yourName = input('Who are you?')
print('Welcome' , yourName)
The , represents a space in python.
Python ignores anything after the # sign and treat it as comments
<
<=
==
>=
>
!=
x = 5
print('Before 5')
if x == 5 :
print('Is 5')
print('Is Still 5')
print('Third 5')
print('afterwards 5')
print('Before 6')
if x == 6 :
print('is 6')
print('is still 6')
print('third 6')
print('afterward 6')
x = 40
if x > 1 :
print('more than one')
if x < 100 :
print('less than 100')
print('All done')
x = 4
if x > 2 :
print('Bigger')
else :
print('Smaller')
print "All done'
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
to compensate for errors
astr = 'Bob'
try:
print('Hello')
istr = int(astr)
print('there')
except:
istr = -1
print('Done', istr)
Two kinds of functions. Built in functions and functions we define ourselves. Function is reuseable code that takes arguments as inputs, does some computation, and returns something.
big = max('Hello world')
print(big)
=w
tiny = min('Hello world')
print(tiny)
=
A variable which we use in the function definition. It is a handle that allows the code in the function to access the arguments for a particular function invocation.
Often a function will take its arguments, do some computations and returns a value to be used as the value of the function in the calling expressio. The return keyword is used for this.
n = 5
while n > 0 :
print(n)
n = n - 1
print('blastoff!')
print(n)
n = 5
while n > 0 :
print('lather')
print('rinse')
print('dry off!')
while True:
line = input('> ')
if line === 'done' :
break
print(line)
print('done!')
while True:
line = input('> ')
if line[0] === '#' :
continue
if line === 'done' :
break
print(line)
print('done!')
Looping of a finite set of things
for i in [5, 4, 3, 2, 1] :
print(i)
print('done')
definite loop with strings
friends = ['joseph', 'jane', 'jessica']
for friend in friends :
print('Happy New Year: ', friend)
print('done')
for thing in [5, 4, 3, 2, 1] :
print(thing)
print('done')
We make a variable that contains the current largest vvalue. If the number we are looking at is larger, it is the new largest value.
largest_so_far = -1
print('Before', largest_so_far)
for the_num in (9, 41, 12, 3, 74, 15] :
if the_num > largest_so_far :
largest_so_far = the_num
print(largest_so_far, the_num)
print('After', largest_so_far)
To Count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one t oit each time through the loop.
zork = 0
print ('Before', zork)
for i in [5, 4, 3, 2, 1] :
zork = zork + 1
print(zork, i)
print('done', zork)
To add up a value we encounter in a loop, we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop
zork = 0
print ('Before', zork)
for i in [5, 4, 3, 2, 1] :
zork = zork + i
print(zork, i)
print('done', zork)
An average combines the counting and sum patterns and divides when the loop is done.
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15] :
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum / count)
We use an if statement in the loop to catch / filter the values we are looking for
print('Before')
for value in [9, 41, 12, 3, 74, 15] :
if value > 20:
print('Large number', value)
print('After')
If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for.
found = False
print('Before', found)
for value in [9, 41, 12, 3, 74, 15] :
if value == 3 :
found = True
print(found, value)
print('After', found)
smallest_so_far = 78
print('Before', smallest_so_far)
for the_num in (9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far, the_num)
print('After', smallest_so_far)
The first time we loop through smallest is None, so we take the first value to be the smallest.(9)
smallest_so_far = None
print('Before')
for value in (9, 41, 12, 3, 74, 15] :
if smallest is None :
smallest = value
elif value < smallest :
print(smallest, value)
print('After')
A string is a sequence of characters A string literal uses quotes like 'hi or "hi" For strings + means concatenate We can convert numbers in a string into a number using int()
We can get any single character in a string using an index specified in square brackets.
fruit = 'banana'
letter = fruit[0]
print(letter)
=b
fruit = 'banana'
print(len(letter))
=6
While Loop
fruit = 'banana'
index = 0
while index < len(fruit) :
letter = fruit[index]
print(index,letter)
index = index + 1
For Loop
fruit = 'banana'
for letter in fruit:
print(letter)
Simple loop that loops through each letter in a string and counts the number of times the loop encounters the 'a' character.
word = 'banana'
count = 0
for letter in word:
if letter == 'a' :
count = count + 1
print(count)
s = 'Monty Python'
print(s[0:4])
=Mont
print(s[6:7])
=P
print(s[6:20])
=Python
print(s[:2])
=Mo
print(s[8:])
=thon
print(s[:])
=Monty Python
a = 'Hello'
b = a + "There'
print(b)
=HelloThere
The in keyword can also be used to check to see if one string is "in" another string
fruit = 'banana'
'n' in fruit
=True
'm' in fruit
=False
'nan' in fruit
=True
Pythong has a number of string functions which are in the string library These functions are already built into every string We do not modify the original string, instead we return a new string that has been altered
greet = 'Hello Bob'
zap = greet.lower()
print(zap)
=hello bob
fruit = 'banana'
pos = fruit.find('na')
print(pos)
=2
greet = 'Hello Bob'
nn = greet.upper()
print(nn)
=HELLO BOB
greet = 'Hello Bob'
nstr = greet.replace('Bob', 'Jane')
print(nstr)
=Hello Jane
greet = ' Hello Bob '
greet.lstrip()
='Hello Bob '
greet.rstrip()
='. Hello Bob'
greet.strip()
='Hello Bob'
From justin@gmail.com Tue July 14 8:04:30:30 2020
data = 'From justin@gmail.com Tue July 14 8:04:30:30 2020'
atpos = data.find('@')
print(atpos)
=11
sppos = data.find(' ',atpos)
print(sppos)
=21
host = data[atpos+1 : sspos]
print(host)
gmail.com
Before we can read the contents of a file we tell python which file and what we are doing with the file. open() function handle = open(filename,mode) returns a handle use to manipulate the file filename is a string mode is optional and should be 'r' if we are planning to read the file and 'w' if we are going to write to the file
fhand = open('mbox.txt')
print(fhand)
<_io.TextIOWrapper name='mbox.txt' mode='r' encoding='UTF=8'>
\n
stuff = 'Hello\nWorld!'
print(stuff)
=Hello
=World!
xfile = open('mbox.txt')
for cheese in xfile:
print(cheese)
Open a file read-only Use a for loop to read each line Count the lines and print out the number of lines
fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)
python open.py
=Line Count: 132045
Read the whole file into a single string
fhand = open('mbox.txt')
inp = fhand.read()
print(len(inp))
=94626
print(inp[:20])
From justin.kim@gma
fhand = open('mbox.txt')
for line in fhand:
if line.startswith('From:') :
print(line)
fhand = open('mbox.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From:') :
continue
print(line)
We can look for a string anywhere in a line as our selection criteria
fhand = open('mbox.txt')
for line in fhand:
line = line.rstrip()
if not '@uct.ac.za' in line:
continue
print(line)
fname = input('Enter file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print("there were", count, "subject lines in", fname)
fname = input('Enter file name: ')
try:
fhand = open(fname)
except:
print('file cannot be opened:', fname)
quit()
count = 0
for line in fhand:
if line.startswith('Subject:') :
count = count + 1
print("there were", count, "subject lines in", fname)
friends = ['joseph', 'max', 'sam']
friends = ['joseph', 'max', 'sam']
for friends in friends:
print('Happy new year:', friend)
print('done!')
friends = ['joseph', 'max', 'sam']
friends[0]
=joseph
you can change the values, unlike strings.
friends = ['joseph', 'max', 'sam']
print(len(friends))
=3
print(range4))
=[0, 1, 2, 3]
friends = ['joseph', 'max', 'sam']
print(len(friends))
=3
print(range(len(friends)))
=[0, 1, 2]
a = [1, 2, 3]
b = [5, 6, 7]
c = a + b
print(c)
= [1,2,3,5,6,7]
t = [1, 2 ,3 ,4, 5, 6]
t[1:3]
= [2, 3]
stuff = list()
stuff.append('book')
stuff.append(99)
print(stuff)
=['book', 99]
some = [1, 9, 21, 10]
9 in some
=True
15 in some
=False
20 not in some
=True
friends = ['joseph', 'max', 'sam']
friends.sort()
print(friends)
=['joseph', 'max', 'sam']
nums = [3, 41, 12, 9, 74, 15]
print(len(nums))
=6
print(max(nums))
=74
print(min(nums))
=3
print(sum(nums))
=154
print(sum(nums)/len(nums))
=25.6
abc = 'With three words'
stuff = abc.split()
print(stuff)
=['With', 'three', 'words']
line = A lot of spaces'
etc = line.split()
print(etc)
=['A', 'lot', 'of, 'spaces']
line = 'first;second;third'
thing = line.split()
print(thing)
=['first;second;third']
thing = line.split(';')
print(thing)
=['first', 'second', 'third']
print(len(thing))
3
They are the Objects of Javascript They use keys: values instead of number/values
Use curl braces and have a list of key:value pairs
jjj = {'chuck' : 1, 'fred' : 42, 'jan': 100}
print(jjj)
={'jan': 100, 'chuck': 1, 'fred': 42}
You can make an empty dictionary using empty curly braces
print(ooo)
{}
One common use of dictionaries is counting how often we "see" something
ccc = dict()
ccc['csev'] = 1
ccc['cwen'] = 1
if name in counts:
x = counts[name]
else :
x = 0
x = counts.get(name, 0)
The general pattern to count the words in a line of text is to split the line into words, then loop through the words and use a dictionary to track the count of each word independently.
counts = dict()
print('Enter a line of text:')
line = input('')
words = line.split()
print('Words:', words)
print('Counting...')
for word in words:
count[word] = counts.get(word,0) + 1
print('Counts', counts)
jjj = {'chuck':1, 'fred':42, 'jan':100}
print(jjj.keys())
=['jan', 'chuck', 'fred']
print(jjj.values())
=[100,1,42]
or try
jjj = {'chuck':1, 'fred':42, 'jan':100}
for aaa,bbb in jjj.items() :
print(aaa,bbb)
Tuples are immutable, more efficient,
z = (5, 4, 3)
z[2] = 0
= tuple does not support item assignement
(x, y) = (4, 'fred')
Special characters used in python for matching strings of text