int
, float
, complex
for
if
/else
/elif
while
Classes, Objects, and Instances
Short version: Python 2.x is legacy, Python 3.x is the present and future of the language final
A Python interactive mode makes it easy to test short snippets of code, but there are also a bunch of editors like Sublime Text available as well as bundled development environments IDEs like PyCharm.
We will use:
You could use:
Analogy: Blueprint of a house
Example: the data type integer is a class
a = 5
) makes an instance (object) of class int
a
is a reference to this objectint
has methods defined, for example bit_length()
'This is a String'
) or multiline (''' This is a String...'''
)my_string[2] == 'i'
#create string
typo_str = 'Peeface'
#Oh no... a typo, not a good way to start a book, so change it
typo_str[1] = 'r'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-18-a40cf4edfc3f> in <module>()
----> 1 typo_str[1] = 'r'
TypeError: 'str' object does not support item assignment
In [ ]:
# print something
In [ ]:
print(c)
list_a = [5, 3.0, 'Hello']
0
list_a[2]
would give 'Hello'
#creating the list
list_a = [5, 3.0, 'Hello']
#extract third element/object and create reference to it
hello_str = list_a[2]
#mutate list
list_a[2] = 'Good bye'
#print new list
print(list_a)
[5, 3.0, 'Good bye']
In [ ]:
# what is hello_str
In [ ]:
# reverse indexing
In [ ]:
# stepwise indexing (start:stop:step)
tuple_a = (5 , 3.0, 'Hello')
#create tuple
tuple_a = (5, 3.0, 'Hello')
#extract third element/object and create reference to it
hallo_str = tuple_a[2]
#mutate it???
tuple_a[2] = 'Good bye'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-2ae0e9084ab6> in <module>()
----> 1 tuple_a[2] = 'Good bye'
TypeError: 'tuple' object does not support item assignment
In [ ]:
In [ ]:
my_dict = {'one':1, 'two':2, 'three':3}
print(my_dict['one'])
In [ ]:
# how to test if certain key is in dict
print('one' in my_dict)
print('four' in my_dict)
In [ ]:
### example immutable
x = 10
y = x
x = x + 1
print('y: ',y)
### example mutable
x_l = ['10']
y_l = x_l
x_l.append('11')
print('y_l: ', y_l)
True
or False
as result=
is an assignment, ==
is the comparison operatorand
, or
and not
for
Loopthe for
loop is used to iterate over a sequence
for x in y:
counter = counter +1
Loop continues until it reaches last item in y
Example: Sum of numbers
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum + val
if
/elif
/else
if x == 2: # expression
print(my_string) # statement
True
, statements will be executedif x == 2: # expression
print(my_string) # body of if
else:
print(your_string) # body of else
True
, statement in body of if will be executed, otherwise statement in body of else will be executedif x == 2: # 1st expression
print(my_string) # body of if
elif x == 3: # 2nd expression
print(our_string) # body of elif
else:
print(your_string) # body of else
elif
is short for else ifTrue
, statement in body of if will be executed, otherwise 2nd expression will be checked and so on...while
Loopwhile
iterates over a block of code, as long as a statement is True
Is used when the number of times the loop has to be executed is not known beforehand (compare: for
loop)
while x < 2: # expression
print(our_string)
expression is checked before entering the loop for the first time
def my_statement_printer(statements):
"""This is my docstring:
Function to print my statements"""
for statement in statements:
print('I think ' + statement)
def
is the keyword for the function definitionreturn
statement, if no return value is given the function returns None
def add(num1,num2):
"""This function adds two numbers"""
return num1 + num2
print(add(2,3))
print(add.__doc__)
return
statement exits a functionA variable defined inside a function is not visible outside the function
def func():
x = 10
print(x)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-fc17d851ef81> in <module>()
----> 1 print(x)
NameError: name 'x' is not defined
x
inside func
is not visible outside, so they can have the same namex
inside func is a local variable inside the function def add(num1,num2=1):
"""This function adds two numbers, if no second number is defined it adds one to num1."""
return num1 + num2
As already mentioned everything, that means every thing in python is an object. An object is an instance of a class, which defines which attributes and methods an object holds.
class
is the keyword for class
definitionclass
holds attributes (data and methods)dir
argument one can list all methods of an object
In [ ]:
y = 5
dir(y)
y
is not only a number, it has a lot of methods which we can use
In [ ]:
print(y.bit_length())
In [ ]:
import time
class MinimalCake:
def __init__(self, eier=2, mehl=500, milch=250):
self.eggs = eier
self.flour = mehl
self.milk = milch
self.stirred = False
def stir(self):
print('stirring...')
time.sleep(2)
print('...dough')
self.stirred = True
In [ ]:
one_minimal_cake = MinimalCake()
print(one_minimal_cake.eggs, one_minimal_cake.stirred)
In [ ]:
one_minimal_cake.stir()
print(one_minimal_cake.stirred)
Ok, we have dough. But it really doesn't taste well and it can't be baked... That's a disaster, we want choclate and sugar!!
Question: Is a MinimalCake object mutable or immutable?
Please write another class which holds attributes for choclate, sugar and whatever you want. Further, we should be able to bake it. But attention!!! If it is not stirred, baking it would be a waste.
In [ ]:
In [ ]:
In [ ]:
In [ ]: