Python Quick Revision

1.8. Getting Started with Data


In [1]:
print(2 ** 10)
print(2 ** 100)
print(7 // 3)
print(7 / 3)
print(7 % 3)


1024
1267650600228229401496703205376
2
2.3333333333333335
1

1.8.2. Built-in Collection Data Types

1. lists

Lists are heterogeneous, meaning that the data objects need not all be from the same class and the collection can be assigned to a variable as below.

Operation Name Operator Explanation
indexing [ ] Access an element of a sequence
concatenation + Combine sequences together
repetition * Concatenate a repeated number of times
membership in Ask whether an item is in a sequence
length len Ask the number of items in the sequence
slicing [ : ] Extract a part of a sequence

In [2]:
fakeList = ['str', 12, True, 1.232] # heterogeneous
print(fakeList)
myList = [1,2,3,4]
A = [myList] * 3
print(A)
myList[2]=45454545
print(A)


['str', 12, True, 1.232]
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
[[1, 2, 45454545, 4], [1, 2, 45454545, 4], [1, 2, 45454545, 4]]
Method Name Use Explanation
append alist.append(item) Adds a new item to the end of a list
insert alist.insert(i,item) Inserts an item at the ith position in a list
pop alist.pop() Removes and returns the last item in a list
pop alist.pop(i) Removes and returns the ith item in a list
sort alist.sort() Modifies a list to be sorted
reverse alist.reverse() Modifies a list to be in reverse order
del del alist[i] Deletes the item in the ith position
index alist.index(item) Returns the index of the first occurrence of item
count alist.count(item) Returns the number of occurrences of item
remove alist.remove(item) Removes the first occurrence of item

In [3]:
myList = [1024, 3, True, 6.5]
myList.append(False)
print(myList)
myList.insert(2,4.5)
print(myList)
print(myList.pop())
print(myList)
print(myList.pop(1))
print(myList)
myList.pop(2)
print(myList)
myList.sort()
print(myList)
myList.reverse()
print(myList)
print(myList.count(6.5))
print(myList.index(4.5))
myList.remove(6.5)
print(myList)
del myList[0]
print(myList)


[1024, 3, True, 6.5, False]
[1024, 3, 4.5, True, 6.5, False]
False
[1024, 3, 4.5, True, 6.5]
3
[1024, 4.5, True, 6.5]
[1024, 4.5, 6.5]
[4.5, 6.5, 1024]
[1024, 6.5, 4.5]
1
2
[1024, 4.5]
[4.5]

In [4]:
print(list(range(10)))
print(list(range(5,10)))
print(list(range(5,10,2)))
print(list(range(10,1,-1)))


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[5, 7, 9]
[10, 9, 8, 7, 6, 5, 4, 3, 2]

2. Strings

Method Name Use Explanation
center astring.center(w) Returns a string centered in a field of size w
count astring.count(item) Returns the number of occurrences of item in the string
ljust astring.ljust(w) Returns a string left-justified in a field of size w
lower astring.lower() Returns a string in all lowercase
rjust astring.rjust(w) Returns a string right-justified in a field of size w
find astring.find(item) Returns the index of the first occurrence of item
split astring.split(schar) Splits a string into substrings at schar

In [5]:
myName= "David"
print(myName[3])
print(myName * 2)
print(len(myName))
print(myName.upper())
print('.' + myName.center(10) + '.')
print('.' + myName.ljust(10) + '.')
print('.' + myName.rjust(10) + '.')
print(myName.find('v'))
print(myName.split('v'))


i
DavidDavid
5
DAVID
.  David   .
.David     .
.     David.
2
['Da', 'id']

A major difference between lists and strings is that lists can be modified while strings cannot. This is referred to as mutability. Lists are mutable; strings are immutable. For example, you can change an item in a list by using indexing and assignment. With a string that change is not allowed.

3. Tuples

Tuples are very similar to lists in that they are heterogeneous sequences of data. The difference is that a tuple is immutable, like a string. A tuple cannot be changed.


In [6]:
myTuple = (2,True,4.96)
print(myTuple)
print(len(myTuple))


(2, True, 4.96)
3

However, if you try to change an item in a tuple, you will get an error. Note that the error message provides location and reason for the problem.


In [7]:
myTuple[1]=False


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-85d8da7d0711> in <module>()
----> 1 myTuple[1]=False

TypeError: 'tuple' object does not support item assignment

4. Set

A set is an unordered collection of zero or more immutable Python data objects. Sets do not allow duplicates and are written as comma-delimited values enclosed in curly braces. The empty set is represented by set(). Sets are heterogeneous, and the collection can be assigned to a variable as below.


In [8]:
print({3,6,"cat",4.5,False})
mySet = {3,6,"cat",4.5,False}
print(mySet)


{False, 3, 4.5, 6, 'cat'}
{False, 3, 4.5, 6, 'cat'}
Operation Name Operator Explanation
membership in Set membership
length len Returns the cardinality of the set
| aset | otherset Returns a new set with all elements from both sets
& aset & otherset Returns a new set with only those elements common to both sets
- aset - otherset Returns a new set with all items from the first set not in second
<= aset <= otherset Asks whether all elements of the first set are in the second
Method Name Use Explanation
union aset.union(otherset) Returns a new set with all elements from both sets
intersection aset.intersection(otherset) Returns a new set with only those elements common to both sets
difference aset.difference(otherset) Returns a new set with all items from first set not in second
issubset aset.issubset(otherset) Asks whether all elements of one set are in the other
add aset.add(item) Adds item to the set
remove aset.remove(item) Removes item from the set
pop aset.pop() Removes an arbitrary element from the set
clear aset.clear() Removes all elements from the set

In [9]:
mySet = {3,6,"cat",4.5,False}
print(mySet)
yourSet = {99,3,100}
print(yourSet)

print( mySet.union(yourSet))
print( mySet | yourSet)

print( mySet.intersection(yourSet))
print( mySet & yourSet)

print( mySet.difference(yourSet))
print( mySet - yourSet)

print( {3,100}.issubset(yourSet))
print( {3,100}<=yourSet)

mySet.add("house")
print( mySet)

mySet.remove(4.5)
print( mySet)

mySet.pop()
print( mySet)

mySet.clear()
print( mySet)


{False, 3, 4.5, 6, 'cat'}
{3, 99, 100}
{False, 3, 4.5, 99, 6, 100, 'cat'}
{False, 3, 4.5, 99, 6, 100, 'cat'}
{3}
{3}
{False, 'cat', 4.5, 6}
{False, 'cat', 4.5, 6}
True
True
{False, 3, 4.5, 6, 'house', 'cat'}
{False, 3, 6, 'house', 'cat'}
{3, 6, 'house', 'cat'}
set()

5. Dictionary

Dictionaries are collections of associated pairs of items where each pair consists of a key and a value. This key-value pair is typically written as key:value. Dictionaries are written as comma-delimited key:value pairs enclosed in curly braces. For example,


In [10]:
capitals = {'Iowa':'DesMoines','Wisconsin':'Madison'}
print(capitals)
print(capitals['Iowa'])
capitals['Utah']='SaltLakeCity'
print(capitals)
capitals['California']='Sacramento'
print(len(capitals))
for k in capitals:
   print(capitals[k]," is the capital of ", k)


{'Iowa': 'DesMoines', 'Wisconsin': 'Madison'}
DesMoines
{'Iowa': 'DesMoines', 'Wisconsin': 'Madison', 'Utah': 'SaltLakeCity'}
4
DesMoines  is the capital of  Iowa
Madison  is the capital of  Wisconsin
SaltLakeCity  is the capital of  Utah
Sacramento  is the capital of  California
Operator Use Explanation
[] myDict[k] Returns the value associated with k, otherwise its an error
in key in adict Returns True if key is in the dictionary, False otherwise
del del adict[key] Removes the entry from the dictionary
Method Name Use Explanation
keys adict.keys() Returns the keys of the dictionary in a dict_keys object
values adict.values() Returns the values of the dictionary in a dict_values object
items adict.items() Returns the key-value pairs in a dict_items object
get adict.get(k) Returns the value associated with k, None otherwise
get adict.get(k,alt) Returns the value associated with k, alt otherwise

In [11]:
phoneext={'david':1410,'brad':1137}
print(phoneext)
print(phoneext.keys())
print(list(phoneext.keys()))
print(phoneext.values())
print(list(phoneext.values()))
print(phoneext.items())
print(list(phoneext.items()))
print(phoneext.get("kent"))
print(phoneext.get("kent","NO ENTRY"))


{'david': 1410, 'brad': 1137}
dict_keys(['david', 'brad'])
['david', 'brad']
dict_values([1410, 1137])
[1410, 1137]
dict_items([('david', 1410), ('brad', 1137)])
[('david', 1410), ('brad', 1137)]
None
NO ENTRY

1.9. Input and Output


In [12]:
aName = input("Please enter your name ")
print("Your name in all capitals is",aName.upper(),
      "and has length", len(aName))


Please enter your name 
Your name in all capitals is  and has length 0

In [13]:
sradius = input("Please enter the radius of the circle ")
radius = float(sradius)
diameter = 2 * radius
print(diameter)


Please enter the radius of the circle 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-21781b49943e> in <module>()
      1 sradius = input("Please enter the radius of the circle ")
----> 2 radius = float(sradius)
      3 diameter = 2 * radius
      4 print(diameter)

ValueError: could not convert string to float: 

1.9.1. String Formatting


In [14]:
print("Hello","World")
print("Hello","World", sep="***")
print("Hello","World", end="***")


Hello World
Hello***World
Hello World***

In [15]:
aName = "Anas"
age = 10
print(aName, "is", age, "years old.")
print("%s is %d years old." % (aName, age)) 
# The % operator is a string operator called the format operator.


Anas is 10 years old.
Anas is 10 years old.
Character Output Format
d, i Integer
u Unsigned integer
f Floating point as m.ddddd
e Floating point as m.ddddde+/-xx
E Floating point as m.dddddE+/-xx
g Use %e for exponents less than
c Single character
s String, or any Python data object that can be converted to a string by using the str function.
% Insert a literal % character
Modifier Example Description
number %20d Put the value in a field width of 20
- %-20d Put the value in a field 20 characters wide, left-justified
+ %+20d Put the value in a field 20 characters wide, right-justified
0 %020d Put the value in a field 20 characters wide, fill in with leading zeros.
. %20.2f Put the value in a field 20 characters wide with 2 characters to the right of the decimal point.
(name) %(name)d Get the value from the supplied dictionary using name as the key.

In [16]:
price = 24
item = "banana"
print("The %s costs %d cents" % (item, price))
print("The %+10s costs %5.2f cents" % (item, price))
print("The %+10s costs %10.2f cents" % (item, price))
print("The %+10s costs %010.2f cents" % (item, price))
itemdict = {"item":"banana","cost":24}
print("The %(item)s costs %(cost)7.1f cents" % itemdict)


The banana costs 24 cents
The     banana costs 24.00 cents
The     banana costs      24.00 cents
The     banana costs 0000024.00 cents
The banana costs    24.0 cents

1.10. Control Structures

algorithms require two important control structures: iteration and selection.

- Iteration

1. While


In [17]:
counter = 1
while counter <= 5:
   print("Hello, world")
   counter = counter + 1


Hello, world
Hello, world
Hello, world
Hello, world
Hello, world

2. for


In [18]:
for item in [1,3,6,2,5]:
    print(item)


1
3
6
2
5

In [19]:
for item in range(5):
...    print(item**2)


0
1
4
9
16

In [20]:
wordlist = ['cat','dog','rabbit']
letterlist = [ ]
for aword in wordlist:
    for aletter in aword:
        if(aletter not in letterlist):
            letterlist.append(aletter)
print(letterlist)


['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

list comprehension


In [21]:
sqlist=[]
for x in range(1,11):
         sqlist.append(x*x)
print(sqlist)        

sqlist2=[x*x for x in range(1,11)] # list comprehension
print(sqlist2)


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In [22]:
sqlist=[x*x for x in range(1,11) if x%2 != 0]
print(sqlist)


[1, 9, 25, 49, 81]

In [23]:
[ch.upper() for ch in 'comprehension' if ch not in 'aeiou']


Out[23]:
['C', 'M', 'P', 'R', 'H', 'N', 'S', 'N']

In [24]:
wordlist = ['cat','dog','rabbit']

uniqueLetters = [letter for word in wordlist for letter in word]
print(uniqueLetters)


['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

1.12. Defining Functions

problem

Here’s a self check that really covers everything so far.

You may have heard of the infinite monkey theorem?

The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare.

Well, suppose we replace a monkey with a Python function. How long do you think it would take for a Python function to generate just one sentence of Shakespeare? The sentence we’ll shoot for is: “methinks it is like a weasel”

You’re not going to want to run this one in the browser, so fire up your favorite Python IDE. The way we’ll simulate this is to write a function that generates a string that is 27 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal.

A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string.To make it easier to follow your program’s progress this third function should print out the best string generated so far and its score every 1000 tries.


In [25]:
import string
import random
import time

start_time = time.time()

def generate_new_sentense():
    sentense = [random.choice(string.ascii_lowercase + " ") for x in range(28) ]
    return "".join(sentense)

def compare_sentences(guess):
    target_sentence = "methinks it is like a weasel"
    return guess == target_sentence

def main():
    i= 0
    print (i)
    guess = generate_new_sentense()
    print (guess)
    while not compare_sentences(guess):
        guess = generate_new_sentense()
        print (guess)
        i+= 1
        print (i)
# main()

print("--- %s seconds ---" % (time.time() - start_time))


--- 0.0005996227264404297 seconds ---

1.13. Object-Oriented Programming in Python: Defining Classes

1.13.1. A Fraction Class


In [26]:
class Fraction:
    
    def __init__(self, top, bottom):
        self.num = top
        self.den = bottom

    def show(self):
     print(self.num,"/",self.den)
    
    # Overriding the default __str__ function
    def __str__(self):
        return str(self.num)+"/"+str(self.den)
    
    def __add__(self,otherfraction):
     newnum = self.num * otherfraction.den + self.den * otherfraction.num
     newden = self.den * otherfraction.den
     return Fraction(newnum,newden)
        
myfraction = Fraction(3,5)
print(myfraction)
print(myfraction.show())
f1 = Fraction(1,4)
f2 = Fraction(1,2)
f3 = f1 + f2
print(f3)


3/5
3 / 5
None
6/8

In [ ]: