Strings

Uitvoer met print functie:resultaat
uitvoer met regelovergang:print(¨Hello world!")
uitvoer zonder regelovergang:print("Hello world!", end="")
scheider , is spatie in uitvoer:print("2 x 2 is", 2*2)
geen scheider:print("2 x 2 is ", 2*2, sep="")
extra regelovergang:print("regel 1\nregel 2")
lege regel: print()

Strings (tekst)resultaat
genoteerd tussen quotes:"hallo", 'hallo'
vrije keuze, dus kies handig:"kom 's morgens!"
'met " dubbele quote'
met escape codes:"string met \\, \t, \n en \""
'C:\\temp\\newfile.txt'
raw string maakt \ letterlijk:r'drie \\\ backslashes'
r"C:\temp]\newfile.txt"
drievoudig quotes bij regelovergang: """een string over
meerdere regels"""
'''en nog eentje maar
dan enkele quotes'''

Strings maken
a = 'parkeer'
b = 'bon'
c = """complexe
string"""

Strings en operatoren
boete = a + b# parkeerbon
lekker = b * 2# lekker wordt 'bonbon'

0123456789
boetep arkeerbon
-10-9-8-7-6-5-4-3-2-1

Indexeren en slice nemen
derde = boete[2]# derde wordt 'r'
recht = boete[-1]# rechts wordt 'n'
maal = boete[3:7]# maal wordt 'keer' -> slice
voor = boete[0:5:2]# van 0 - 5 elk 2e element: 'pre'
invers = boete[::-1]# invers wordt 'nobreekrap'
String lengte
lengte = len(boete)# lengte wordt 1
lengte = len(c)# lengte wordt 15

Strings test
if "on" in lekker:# lekker bevat 'bonbon', dus True
print('on')
if "en" in lekker# lekker bevat 'bonbon', dus False
print('en')
if "mies" < "wim":# True (lexicografisch, qua sortering)
print('mies is kleiner')

String is geen getal
a = "123"
x = a * 3# x wordt '123123123'
x = a + 3# Exception! Geen + voor string en int
b = 123
x = b * 3# x wordt 369
Conversie
a = "123"
b = int(a) + 3# b wordt 126
c = str(b) * 3# c wordt '126126126'

str(42) # "42"
int("42")# 42
int("42", 8)# 34
int("42", 16)# 66
float("1.52")# 1.52
chr(65) # 'A'
ord('A')# 65
list('bon')# ['b', 'o', 'n']
tuple('bon')# ('b', 'o', 'n')
dict([('bon', 3), ('hoi', 7)]) # {'bon':3, 'hoi':7}

Lijst met mogelijke escape sequences:
EscapeBetekenis
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (TAB)
\oooTeken met octale waarde ooo
\xhhTeken met hexadecimale waarde hh

Variabelen met meerdere elementen

List, [13, 71, 22, 15, 37, 12]
elementen zijn te wijzigen, te verwijderen en toe te voegen
aanduiding element met volgnummer, beginnen bij 0

print(neerslag[1])# toont 71
n = len(neerslag)# n wordt 6
neerslag[1] = 57# wijzig tweede element
print(neerslag[1])# toont 57
tot = sum(neerslag)# tot wordt 156

tuple, (13, 71, 22, 15, 37, 12)
elementen zijn niet te wijzigen en niet te verwijderen en niet toe te voegen
aanduiding elementen met volgnummer, beginnend bij 0

print(neerslag[1])# toont 71
n = len(neerslag)# n wordt 6
tot = sum(neerslag)# tot wordt 170
neerslag[1] = 57exception: wijzigen mag niet

dictionary, {'jan':13, 'feb':71, 'maa':22, 'apr':15, 'mei':37, 'jun':12}
elementen zijn te wijzigen, te verwijderen en toe te voegen
aanduiding element met 'sleutel'/key

print(neerslag['feb'])# toont 71
n = len(neerslag)# n wordt 6
neerslag]['feb'] = 57# wijzig element 'feb'
print(neerslag['feb'])# toont 57
neerslag['jun'] = 66# voeg element 'jul' toe
print(neerslag)# toont gehele dictionary met
# elementen in willkeurige volgorde:

Basis data-types

Soort Voorbeeld Eigenschap
numbers3.1415 1234 99999999 3+4jimmutable
text(string)'Ni' 'Met"quote' "guido's"immutable
Data (bytes)b'Hallo' b"Hallo"immutable
Lists[1, 2, 'Piet', 4]mutable
Tuples(1, 2, 'ABC', 4 'U')immutable
Dictionaries{'jan':42, 'Marie':38}mutable
Setsset([2, 3, 5, 7]) geen dubbelenmutable
BooleansFalse, Trueimmutable
NoneTypeNone geeft bewust aan: nu geen waarde

