Today: variables, types, defining your own functions, if-else
How to use variables in Python.
# this is how you assign a variables
x = 2
y = 3
x+y
x**2 + x + 1
# you can re-assign and lose the old value
x = 3
x+y
# variables can hold strings as well
strng = "will print"
# by the way, print is a handy function, if you want to print more than one value
print("hellp")
print(x)
print("print " + strng, 1, 2, x, x+1)
Every variable (and every expression has a type)
# take a look at this
x = 2/2
print(x)
y = 1
print(y)
what's going on? It's because 2/2 has a different type than 1.
# division by integer has float type
type(2/2)
type(1.0)
type(1)
# let's look at some other types
type("hellooo")
# even functions have a type
type(abs)
import math
type(math.cos)
# even modules have type
type(math)
types are important in programming. you must always think about the types of the objects you are working with.
def f(x):
return x*x
f(3)
# what is this going to do?
def g(x,y):
print("One day, I will pass the Turing test.")
z = x + y
return z
z = 1/0 # we never get to this line
return z+1 # we never get to this line
g(1,2)
Every line inside the function is executed until return is called
# What's going to happen?
def f(x,y):
zzz = 0 # local variable
return x+y
f(2,1)
print(zzz) # error because zzz is a local variable, not known outside the function
We didn't do the following during the lecture, but it's good to put here
ggg = 1
def f(x,y):
ggg = 1000
return x+y
print(f(1,2),ggg)
So ggg's value didn't change. Why? It was because ggg inside the function is a new, local variable. Not the global one.
Fix: use the global
keyword
ggg = 1
def f(x,y):
global ggg
ggg = 1000
return x+y
print(f(1,2),ggg)