ls scripts/hello-world*.py cat scripts/hello-world.py !python scripts/hello-world.py cat scripts/hello-world-in-arabic.py !python scripts/hello-world-in-arabic.py import math import math x = math.cos(2 * math.pi) print(x) from math import * x = cos(2 * pi) print(x) from math import cos, pi x = cos(2 * pi) print(x) from math import cos as cos1 import math as ma x = cos1(2 * ma.pi) print(x) import math print(dir(math)) help(math.log) log(10) log(10, 2) %load solutions/getting_help.py from os import getcwd help(getcwd) print(getcwd()) # variable assignments x = 1.0 my_variable = 12.2 type(x) x = 1 type(x) print(y) # integers x = 1 type(x) # float x = 1.0 type(x) # boolean b1 = True b2 = False type(b1) # complex numbers: note the use of `j` to specify the imaginary part x = 1.0 - 1.0j type(x) print(x) print(x.real, x.imag) import types # print all types defined in the `types` module print(dir(types)) x = 1.0 # check if the variable x is a float type(x) is float # check if the variable x is an int type(x) is int isinstance(x, float) x = 1.5 print(x, type(x)) x = int(x) print(x, type(x)) z = complex(x) print(z, type(z)) x = float(z) y = bool(z.real) print(z.real, " -> ", y, type(y)) y = bool(z.imag) print(z.imag, " -> ", y, type(y)) 1 + 2, 1 - 2, 1 * 2, 1 / 2 1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0 # Integer division of float numbers 3.0 // 2.0 # Note! The power operators in python isn't ^, but ** 2 ** 2 True and False not False True or False 2 > 1, 2 < 1 2 > 2, 2 < 2 2 >= 2, 2 <= 2 # equality [1,2] == [1,2] # inequality 1 != 1 # objects identical? l1 =[1,2] l2 = l1 l1 is l2 a = 15 b = 5 c = 2.2 # expression evaluation here val = 0 print(val) %load solutions/operators.py a = 15 b = 5 c = 2.2 # expression evaluation here val = (float(5*(a>b)) + float(2*(a<(b*4))))/float(a) * c print(val) s = "Hello world" type(s) s1 = "KAUST's hello world" print(s1) s2 = 'He said "Hello"' print(s2) # length of the string: the number of characters len(s) # replace a substring in a string with somethign else s2 = s.replace("world", "test") print(s2) s[0] s[0:5] s[:5] s[6:] s[:] s[:-2] s[-1], s[-2] s[::1] s[::2] print(dir(str)) import math print 'The value of %5s is approximately %5.3f.' % ('PI', math.pi) print('1234'.zfill(7)) print('-3.14'.zfill(7)) print('1234'.zfill(2)) print str(1).rjust(2), str(1**2).rjust(3),str(1**3).rjust(4) print str(5).rjust(2), str(5**2).rjust(3),str(5**3).rjust(4) print str(10).rjust(2), str(10**2).rjust(3),str(10**3).rjust(4) print('We are the {} who say "{}!"'.format('knights', 'Ni')) print('{0} and {1}'.format('spam', 'eggs')) print('{1} and {0}'.format('spam', 'eggs')) print( 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible') ) print( 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg') ) import math print( 'The value of PI is approximately {0:.3f}.'.format(math.pi) ) name1 = 'Sjoerd' phone1 = 4127 name2 = 'Jack' phone2 = 4098 name3 = 'Dcab' phone3 = 7678 print( '{0:10} ==> {1:10d}'.format(name1, phone1) ) print( '{0:10} ==> {1:10d}'.format(name2, phone2) ) print( '{0:10} ==> {1:10d}'.format(name3, phone3) ) %load solutions/strings.py s = 'Hello world' s = s.replace('o', 'a') s = s[:6].lower() + s[6:].upper() print(s[3:-1]) l = [1,2,3,4] print(type(l)) print(l) print(l) print(l[1:3]) print(l[::2]) l[0] l = [1, 'a', 1.0, 1-1j] print(l) nested_list = [1, [2, [3, [4, [5]]]]] print(nested_list) nl = [1, [2, 3, 4], [5, [6, 7, 8]]] print(nl) print(nl[0]) print(nl[1][1]) print(nl[2][1][2]) start = 10 stop = 30 step = 2 range(start, stop, step) # in python 3 range generates an interator, which can be converted to a list using 'list(...)'. It has no effect in python 2 list(range(start, stop, step)) list(range(-10, 10)) s # convert a string to a list by type casting: s2 = list(s) s2 # sorting lists s2.sort() print(s2) # create a new empty list l = [] # add an elements using `append` l.append("A") l.append("d") l.append("d") print(l) l[1] = "p" l[2] = "p" print(l) l[1:3] = ["d", "d"] print(l) l.insert(0, "i") l.insert(1, "n") l.insert(2, "s") l.insert(3, "e") l.insert(4, "r") l.insert(5, "t") print(l) l.remove("A") print(l) del l[7] del l[6] print(l) l1 = [1, 2, 3] + [4, 5, 6] print(l1) l2 = [1, 2, 3] * 2 print(l2) a = [1, 2, 3] b = a print("a is b? ", a is b) b[0] = -1 print("a = ", a) print("b = ", b) a = [1, 2, 3] b = a[:] # or: print("a is b? ", a is b) c = list(a) b[0] = -1 c[1] = -1 print("a = ", a) print("b = ", b) print("c = ", c) a = [ [1, 2, 3], 4, 5] b = a[:] c = list(a) a[0].append(-1) print("a = ", a) print("b = ", b) print("c = ", c) from copy import deepcopy a = [ [1, 2, 3], 4, 5] b = deepcopy(a) a[0].append(-1) print("a = ", a) print("b = ", b) %load solutions/lists.py l = range(5,16,2) print(l) l[-1] = range(4,9,2) print(l) l[-1][-2] = -1 print(l) del l[1:4] print(l) l.insert(1, 'Hello') print(l) point = (10, 20) print(point, type(point)) point = 10, 20 print(point, type(point)) x, y = point print("x =", x) print("y =", y) point[0] = 20 params = {"parameter1" : 1.0, "parameter2" : 2.0, "parameter3" : 3.0, 1: 4.0, (5, 'ho'): 'hi'} print(type(params)) print(params) print("parameter1 = " + str(params["parameter1"])) print("parameter2 = " + str(params["parameter2"])) print("parameter3 = " + str(params["parameter3"])) params["parameter1"] = "A" params["parameter2"] = "B" # add a new entry params["parameter4"] = "D" print("parameter1 = " + str(params["parameter1"])) print("parameter2 = " + str(params["parameter2"])) print("parameter3 = " + str(params["parameter3"])) print("parameter4 = " + str(params["parameter4"])) print("'key 1' = " + str(params[1])) print("'key (5, 'ho')' = " + str(params[(5, 'ho')])) del params["parameter2"] print(params) %load solutions/dicts.py d = {('John', 'Smith'):30, ('Ahmad', 'Said'):22, ('Sara', 'John'):2 } print(d) john = ('John', 'Smith') d[john] = d[john] + 1 print(d) d[('Ahmad', 'Ahmad')] = 19 print(d) del d[('Sara','John')] print(d) statement1 = False statement2 = False if statement1: print("statement1 is True") elif statement2: print("statement2 is True") else: print("statement1 and statement2 are False") statement1 = statement2 = True if statement1: if statement2: print("both statement1 and statement2 are True") # Bad indentation! if statement1: if statement2: print("both statement1 and statement2 are True") # this line is not properly indented statement1 = False if statement1: print("printed if statement1 is True") print("still inside the if block") x = 10 y = 5 if x > y: print(float(x)/y) elif x == y: print(1) else: print(float(y)/x) if statement1: print("printed if statement1 is True") print("now outside the if block") # a compact way for using the if statement a = 2 if statement1 else 4 print("a= ", a) name = 'john' if name in ['jed', 'john']: print("We have Jed or John") num = 1 if num in [1, 2]: print("We have 1 or 2") for x in [1,2,3]: print(x) for x in range(4): # by default range start at 0 print(x) for x in range(-3,3): print(x) for word in ["scientific", "computing", "with", "python"]: print(word) for key, value in params.items(): print(key + " = " + str(value)) for idx, x in enumerate(range(-3,3)): print(idx, x) l1 = [x**2 for x in range(0,5)] print(l1) # Nested list comprehensions l2 = [(x, y) for x in range(0,5) for y in range(5,10)] print(l2) #List comprehensions with conditional statement l1 = [x**2 for x in range(0,5) if x != 2] print(l1) i = 0 while i < 5: print(i) i = i + 1 print("done") words = ["Aerial", "Affect", "Agile", "Agriculture", "Animal", "Attract", "Audubon", "Backyard", "Barrier", "Beak", "Bill", "Birdbath", "Branch", "Breed", "Buzzard", "The", "On", "Upper", "Not", "What", "Linked", "Up", "In", "A", "lol"] %load solutions/control_flow.py d = {} for w in words: if len(w) > 2: if len(w) in d: d[len(w)].append(w) else: d[len(w)] = [w] print d def func0(): print("test") func0() def func1(s): """ Print a string 's' and tell how many characters it has """ print(s + " has " + str(len(s)) + " characters") help(func1) func1("test") def square(x): """ Return the square of x. """ return x ** 2 square(4) def powers(x): """ Return a few powers of x. """ return x ** 2, x ** 3, x ** 4 powers(3) x2, x3, x4 = powers(3) print(x3) def myfunc(x, p=2, debug=False): if debug: print("evaluating myfunc for x = " + str(x) + " using exponent p = " + str(p)) return x**p myfunc(5) myfunc(5, debug=True) myfunc(p=3, debug=True, x=7) f1 = lambda x: x**2 # is equivalent to def f2(x): return x**2 f1(2), f2(2) # map is a built-in python function map(lambda x: x**2, range(-3,4)) # in python 3 we can use `list(...)` to convert the iterator to an explicit list list(map(lambda x: x**2, range(-3,4))) elements = [-100, 21, 115, 0.34, 45, -80, 12, 120, 73, -1] %load solutions/functions.py def apply(l, fun): new_l = [] for el in l: new_l.append(fun(el)) return new_l apply(elements, lambda x: abs(x)) import re # Regular expression functionality of Python is placed in a separate module 're' string = 'Hello, class! This is a testing string that contains a word CAT' pattern = r'CAT' match = re.search(pattern, string) if match: print 'found', match.group() else: print 'not found' string = 'Hello, class! This is a testing string that contains a word caT' pat = r'[cC][aA][tT]' print 'found', re.search(pat, string).group() # Special characters: . ^ $ * + ? { } [ ] \ | ( ) string = 'Hello, class! This is a testing string that contains a word CAR' pat = 'CA.' print 'found', re.search(pat, string).group() string = 'Hello, class! This is a testing string that contains a word CAAAAAAAAAAAT' pat = 'CA*T' print 'found', re.search(pat, string).group() string = 'Hello, class! This is a testing string that contains a word CAAT' pat = 'CA+T' print 'found', re.search(pat, string).group() pat = re.compile(r'CA+T') print 'found', pat.search(string).group() # Yet another example line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: print "No match!!" dir(pat) pat.findall? # A piece of text from "KAUST Highlights of 2013" article text = """ This past year saw members of KAUST faculty and leadership being awarded major international awards. At the beginning of the year, Prof. Jean Frechet, KAUST Vice President for Research, was awarded the 2013 Japan Prize in recognition of his original and outstanding scientific achievements serving to promote peace and prosperity for all mankind. Dr. Frechet and C. Grant Willson of the University of Texas at Austin were recognized for their achievement in the development of chemically amplified resistant polymer materials for innovative semiconductor manufacturing processes. Also appointed in the past year, Prof. Yves Gnanou, KAUST Dean of Physical Science and Engineering (PSE), was inducted into the elite ranks of the French Ordre national de la Légion d'honneur (National Order of the Legion of Honor). He was presented with the coveted Chevalier medal at a ceremony held in Paris on June 27, 2013. Established over two centuries ago by Napoleon Bonaparte, the award recognizes its recipients' extraordinary contributions to France and French culture. Prof. Gnanou previously served as Vice President of Academic Affairs and Research at École Polytechnique in Paris. Spanning a third continent, the Desert Research Institute (DRI), in the US, presented Nina Fedoroff, Distinguished Professor of Bioscience and Director of the KAUST Center for Desert Agriculture, with the 2013 Nevada Medal. The award acknowledges outstanding achievements in science and engineering. The DRI President, Dr. Stephen Wells, said: "In only a few decades Prof. Fedoroff's research has helped stimulate a revolution in biology." """ pat = re.compile(r'awards?') pat.findall(text) pat = re.compile(r'award[^\s,.!?:;]*') pat.findall(text) pat = re.compile(r'(award)([^\s,.!?:;]*)') pat.findall(text) # Taken from somewhere from the web emails =""" litke@talktalk.net owarne000s@talk21.com seo@webindustry.co.uk w0lfspirit32@hotmail.co.uk robert.douglas3@virgin.net dan@webindustry.co.uk sasha_aitken@mail.ru brian@tweddle1966.freeserve.co.uk asmileiscatching@hotmail.com sashalws@aol.com ebbygraham372@hotmail.com chnelxx@hotmail.com choudhury.esaa@hotmail.co.uk girishvishwasjoshi@gmail.com mark.clynch@ntlworld.com ssladmin@eskdalesaddlery.co.uk owarnes.t21@btinternet.com mgrahamhaulage@aol.com beccababes@dsl.pipex.com victor-2k7@hotmail.co.uk kellybomaholly@hotmail.com sugar@caton9108.freeserve.co.uk paulapowley@btinternet.com owarnes@talk21.com lesleygodwin1@hotmail.com nicolawinter4@hotmail.com diwasbhattarai@yahoo.com james.hutchinson@aggregate.com margaret.howroyd@hotmail.com tina.wane@tiscali.co.uk lizzy26259495@yahoo.com kennyspence53@hotmail.com pedrovieira1@gmail.com versivul@mail.ru booom2012@mail.ru sin_0.8@mail.ru kaplya71@mail.ru smirnova-s-s@mail.ru 325jm@mail.ru rasmyrik@mail.ru tanya_tyurnina@mail.ru fedorova2006@inbox.ru veniaminm77@mail.ru dimon_gushin@mail.ru anna_shevchenko@list.ru belexovagalina@mail.ru engelgardt_ledi_elena_01.11.77@mail.ru kolzhanov92@mail.ru digital1q@mail.ru """ %load solutions/regular.py pat = re.compile("([\w.-_]+)@([\w.-]+\.[a-z]+)") email_list = pat.findall(emails) print email_list[:3] print "# of emails in the list is", len(email_list) raise Exception("description of the error") try: print("test") # generate an error: the variable test is not defined print(test) except: print("Caught an expection") try: print("test") # generate an error: the variable test is not defined print(test) except Exception as e: print("Caught an exception:" + str(e)) os.makedirs('mydir') os.makedirs('mydir') # This will raise error because the directory already exist %load solutions/exeptions.py def ensure_dir(d): import os, errno try: os.makedirs(d) #except OSError as exc: except Exception as exc: if exc.errno == errno.EEXIST: pass else: raise ensure_dir('mydir')