ADL 02 Python Primer
ADL 02 Python Primer
2
How can we ask a user for information?
• The input function allows you to specify a message to display and returns the
value typed in by the user.
• We store it in a variable called name
• Modify it
name = "Mary"
print(name)
Variables
• Store information
• Use meaningful names
• Numbers as first character forbidden (1Variable, 3name,...)
• Case sensitive
• Not type explicit (compare to java: int myvar = ...)
• Type can be retrieved with type(var)
4
Types
Example:
salary = 5000
bonus = 500
payCheck = salary + bonus
print(payCheck)
5
Types
Next try:
salary = input("Please enter your salary: ")
bonus = input("Please enter your bonus: ")
payCheck = salary + bonus
print(payCheck)
6
Types
Converting
• int(value) converts to an integer
• long(value) converts to a long integer
• float(value) converts to a floating number (i.e. a number
that can hold decimal places)
• str(value) converts to a string
Watch out:
var = "2"
print(var) #2
print(2 * var) #22
print(2 * int(var)) #4
print(var) #2 again
7
Conditional code
• If statements allow you to specify code that only executes if a specific
condition is true
answer=input("Would you like express shipping?")
if answer == "yes" :
print("That will be an extra $10")
print("Have a nice day")
• Watch out:
• indention is required!
• No brackets on condition
• No brackets on instructions
8
Conditional code
• Alternatives
• (What if you get a free toaster for over $100 and a free mug for under $100)
9
Visibility on variables
deposit= input("how much would you like to deposit? ")
if float(deposit) > 100 :
#Set the boolean variable freeToaster to True
freeToaster=True
10
Visibility on variables
#Initialize the variable to fix the error
freeToaster=False
11
Elif
country = input("Where are you from? " )
if country == "CANADA" :
print("Hello")
elif country == "GERMANY" : elif = short for else if
print("Guten Tag")
elif country == "FRANCE" :
print("Bonjour")
else :
print("Aloha/Ciao/G’Day")
12
Combine conditions
#Imagine you have code that ran earlier which
#set these two variables
wonLottery = True
bigWin = True
13
Combine conditions
#Imagine you have code that ran earlier which
#set these two variables
saturday = True
sunday = False
14
Nesting
• You can nest if statements inside each other (watch for indention)
monday = True
freshCoffee = False
if monday :
#you could have code here to check for fresh coffee
15
Loops
• Repeat instructions with loops
- Number of times to execute the body
for steps in range(4): - Can also be a variable
print("step " , steps)
print("left foot")
print("right foot") Starts with zero, ends with three
16
Loops
• Define start and end
for steps in range(1,4) :
print(steps) #1 2 3
• Define step-width
for steps in range(1,10,2) :
print(steps) #1 3 5 7 9
17
Loops
• Exactly define, what values you want
for steps in [1,2,3,4,5] :
print(steps) #1 2 3 4 5
→[ ] brackets and no range!
• Very flexible
for steps in ['red','blue’, 8.32, 42] :
...
18
Loops
• While loop
answer = "0"
19
Lists
• Lists allow you to store multiple values
guests = ['Christopher','Susan','Bill','Satya’]
scores = [78,85,62,49,98]
emptyList = []
• Print some elements from the list
print(guests[0]) #first / index 0
print(guests[-1]) #last
print(guests[-2]) #second last
20
Lists
• Modify entry
guests[0] = 'Steve'
• Append something
guests.append('Steve‘)
• Remove something
guests.remove('Christopher‘)
• Check for something
print(guests.index('Bill’)) #returns index
21
Lists
Deleting an element
guests = ['Christopher','Susan','Bill','Satya']
22
Lists
guests = ['Christopher','Susan','Bill','Satya']
23
Lists
#this is really easy
guests = ['Christopher','Susan','Bill','Satya']
24
Slicing a list
• Access pieces of lists with slicing
• Provide start and end, separated by colon „:“
In [18]: b
Out[18]: [10.0, 'girls & boys', (2+0j), 3.14159, 21]
In [19]: b[1:4]
Out[19]: ['girls & boys', (2+0j), 3.14159]
In [20]: b[3:5]
Out[20]: [3.14159, 21]
25
Slicing
• if left index is 0 or right is the length of the list, it can be left out
In [21]: b[2:]
Out[21]: [(2+0j), 3.14159, 21]
In [22]: b[:3]
Out[22]: [10.0, 'girls & boys', (2+0j)]
In [23]: b[:]
Out[23]: [10.0, 'girls & boys', (2+0j), 3.14159, 21]
26
Tuple
• Tuples are immutable lists
In [37]: c = (1, 1, 2, 3, 5, 8, 13)
In [37]: c[4]
Out[38]: 5
In [39]:
c[4] = 7
---------------------------------------------------------------------------
TypeError: 'tuple' object does not support item assignment
27
Multidimensional lists
• A list of lists
In [40]: a = [[3, 9], [8, 5], [11, 1]]
In [41]: a[0]
Out[41]: [3, 9] #returns list at a[0]
In [42]: a[1]
Out[42]: [8, 5]
In [43]: a[1][0]
Out[43]: 8
28
NumPy Arrays
• Also ndarray
• No mixed datatypes
• Can be created from lists
In [1]: a = [0, 0, 1, 4, 7, 16, 31, 64, 127]
In [2]: b = array(a)
In [3]: b
Out[3]: array([ 0, 0, 1, 4, 7, 16, 31, 64, 127])
• Promotes all entries to most general datatype (e.g. int to float)
29
NumPy Arrays
• Can be directly created
In [6]: linspace(0, 10, 5)
Out[6]: array([ 0. , 2.5, 5. , 7.5, 10. ])
• Or
In [10]: arange(0., 10, 2)
Out[10]: array([ 0., 2., 4., 6., 8.])
30
NumPy Arrays
• Create uniform arrays
In [12]: zeros(6)
Out[12]: array([ 0., 0., 0., 0., 0., 0.])
31
NumPy Arrays
• Benefit: you can process/transform all elements at once
In [16]: a
Out[16]: array([-1., 0., 1., 2., 3., 4., 5.])
In [17]: a*6
Out[17]: array([ -6., 0., 6., 12., 18., 24., 30.])
• Or
In [26]: b = 5*ones(8)
In [27]: b
Out[27]: array([ 5., 5., 5., 5., 5., 5., 5., 5.])
32
NumPy Arrays
• Also works with functions
In [30]: x = linspace(-3.14, 3.14, 21)
In [31]: y = cos(x)
In [32]: x
Out[32]: array([-3.14 , -2.826, -2.512, -2.198, -1.884, -1.57 , -1.256, -0.942, -
0.628, -0.314, 0. , 0.314, 0.628, 0.942, 1.256, 1.57 , 1.884, 2.198, 2.512,
2.826, 3.14 ])
• Addressing and slicing work just like using a list
33
Dictionary
• A collection of objects, but indexed by numbers or strings
In [1]: room = {"Emma":309, "Jacob":582, "Olivia":764}
In [2]: room["Olivia"]
Out[2]: 764 #gives us the entry to the key Olivia
• Building a dictonary
In [8]: d = {}
In [9]: d["last name"] = "Alberts"
In [10]: d["first name"] = "Marie"
34
Dictionary
• Get keys or values
In [13]: d.keys()
Out[13]: ['last name', 'first name', 'birthday‘]
In [14]: d.values()
Out[14]: ['Alberts', 'Marie', 'January 27']
35
Functions
• Defining a function with parameter
def print_hi(name):
print(f'Hi, {name}') # here as an f-string.
• And calling it
print_hi("Donald")
36
Functions
• Everything is passed by reference
# Function definition is here
37
Functions
• One little caveat
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assign new reference in mylist
print("Values inside the function: ", mylist)
return
38
Functions
• Keyword arguments allows skipping of arguments or out of order arguments
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
39
Functions
• Default arguments allow skipping of arguments
# Function definition is here
def printinfo( name, age = 35):
"This prints a passed info into this function"
print("Name: ", name)
print("Age ", age)
return;
# Now you can call printinfo function
printinfo(name="miki" ) # miki 35
printinfo( age=50, name="miki" ) #still works miki 50
40
Functions
• Return values
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print("Inside the function : ", total)
return total;
41
Classes
• An example
class Bike:
name = ""
gear = 0
• Create an object
bike1 = Bike()
bike1.gear = 11 #modify it
42
Classes
• An example
class Bike:
name = ""
gear = 0
#method
def give_info(self):
print(“bike gears: ", self.)
• Create an object
bike1 = Bike()
bike1.gear = 11 #modify it
bike1.give_info()
43
Classes
• An example
class Bike:
name = ""
gear = 0
# constructor function
def __init__(self, name = “unknown type"):
self.name = name
• Create an object
bike1 = Bike("Mountain Bike")
bike1.gear = 11 #modify it
bike1.give_info()
44
Classes
• Functions without self? → class function instead of object function
class Bike:
def test():
print("huhu")
Create an object
bike1 = Bike()
bike1.test() #ERROR
Bike.test() #works
45
Importing modules
• Importing other modules allows accessing their content
• Alias can be used
import tensorflow as tf
46
Running your code
• Running a python file
python my_python_file.py
47
Summary
• Indention is important
• Default and keyword parameters
• Always called be reference
• Lists and numPy arrays are important for ai projects
48