Blockstructuren in Python

print('we hebben nu ', end='')
if temperatuur >= 0:
print('dooi')
else:
print('vorst')
print('dus komt naar buiten!')

Indentatie is enige aanwijzing (ook voor compiler)
Gebruik 4 spaties voor indentatie (liever geen TABS)

Conditionele uitvoerig
if conditie:if conditie:if conditie:
statementstatementstatement
else condition:elif condition:
statementstatement
elif condition:
statement
else:
statement

Conditionele herhaling

bijv.

Indexering met while

Herhaling met het for statement

bijv.

Functie range():

genereer reeks getallen mogelijke aanroepen
range(10)getallen van 0 t/m 9
range(1, 11)getallen van 1 t/m 10
range(3, 20, 5)getallen van 3 t/m 19 in stappen van 5 (dus 3 8 13 18)
range(5, 0, -1)getallen 5, 4, 3, 2, 1

Functie enumerate():

genereer elementnummers bij iedere waarde

Exception afvangen

In eigen code exception forceren

break

repetities kunnen vroegtijdig worden onderbroken met break

continue

vroegtijdig continueren kan met continue

pass

op sommige plaatsen is een statement verplicht, terwijl er niets te doen valt....
dummy statement pass

Variabelen nemen dynamisch type aan

a = "hallo daar"# a is nu string
a = 4# a is nu integer
a = [1,2,3]# a is nu list
a = {'aap',: 4}# a is nu dictionary
a = (4,13,7)# a is nu tuple
Maar actie moet wel bij dat type passen
a = 6# a is an integer
b = [4]Traceback (most recent call last): File "", line 1, in ? TypeError: unsubsciptable object
a = "hallo daar"# a is a string
a = a+7Traceback (most recent call last): File "", line 1, in ? TypeError: cannot concatenate 'str' and 'int' object
type() Om te verifieren of twee variabelen van het zelfde type zijn
isinstance() Om te checken of een variabele van een gegeven type is
a = 'blurp'
b = 7
c = 352
if type(a) == type(b):# levert False
   .....
if type(b) == type(c):# levert True
   .....
if isinstance(a,str):# levert True
   .....
if isinstance(a,int):# levert False
   .....

Toekenning bindt naam aan object

a = 7# a gebonden aan int(7)
a = [1,2,3]# 7 nu weg
a = 3# lijst nu weg
b = [1,2,3]# b is lijst
c = b# c is dezelfde lijst
c[1] = 7# b[1] nu ook 7
d = [1,2,3]# d is lijst
e = [9,d,8]# e nu [9,[1,2,3],8]
d[1] = 0# e nu [9,[1,0,3],8]
f = [1,2,3,]# f is lijst
g = [9,f[:],8]# g nu [9,[1,2,3],8]]
f[1] = 0# nu [9,[1,2,3],8]

Method: functie bij specifiek datatype

a = [7,1,9,2]# a is a list
a.sort()# sort van list a nu [1,2,7,9]
a.append(23)# append van list (voeg 1 element toe) a nu [1,2,7,9,23]
a.extend([6,5])# extend van list (voegt hele lijst toe) a nu [1,2,7,9,23,6,5]
n = a.pop()# pop van list (verwijdert laatste element n wordt nu 5 a nu [1,2,7,9,23,6]
m = a.pop(3)# pop van list (verwijdert element 3) m wordt 9 a nu [1,2,7,23,6]

Lijst van methoden voor bepaalde datatype

>>>> dir(list)
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Meer info over gebruik van methodes

>>>> help(list)
Help on class list in module __builtin__:
class list(object)
    list() -> new empty list
    list(iterable) -> new empty list initialized from iterable's items
 
    Methods defined here:
 
    __add__(...)
        x.__add__(y) <==> x+y
 
    append(...)
        L.append(object) -- append object to end
 
    count(...)
        L.count(value) -> integer -- return nr of occurrences of value
 
....
>>>> help(list.append)
....

sequences

Dataypes string, list en tuple veel gemeen: gezamelijk "sequences"

s = "EYAWTKAPBWATA
if "A" in s: ...# 'A' in s ?
print(s[::2])# 'EATABAA'
c = len(s)# 13
a = min(s); b = max(s)# 'A' resp. 'Y'
l = [17,51,12,3,46,25]
if 46 in 1: ...# 46 in 1?
n = l[1:5:2][51, 3] (1 tot 5!)
c = len(1)6
a = min(1); b = max(1)3 resp. 51
t = (23, "hallo", 77)
if 77 in t: ...# True
u = t[:2]# (23, 'hallo')
c = len(t)3
a = min(t)Exception: unorderable types!
b = max(t)Exception: unorderable types!

