Tel Aviv University - Python for engineers course
Summary of Python 2.7 Commands
Basic commands
Command Example Explanation
type type (‘123’) Returns the type of the expression
If, else, elif if condition1: Used to execute statements conditionally
statement1
elif condition2:
statement2
else:
statement3
for for element in iterable: Run over all the elements of a given iterable
statement (such as list, string)
while while condition: Used to repeat the same instructions until the
statement stop criterion is met
break for i in [0,1,2,3]: Terminates the nearest enclosing loop,
print ‘the number is:’ i skipping the code that follows the break inside
If i >= 0: the loop. Commonly used for getting out of
break loops once a condition is met.
>>> the number is: 0
continue for i in [0,1,2,3]: Continues with the next iteration of the loop
if i % 2 == 0 :
continue
print i
(it will print 1,3)
import import math Imports a complete module of functions.
print math.sqrt(10) Functions are used by typing:
module_name.Function_name(arguments)
int int(“x”) Converts x to an integer
str str(x) Converts object x to a string representation
float float(x) Converts x to a floating-point number.
list list (s) Converts s to a list.
Arithmetic operators
Command Example Explanation
+ x+y Adds x to y
- x-y Subtracts x from y
* x*y Multiplies x by y
** x ** y X to the power y
/ x/y Divides x by y
% x%y Computes the remainder of dividing x by y
+ x+y Adds x to y
Comparison operators
Command Example Explanation
Less than x<y true if x is less than y, otherwise false.
Greater than x>y true if x is greater than y, otherwise false.
Less than or equal x <= y true if x is less than or equal to y, otherwise
to false.
Greater than or x >= y true if x is greater than or equal to y,
equal to otherwise false.
Equal x == y true if x equals y, otherwise false.
Not Equal x != y true if x is not equal to y, otherwise false.
Logical operators
Command Example Explanation
and x and y If both a and y are True, return True,
otherwise: return False.
or x or y If either x or y is True, return True,
Otherwise: False.
not not x x is False -> True, x is True -> False
Strings
Command Example Explanation
Instantiation s=’ABCDEFG’ Creates a new String object
len len(s) Returns the length of string s
indexing s[0] Returns the character in position 0
slicing s[1:3] Returns a new string containing positions 1
(inclusive) to 5 (exclusive) of s
split s.split(‘,’) Splits the string into tokens using the
specified delimiter, returns a list of strings.
strip s.strip() Will remove white spaces from both sides of
the string
s.strip(‘abc’) Will remove any instance of the specified
characters from both sides of the string
rstrip/lstrip rstrip(“ abba “) Removes all trailing whitespace of string/
Removes all leading whitespace of string
+ s3=s1+s2 Returns a concatenation of s1 and s2
* s*2 Repeat
in 'a’ in s Membership test (returns True if substring is
part of string, False otherwise)
not in ‘a’ not in s Returns True if substring is not part of string,
False otherwise.
% “%s %d” % (s,i) Used to generate a string that combines text
and values of variables.
In the format string appearing between “ “, %s
is used as a placeholder for string and %d is
used as a placeholder for numeric or decimal
values
The placeholders are replaced by the values
of the variables specified after the format
string
format "Check {}self before {} Replaces the curly brackets in the original
wreck string with the specified parameters.
{}self.".format("your",
"you", "your")
>>>Check yourself
before you wreck
yourself.
find s1.find(s2) Returns the lowest index of substring s2
within s1, -1 if s2 is not within s1.
lower s.lower() Returns string with all characters being
lowercase
upper s.upper() Returns string with all characters being
uppercase
title s.title() Returns string with all words beginning in
uppercase
join s.join(lst) Returns a combined string containing all
objects within iterable lst (list or tuple, for
instance) with string s separating them.
replace s.replace(s1,s2) Returns string s with all substrings s1
replaces with substrings s2
startswith/endswith s.startswith(s1) Returns True if s starts/ends with substring
s.endswith(s1) s1, False otherwise.
Isalpha, isdigit, s.isalpha() Returns True if all characters within s are
islower, isupper s.isdigit() letters/digits/lowercase/uppercase.
s.islower()
s.isupper()
min/max min(“python”) Returns the min/max alphabetical character
from within the string.
center s.center(width) Returns s centered in a string of length width
Lists
Command Example Explanation
Instantiation l=[1,2,3] Creates a new List object
len len(l) Returns the length of list l
indexing l[0] Returns the item in position 0
l[0][2] Returns the item in row 0, column 2 of a two
dimensional matrix (list of lists)
slicing l[1:5] Returns a new list holding references to
elements 1 (inclusive) to 5 (exclusive) of l
Lst2 = lst1[:] Using slicing to duplicate lst1. Now lst2 is
an exact copy of lst1 but they point to
different objects in memory thus changing
lst2 will not affect lst1
range range(x) Returns a list of numbers spanning from 0
to x-1
range (2,6,2) Returns a list of integers from 2 to 6-1 using
2 as the step (==[2,4])
List [i**2 for i in range(10)] Creates a new list based on the specified
comprehensions rule. For ever i in the range add i**2 to the
new list.
Returns [0,1,4,9,16,...,81]
append(item) l.append(x) Adds object x to the end of list l
extend(list) l.extend(l2) Adds the items of list l2 to the end of list l
pop([index]) e=l.pop() Returns last object in list l and removes it
from the list. If index is specified, removes
item in location index.
remove(item) l.remove(item) Removes item from the list l
del del l[3] Deletes an element from the list
sort l.sort() Sorts the list l in place
count l.count(x) Returns number of occurrences of x within
list l
index l.index(x) Returns first index of x within l. Raises
ValueError if not present.
Insert l.insert(i,x) Inserts object x into list l before index i
reverse l.reverse() Reverses list l, replacing original list
sorted sorted(l) Returns a new sorted list containing all
items in l
sorted(l,reverse=True) Returns a new sorted list containing all
items in l, in reverse (descending) order
sorted(lst_of_lst, Returns a list that is sorted based on the
key=my_function) output of the function my_function
def my_function (my_function will be activated on each one
(member_in_list): of the list members)
return member_in_list[4]
max lst=[4,5,2,3] With a single iterable argument, return its
max(lst) largest item.
>>>5 With two or more arguments, return the
largest argument.
lst=[‘a’,’B’] ‘a’ is returned here because lower letters
max(lst) appear after upper letter in lexicographic
>>>’a’ order.
max(lst,key=str.upper) Specify a function name with the ‘key’
>>>’B’ parameter for the max/min/sort commands
in order to use ordering that is based on the
values returned by the function when
applied to each one of the list items.
min list=[4,5,2,3] With a single iterable argument, return its
min(list) smallest item.
>>>2 With two or more arguments, return the
smallest argument.
remove list=[4,5,2,3] removes the given object from the list
new_list=list.remove(3)
new_list=[4,5,2]
map list=[‘1’,’2’,’3’] Convert all the strings in the list to int ,
list=map(int,list) can work in the opposite way (from int to
>>>List string), and with other classes
>>>[1,2,3]
Tuples
Command Example Explanation
Instantiation t=(1,2,3) Creates a new Tuple object
tuple() tuple=tuple(list) tuple() takes a list as an input and turns it into
a tuple with same ingredients
len(tuple) t1 = (1,2,3) Returns the length/maximum/minimum of the
max(tuple) print len(t1) given tuple
min(tuple)
print max(t1)
print min(t1)
Sets
Command Example Explanation
Instantiation s={1,2,3} Creates a new Set object
s=set() Creates a new empty Set
s=set([1,2,3,3] Creates a new set object based on a list
>>(1,2,3)
Dictionaries
Command Example Explanation
Instantiation D={‘Moshe’:5,’David’:4} Creates a new Dictionary object
accessing D[k] Returns the value to which k is mapped in D
get D.get(k, [d]) Returns the value mapped for key k in D, if k
is not in D, returns d (default: None).
has_key D.has_key(k) Returns True if D has a key k, False
otherwise.
items D.items() Returns a list of all dictionary items as
2-tuples of (key, value) pairs
keys D.keys() Returns a list of D's keys
values D.values() Returns a list of D's values
pop D.pop(k, [d]) Removes the specified key k from D and
return its value. If k is not a key in D, returns
d. Raises a KeyError if k is not in D and d is
not specified.
update D.update(D2) Adds dictionary all items in D2 (key-value
pairs) into D. This function does not return
anything.
sorted sorted(D) Returns a new sorted list containing all keys
in D. Equivalent to sorted(D.keys()).
sorted(D.keys(), Returns a new sorted list containing all keys
reverse=True) in D, in reverse (descending) order
sorted(D.keys(), Returns a new list containing all keys in D,
key=D.get) sorted by their matching values in D.
Key is an optional parameter to the function
D={"first": 1, "third": 3, sorted. It specified a function to be used as a
"fourth": 4, "second": 2} key for the sorting.
sorted(d, key=d.get)
>>>['first', 'second',
'third', 'fourth']
Basic IO (Input/Output)
Command Example Explanation
print print i Prints to the screen the value of variable i +
new line
print i, Same, without adding a new line
raw_input str = raw_input(‘Enter Reads a line from standard input and return it
your input : ’) as a string
“\n” New line character
“\t” Tab character
File IO (Input/Output)
Command Example Explanation
open f=open(‘input.txt’,’r’) Opens a file for reading, returns a file object
f=open(‘output.txt’,’w’) Opens a file for writing, returns a file object
f=open(‘file.txt’,’a’) Opens a file for appending, returns a file
object
read s=f.read() Reads the entire content of file f, returns a
string
readline s=f.readline() Read the next line from the file f, returns a
string
readlines s=f.readlines() Reads all remaining lines from the file f,
returns a list of strings
For line in f: for line in f: Reads line by line from file f, line holds the
print line current line
close f.close() Closes a file to free up its resources
write f.write(‘abc’) Writes a string to a file.
writelines f.writelines([‘abc’,’ab’]]) Writes a sequence to a file, where each
element in the sequence is translated to a line
in the file. Only works for a sequence of
strings.
Functions
Command Example Explanation
def def Defines a new function that receives two
func_name(param1, parameters (arguments)
param2 = 0) The second parameter is assigned a default
value of 0 (which means the function can be
called without supplying a value for param2)
return return x Stops the execution of the function and return
the specified value (x) to the calling code
global global a Define “a” as a global variable rather than a
local variable (a will persist in memory after
the function ends)
:(Exceptions - טיפול בשגיאות זמן ריצה )חריגות
: תפיסה וטיפול בשגיאה שקרתה באופן בלתי צפוי.א
Explanation Example Command
ובמידה ונתקל בשגיאהTry מריץ את השורות שלאחר ה try: Try:
הוא מבצע את שורות הקודExceptionמהסוג שצוין ב X=50/0 …..
. ולאחר מכן סוגר את התוכניתException שלאחר ה except ZeroDivisionError: Except
Print "Error!" Type-of-Exception:
…...
אפילו אם.תוספת של מספר פקודות שיבוצעו בכל מקרה f=open("txt1.txt",'r') Finally:
נוצרה השגיאה try: …..
X="Hello"
X=int(X)
except ValueError:
….
finally:
f.close()
:סוגי שגיאות נפוצות שכדאי להכיר
0שגיאת חלוקה ב try: ZeroDivisionError
X=50/0
except ZeroDivisionError:
print "Error!"
(שגיאת ערך )בדוגמא – מנסה להמיר מחרוזת למספר Try: ValueError
X="Hello"
X=int(X)
except ValueError:
….
ניסיון פניה למשתנה שאינו קיים try: NameError
X=10
Print X+Y
except NameError:
Print "Y is not
defined"
שגיאה במידה ולא קיים הקובץ לפתיחה try: IOError
f=open("txt1.txt",'r')
…
except IOError:
Print "The file does
not exist"
תופס את כל סוגי השגיאות try: Exception
…
except Exception:
Print "Error!"
ניסיון לביצוע פעולות כאשר הטיפוס אינו-שגיאת טיפוס try: TypeError
מתאים num=2
Print ’2’ + num
except TypeError:
….
פקודה התופסת את כל השגיאות ומחזירה הודעה except Exception as e:
שמסבירה את השגיאה הספציפית print str(e)
:( זריקת חריגה באופן יזום )כשקוד שאנחנו כותבים נתקל במצב שלא מאפשר להמשיך.ב
Explanation Example Command
זורק חריגה באופן יזום מהסוג If a==0 raise TypeOfException
.שמצוין Raise ValueError
ניתן גם לרשום הודעה בסוגריים … raise TypeOfException(any
message)
If a==0
Raise ValueError("a is 0, please
change number")
…
רקורסיה:
פונקציה רקורסיבית היא פונקציה הקוראת לעצמה .כאשר כותבים פונקציה רקורסיבית צריך להגדיר את
תנאי הבסיס ואת צעד הרקורסיה.
דוגמאות פשוטות:
תנאי הבסיס הוא n==0
צעד הרקורסיה )n*factorial(n-1
תנאי הבסיס הוא n<2
) )fibonacci_rec(n-1)+fibonacci_rec(n-2
צעד הרקורסיה
אלגוריתמים למיון רשימות
Merge Sort
אלגוריתם מיון משופר ,מפלג את הרשימה המקורית ולאחר מכן ממזג את תת הרשימות לרשימה
ממויינת ,בצורה הבאה:
.1הגדרת מקרה בסיס.
.2חלוקת הרשימה המקורית לשתי תת רשימות ומיונן בצורה רקורסיבית.
.3מיזוג שתי תת הרשימות הממויינות.
לדוגמא:
לא נלמד הסמסטר Bubble Sort
אלגוריתם מיון הבנוי מלולאה בתוך לולאה .האלגוריתם מחליף ,אם צריך ,בין כל איברים צמודים ברשימה עד
שהרשימה ממוינת .משמעות המילה בועה בשם האלגוריתם הוא שבכל ריצה של הלולאה החיצונית האיבר הגדול
ביותר הוא כמו בועה שנעה למקומה המתאים .שקול בזמן הריצה לאלגוריתם מיון נאיבי שגם הוא )O(n^2
)Time complexity- o(n^2
Counting Sort
באלגוריתם זה בונים היסטוגרמה -מילון המכיל מפתחות שהם הערכים השונים ברשימה ,וערך כל מפתח הוא מספר
המופעים של מפתח זה ברשימה .בעזרת ההיסטוגרם האלגוריתם בונה רשימה ממוינת.
חשוב לציין שהפונקציה מקבלת את הערך max_valהמקיים שכל איברי הרשימה קטנים או שווים לו ,ושאיברי הרשימה לא
שליליים.
Time complexity- o(n+k); n=len(lst). k=max_val
NUMPY
Creating new arrays
Command Example Explanation
np.array a=np.array([1,2,3) Creates a new Numpy array from a list
a=np.array([1,2,3],dtyp Creates a new Numpy array from a list and
e=float-pyt’) convert to float
np.zeros Creates an array filled with zeros
np.ones Creates an array filled with ones
Reduction Functions
Command Example Explanation
np.sum a=np.array([[1,2,3],[4,5,6]])
s=np.sum(a) Returns the sum of all elements in a
s=a.sum() Same (the method version)
col_sums=a.sum(axis=0) Returns a vector containing the sums
col_sums=np.sum(a,axis=0) of each column in a
row_sums=a.sum(axis=1) Returns a vector containing the sums
row_sums=np.sum(a,axis=1) of each row in a
np.max mx=np.max(a) Returns the maximal value in a
mx=a.max()
np.min
np.mean mn=a.mean() Returns the mean(single value) of a’s
values
c_mn=a.mean(axis=0) Returns the mean of a’s columns as a
vector
r_mn=a.mean(axis=1) Returns the mean of a’s rows as a
vector
np.all r= a.all() True אם כל המטריצה היאTrue מחזיר
np.any )(r= a.any Returns True if exists at least one
True value in array a
Arg Functions
Command Example Explanation
np.argmax )(a.argmax הפקודה תחזיר את האינדקס של האיבר בעל הערך
המקסימלי במערך
)a.argmax(axis=0 תחזיר רשימת אינדקסים של האיבר המקסימלי בכל
טור
np.argmin )(a.argmin הפקודה תחזיר את האינדקס של האיבר בעל הערך
המינימלי במערך
)a.argmin(axis=1 תחזיר רשימת אינדקסים של האיבר המינימלי בכל
שורה
np.argsort )np.argsort(a תחזיר רשימת אינדקסים כך שאם נסדר את המערך
לפיה ,הוא יופיע בסדר עולה מהאיבר הקטן לגדול