0% found this document useful (0 votes)
10 views

ADL 02 Python Primer

Uploaded by

Prachi Painuly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

ADL 02 Python Primer

Uploaded by

Prachi Painuly
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Python

Crash course for python


Content
• Input/output • Lists / tuples / dictionaries
• Variables • Modules / imports
• Conditional clauses • Classes
• Loops
• Functions

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

name = input("What is your name? ") No semicolon


• Print it on the console
print(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)

deposit=input("How much would you like to deposit? ")


if float(deposit) > 100 :
print("You get a free toaster!")
else:
print("Enjoy your free mug!")
print("Have a nice day")
• Else is only executed if the condition is NOT true

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

#if the variable freeToaster is True


#the print statement will execute
if freeToaster :
print("enjoy your toaster")
Error „freeToaster“ not defined

10
Visibility on variables
#Initialize the variable to fix the error
freeToaster=False

deposit= input("how much would you like to deposit? ")


if float(deposit) > 100 :
#Set the boolean variable freeToaster to True
freeToaster=True

#if the variable freeToaster is True


#the print statement will execute
if freeToaster :
print("enjoy your toaster")

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

#print statement only executes if both conditions are true


if wonLottery and bigWin :
print("you can retire")

13
Combine conditions
#Imagine you have code that ran earlier which
#set these two variables
saturday = True
sunday = False

#print statement executes if either condition is true


if saturday or sunday :
print("you can sleep in")

• You can combine multiple and/or statements


• ‚and‘ is evaluated first
• Better use parenthesis

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

# the if statement is nested, so this if statement


# is only executed if the other if statement is true
if not freshCoffee :
print("go buy a coffee!")
print("I hate Mondays")
print("now you can start work")

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

• Can also be nested

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"

while answer != "4":


answer = input("What is 2 + 2 ")

print ("Yes! 2 + 2 = 4")

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']

#delete the first item in the list


del guests[0]

#print the first item in the list


print(guests[0])

22
Lists
guests = ['Christopher','Susan','Bill','Satya']

#4 values --> Create a loop that executes four times


for steps in range(4) :
print(guests[steps])

#or find out how many entries are in the list


nbrEntries = len(guests)

for steps in range(nbrEntries) :


print(guests[steps])

23
Lists
#this is really easy

guests = ['Christopher','Susan','Bill','Satya']

#specify the name of your list and a variable name


#to hold each entry as you go through the loop
for guest in guests :

#the variable guest will contain the values


#as we go through the loop
print(guest)

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.])

• You can also define the datatype


In [14]: ones(8, dtype=int)
Out[14]: array([1, 1, 1, 1, 1, 1, 1, 1])

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

def changeme( mylist ):


"This changes a passed list into this function"
mylist.append([1,2,3,4])
print("Values inside the function: ", mylist)
return #can also return a value

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print("Values outside the function: ", mylist)

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

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print("Values outside the function: ", mylist)

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;

# Now you can call sum function


total = sum( 10, 20 )
print("Outside the function : ", 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

• If ony specific modules are needed


from tensorflow import keras
from tensorflow.keras import layers

46
Running your code
• Running a python file
python my_python_file.py

• Without main function


• Each instruction in the provided file is executed one after the other
• With main function
• Defined entry point, where to start
• Can be helpful if modul should contain runnable code and library code
if __name__ == '__main__‘:
print_hi('PyCharm‘)

47
Summary
• Indention is important
• Default and keyword parameters
• Always called be reference
• Lists and numPy arrays are important for ai projects

48

You might also like