Veel-gebruikte sequence operators

x in stest of element met waarde x in s zit
x not in s
s + ts geconcateneerd met t
s * nn exemplaren van s
n * s
s[i]element i van s, geteld vanaf 0
s[i:j]slice van s vanaf i tot j
s[i:]slice van s vanaf i tot einde
s[i:j:k]slice van s vanaf i tot einde, stapgrootte k
len(s)lengte van s (aantal objecten)
min(s)kleinste element van s
max(s)grootste element van s

String methods

String heeft - naast sequence methods - nog extra methods

 
s = "!Jantje zag pruimen hangen!!"
c = s.count('an')# 2 keer 'an'
i = s.find('ag')# 9 s[9...] 'ag...'
i = s.find('zzz')# -1 niet gevonden
 
i = s.index('ag')# 9
i = s.index('zzz')# Exception!
 
u = s.super()# u bevat '!JANTJE ZAG ...'
z = s.stip('!')# z bevat 'Jantje zag pruimen hangen'
 
p = s.replace('Jantje', 'Pietje')# p bevat '!Pietje zag ...'
 
t = s.split()# ['Jantje', 'zag', 'pruimen', 'hangen!!']
for woord in t:
    print
 
v = "=".join(t)# '!Jantje=zag=pruimen=hangen!!
s.count(s2[,b[,e]])tel aantal keren s2 in s of deel daarvan
s.endswitch(s2[,b[,e]])start of eindigt s (of substring) met s2?
s.startswitch(s2[,b[,e]])
s.find(s2[,b[,e]])vind s2 in s vanaf links of vanaf rechts
s.rfind(s2[,b[,e]])(-1 als niet gevonden)
s.index(s2[,b[,e]])idem, met exception als niet gevonden
s.rindex(s2[,b[,e]])
s.isalnum(), s.isalpha(), s.isdigit(),test alle characters in s
s.islower(), s.isspace(), s.istitle(),true als alle voldoen, fals als niet of leeg
s.isupper()
s.lower(), s.upper(), swapcase(),maak hele string uppercase, lowercase, ...
s.capitalize(), s.title()
s.lstrip([s2]), s.rstrip([s2]),verwijder chars in s2 uit s
s.strip([s2])(default: whitspace)

Merk op: string immutable, dus methods geven nieuwe string terug!

Veel gebruikte string methods:

s.replace(old, new[,cnt])vervang old door new in s (geeft nieuwe string)
s.join(seq)maak string van seq met scheider s
s.split([sep[,max]])maak lijst van s, met scheider sep
s.splitlines([keepends])maak lijst van regels (default: verwijder newlines)

String formateren - klassiek

Variabelen ingevuld voor %. in expressie
"v1 is %d\n" % v1
"de drie v's: %d %f %d\n" % (v1, v2, v3)

%d %igeheel getal in decimale notatie
%e %E %f %F %g %Gfloating point formaat met/zonder exponent
%ccharacter
%s %rals string met str()
%%letterlijke %

a=5.62
print(">%d<" % a)# '>5<'
print(">%f<" % a)# '>5.620000<'
a=1023
print(">%d<" % a)# >1023
n='Eric'
print(">Hallo % s<" % n)# >Hallo Eric
Formateren gaat verder: toevoegen tussen % en conversiecode
getalminimale veldbreedte, rechts uitlijnen
-getallinks i.p.v. rechtsuitlijnen
0getalvoorloopnullen i.p.v. spaties
.getalprecisie-aanduiding

Voorbeelden

a=512
print(">%7d<" % a)# >    512<
print(">%-6d<" % a)# >512   <
print(">%05d<" % a)# >00512<
print(">%-05d<" % a)# >512  <
">
a=5.115
print(">%7.2f<" % a)# >   5.12<
print(">%.1f<" % a)# >5.1<
print(">%5d< >%7.2f<" % (a, b))

String formattering methode str.format())

variablelen insmelten vor {} in string - postitioneel of benoemd
v = 5.3
w = 17
print( 'Values:{}, {}, {}'.format(v, "hey", w))
# uitvoer: ""Values: 5.3, hey, 17"
print( 'Values:{}, {}, {}'.format(v, "hey", w))
# uitvoer: ""Values: 5.3, 17, hey, 5.3"
s = "{p1}, {p3}, {p2}, {{0}})".format(p1=v, p2="hey", p3=w)
# s bevat: "5.3, 17, hey, (0)"

