Crash course in Python
Crash course in Python
number_of_students = 47
print(type(number_of_students)) The value associated
with the variable
number_of_students is
of type int
division: x/y
always returns float
remainder: x%y
returns remainder (as int or float)
power: x ** y
strings: str
x="John"
x='John'
print(type(x))
string operations Always take a banana to
a party is a string literal,
i.e., an actual value
x="Always take a banana to a party!"
the value of y is added at the end of the value of x and the entire
result is stored in the new string z
Variables and values
bool
z takes the value False
x=4
Syntax note: uppercase y=2 the value of z changes
T followed by lowercase z=(x==y) #False to True
rue - nothing else is z=(x==x) #True
True! a=True
(likewise for False) b=False
bool: Relational and Logical operators
x=8
print(bool(x)) —-> True
y=‘’
print(bool(y)) ——> False
x=8
print(bool(x)) —-> True #But x is still 8
y=‘’
print(bool(y)) ——> False #But y is still an empty string
z = 43.4
print(bool(z)) —-> True #But z is still 43.4
x=8
y=0
result = x and y #0 because y is evaluated last
result = x or y #8 because if x is True then y doesn’t matter
result = y and x #0 because y is False and x doesn’t matter
variables and assignment
x = 5 #Simple assignment
x = y = 5 #Multiple assignment
x += 4 #Augmented assignment
the if statement
The “if” statement and logical
expressions
1. If the price of a stock drops more than 10% below the cost basis - close the position
as a STOP LOSS
2. If the price of the stock goes up by more than 20% - close the position as PROFIT
TAKING
3. If neither 1 nor 2 work, then do nothing
program control flow
purchase_price = float(input("Purchase price? "))
price_now = float(input("Price now? "))
if price_now < .9 * purchase_price:
print("Stop Loss activated. Close the position”)
elif price_now > 1.2 * purchase_price:
print("Profit taking activated. Close the position")
else:
print("Do nothing") this gets done only if the first logical
this gets done only if neither logical
expression is False and the second
expression evaluates to True
one is True
if … elif …. else ….
if condition1 :
statement1_1
statement1_2
… if condition 1 is True then the program does statements 1_1 to 1_n and
statement1_n
elif condition2 : jumps to the post_if statements
statement2_1
statement2_2 if condition 1 is False then condition 2 is checked. If it is True, then the
… program does statements 2_1 to 2_n and jumps to the post_if
statement2_n
elif condition3 : statements
statement3_1
statement3_2 And so on
…
statement3_n
else: If neither of the if or elif conditions evaluate to True then, and only then,
statement4_1 statements 4_1 to 4_n are executed
statement4_2
…
statement4_n
post_if_statement1
post_if_statement2
……
Syntax note: program blocks
else:
print("HOLD: Don't do anything!")
print("Your unrealized profit is",price_now-purchase_price,"Dollars per share")
print("Hope you enjoyed this program!")
the end of indenting
indicates that the block
has ended
Nested blocks
x=5
y=7
z=max(x,y)
print(z)
x,y are arguments or parameters to the
function
max is a black box. we don’t know how
python is figuring out which one is the
greater of the two (and we don’t want
to know!)
Function libraries
Functions can be grouped in libraries
import easygui as eg
eg.msgbox('To be or not to be','What Hamlet elocuted')
def compute_return(price_then,price_now):
investment_return = (price_now - price_then)/price_then * 100
return investment_return
investment_return is a
return is a keyword. it
variable. you can use
tells python what the
any expression here that
function should return
evaluates to a value
Returning values from a function
def spam(x):
x=x+1
def minmax(x,y):
return min(x,y),max(x,y)
x,y = minmax(7,2)
print(x,y) —-> 2,7
a=30
print(div(a,10)) —-> x is 30, y is 10, prints 3
def div(x,y):
return x/y
x=10
y=30
print(div(y,x)) —-> x is 30, y is 10, prints 3
Passing arguments to a function
print(div(x=30,y=10)) —-> 3
print(div(y=10,x=30)) —-> 3
Functions can have default arguments
r1 = compute_return(1.2,91.2)
r1 = compute_return(1.2,91.2,100)
z is 100
Functions can have functions as arguments
(first order functions)
order_by(4,7,max)
pass the function max to
order_by
Collections and
Iteration
Collections
Lists: Sequential ordered mutable collections
Key properties
Examples
x = [1,2,3,4]
x[0]=8 —-> [8,2,3,4]
Mutable vs immutable
Try this?
x = [1,2,3]
y=x
x[2] = 4
print(x)
print(y)
Mutable vs immutable
And this
y=['a','b']
x = [1,y,3]
y[1] = 4
print(x)
print(y)
Mutable vs immutable
What’s the difference?
All list operations, except for the ones that change the
value of a list, are also valid tuple operations
Iteration
iterating using location indices
inventory = [('widgets',100),('spam',30),('eggs',200)]
y=search_list(inventory,'spam')
#The value of y should be 30
y=search_list(prices,'hay')
#The value of y should be None
Dictionaries: key-value pairs
mktcaps = {'AAPL':538.7,'GOOG':68.7,'IONS':4.6}
mktcaps['AAPL'] #key-based retrieval
print(mktcaps['AAPL'])
mktcaps['GE'] #error (no "GE")
'GE' in mktcaps
mktcaps.keys() #returns a list of keys
sorted(mktcaps.keys()) #returns a sorted list of keys
Sets: unordered collections of unique objects
tickers={"AAPL","GE","NFLX","IONS"}
regions={"North East","South","West coast","Mid-West"}
"AAPL" in tickers #membership test
"IBM" not in tickers #non-membership test
pharma_tickers={"IONS","IMCL"}
tickers.isdisjoint(pharma_tickers) #empty intersection
pharma_tickers <= tickers #subset test
pharma_tickers < tickers #proper-subset test
tickers > pharma_tickers #superset
tickers & pharma_tickers #intersection
tickers | pharma_tickers #union
tickers - pharma_tickers #set difference