Als je een dictionary gebruikt, mag je zelfs de keys meegeven om te refereren aan bepaalde elementen van de dictionary, zoals aangegeven in dit voorbeeld:

d = {'a':1, 'b':2, 'c':3}
 
print(d['a'])
print("{0[c]}, {0[b]}".format(d))

           
Formateren gaat verder: {veld:specifier}
specifier: [uitlijnen][breedte][persentatie]
<   links (default string)optioneelc      character
>   rechts (default int)uitvullen end      decimaal
^   centrerenpercisiee f g exponent, float of keuze
=   padding achter teken%
+   expliciet teken

voorbeelden:

a = 512
print(">{0:7}<".format(a))# >      512<
print(">{0:^7}<".format(a))# >   512   <
print(">{0:7}<".format(-a))# >     -512<
print(">{0:=7}<".format(-a))# >-     512<
print(">{0:<6}<".format(a))# >512      <
print(">{0:05}<".format(a))# >00512<
print(">{0:<05}<".format(a))# >51200<
b = 5.115
print(">{0}}<".format(b))# >5.115<
print(">{0:7.2f)}<".format(b))# >   5.12<
print(">{0:.1f)}<".format(b))# >5.1<

Als je een enkele waarde wilt formaterem, kun je gebruik maken van de format functie:

getal = 7
bond = format(getal, '>03d')
print(bond)# >007<

List:

lijst met waarden -- types mogen verschillen
u = []# lege lijst
v = [1, 2, 'ho']# 3 elementen
 
w = [1, [5, 7], 7]# 3 elementen: resp. int, list, int
 
w = [0]# 1
w = [1]# [5,7]
w = [0:2]# [1,[5,7]]
w = [1:]# [[5,7],7]
w = [1][0]# 5
 
# if 5 in w:# False
    ....
 
# if 5 in w[1]:# True
    ....

Gebruik van operatoren
v2 = ["ha"]# ['ha']
v3 = v2 * 3# ['ha','ha','ha']
 
v3[1] = 'ho'# ['ha', 'ho', 'ha']
 
v4 = v3 + v2# ['ha','ho','ha','ha']

Valkuil bij gebruik van slices
a = [1, [2, 3], 4]
b = a[:]# b top-level kopie van a
 
a[0] = 5
print(b[0])# waarde blijft 1
 
a[1][0] = 7
print(b[1][0])# waarde 7 !!
 
import copy
c = copy.deepcopy(a)# c volledige kopie

In plaats van de notatie:

mag ook:

Maar ook de .copy() methode maakt slechts een top-level kopie!

List methodes en functies
v = [1,2,3]
v.reverse()# b top-level kopie van a
v.append(4)
v.insert(1, 6)
v.sort()# waarde blijft 1
 
i = v.index(2)
v.extend([0,7])# waarde 7 !!
 
del v[4]
a = v.pop()# c volledige kopie
t = sum(v)# c volledige kopie
z = sorted(v)# c volledige kopie
 # c volledige kopie
s = "hoi!"# c volledige kopie
w = list(s)# c volledige kopie
on = list( range(1,1000,2))# c volledige kopie

Het tussenvoegen of vervangen van één f meerdere elementen is (ook) mogelijk met de slice-notatie:



List comprehension

List opbouwen
l = []
for i in range(100)
    l.append(2**i)# vul list l met tweemachten
Kan ook in één keer:
l = [ 2**i for i in range(100) ]
Dit kan ook
l = [ 2**i for i in range(100) if i%13 ==0 ]# waarde blijft 1
Zelfs dit kan:
a = [1,2,3]
b = [4,5]
l = [ (i,j) for i in a for j in b ]
print(l)# [(1,4),(1,5), (2,4), (2,5), (3,4), (3,5)]

list comprehension versus element vermenigvuldiging

Voorbeeld element vermenigvuldiging:
>>> a = [ [0]*2 ]*3>>> a = []
>>> a>>> a.append([0, 0])
[[0, 0], [0, 0], [0, 0]]>>>a.append( a[0] )
>>> a[0][1] = 7>>> a.append( a[0] )
>>> a>>> a[0][1] = 7
[[0,7],[0,0],[0,0]]>>> vergelijk: x = [1,2,3]
               y = x
Voorbeeld list comprehension:
>>> a = [ [0]*2 for i in range(3) ]>>> a = []
>>> a [[0,0], [0, 0], [0, 0]]>>> a.append([0, 0])
>>> a[0][1] = 7>>> a.append([0, 0])
>>> a [[0, 7], [0, 0], [0, 0]]>>> a.append([0, 0])
>>> a[0][1] = 7
vergelijk: x = [1,2,3]
           y = [1,2,3]

Little endian versus big endian

Bte-volgorde in geheugen - endianess

Data in bestanden

Voorbeeld: lezen van .gif file
try:
    tux = open("tux.gif", "rb")
except Exception:
    ....
    
head = tux.read(3)# 3 bytes headers: 'GIF'
vers = tux.read(3)# 3 bytes versies: '87a' of '89a'
wpix = tux.read(3)# 2 bytes breedte (little endian)
hpix = tux.read(3)# 2 bytes hoogte (little endian)
 
breed = wpix[1] * 256 + wpix[0]# converteer naar integer
hoog  = wpix[1] * 256 + wpix[0]# converteer naar integer
 
print("%s: versie %s, %dx%d" % (head, vers, breed, hoog))
# uitvoer: b'GIF': versie b'89a', 595x842
 
tux.close()

In binary mode: bytes objects (b".....")

Het eerste deel van een gif file bevat de volgende informatie:
OffsetLengthContents
03 bytes"GIF"
33 bytes"87a" or "89a"
62 bytes<Logical Screen Width>
82 bytes<Logical Screen Height>
101 bytesvarious markers
111 bytes<Background Color Index>
121 bytes<Pixel Aspect Ratio>
...

Binaire files - open mode

f = open(filenaam [,mode])

Wijze van openen (mode)
'rb'voor lezen
'r+b'voor lezen en schrijven
'wb'voor schrijvenals niet-bestaand dan eerst creeren, anders leegmaken
'w+b'voor lezen en schrijvenals niet-bestaand dan eerst creeren, anders leegmaken
'xb'voor schrijvenals niet-bestaand dan eerst creeren, anders exception
'x+b'voor lezen en schrijvenals niet-bestaand dan eerst creeren, anders exception
'ab'voor appendals niet-bestaand dan eerst creeren
'a+b'voor append en lezenals niet-bestaand dan eerst creeren
...





list - types mogen verschillen, methoden en functies, comprehension typles Dictionaries


















Here is the list of all the available command line options:
Option Description
-d provide debug output
-O generate optimized bytecode (resulting in .pyo files)
-S do not run import site to look for Python paths on startup
-v verbose output (detailed trace on import statements)
-X disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6
-c cmd run Python script sent in as cmd string
file run Python script from given file

for the User

The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action −

#!/usr/bin/python
raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application.

Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon −

import sys; x = 'foo'; sys.stdout.write(x + '\n')


Data Types

Python has five standard data types −


Python Numbers

Number data types store numeric values. Number objects are created when you assign a value to them. For example −

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −

del var del var_a, var_b


Python supports four different numerical types −


Examples

Here are some examples of numbers −
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example −


#!/usr/bin/python

str = 'Hello World!'

print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string


This will produce the following result −

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST


Python Lists

Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.


The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example −


#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists


This produce the following result −

['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']


Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example −


#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists


This produce the following result −

('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list


Python Dictionary

Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example −

#!/usr/bin/python

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values


This produce the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']


Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.


Data Type Conversion

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.


There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.


Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

CBT Nuggets

Python Program Flow .py


Objects + types

object: everything in python data entity/attr methods entity passed to fx/assigned to var
Python is: dynamically typed strongly typed data type: data classification characteristics


operators:

+, -, *, /, //, %, **, <, >, ==,!=, AND, OR, NOT


Volgorde van operatie (PEMDAS)

type() # geeft het type variable terug, int char, float etc
isinstance() # test for datatype( Bool) int();
float() # type conversion

Phyton core data types

- number immutable - string - typle
- list mutable - dictionary - files

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

[ Show Example ]

OperatorDescriptionExample
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true. (a!= b) is true.
> If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
< If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −

[ Show Example ]

Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

Pyhton's built-in function bin() can be used to obtain binary representation of integer number.

There are following Bitwise operators supported by Python language

[ Show Example ]

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement It is unary and has the effect of 'flipping' bits. (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. a << = 240 (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand. a >> = 15 (means 0000 1111)

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds True and variable b holds False then

[ Show Example ]

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below

[ Show Example ]

OperatorDescriptionExample
in Evaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators explained below:

[ Show Example ]

OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise. x is not y, here is not results in 1 if id(x) is not equal to id(y).

Python Operators Precedence

The following table lists all operators from highest precedence to lowest.

[ Show Example ]

OperatorDescription
** Exponentiation (raise to the power)
~ + - Ccomplement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators