In [1]:
x_int = 3
x_float = 3.
x_string = 'three'
x_list = [3, 'three']
In [2]:
type(x_float)
Out[2]:
In [3]:
type(x_string)
Out[3]:
In [4]:
type(x_list)
Out[4]:
In [5]:
abs(-1)
Out[5]:
In [6]:
import math
math.floor(4.5)
Out[6]:
In [7]:
math.exp(1)
Out[7]:
In [8]:
math.log(1)
Out[8]:
In [9]:
math.log10(10)
Out[9]:
In [10]:
math.sqrt(9)
Out[10]:
In [11]:
round(4.54,1)
Out[11]:
If this should not make sense, you can print some documentation:
In [12]:
round?
In [13]:
string = 'Hello World!'
string2 = "This is also allowed, helps if you want 'this' in a string and vice versa"
len(string)
Out[13]:
In [14]:
print(string)
print(string[0])
print(string[2:5])
print(string[2:])
print(string[:5])
print(string * 2)
print(string + 'TEST')
print(string[-1])
In [15]:
print(string/2)
In [16]:
print(string - 'TEST')
In [17]:
print(string**2)
capitalizing strings:
In [18]:
x = 'test'
In [19]:
x.capitalize()
Out[19]:
In [20]:
x.find('e')
Out[20]:
In [21]:
x = 'TEST'
x.lower()
Out[21]:
Enviromnents like Jupyter and Spyder allow you to explore the methods (like .capitalize()
or .upper()
using x.
and pressing tab
.
In [22]:
print('Pi is {:06.2f}'.format(3.14159))
print('Space can be filled using {:_>10}'.format(x))
With python 3.6 this became even more readable
In [23]:
print(f'{x} 1 2 3')
In [24]:
x_list
Out[24]:
In [25]:
x_list[0]
Out[25]:
In [26]:
x_list.append('III')
x_list
Out[26]:
In [27]:
x_list.append('III')
x_list
Out[27]:
In [28]:
del x_list[-1]
x_list
Out[28]:
In [29]:
y_list = ['john', '2.', '1']
y_list + x_list
Out[29]:
In [30]:
x_list*2
Out[30]:
In [31]:
z_list=[4,78,3]
max(z_list)
Out[31]:
In [32]:
min(z_list)
Out[32]:
In [33]:
sum(z_list)
Out[33]:
In [34]:
z_list.count(4)
Out[34]:
In [35]:
z_list.append(4)
z_list.count(4)
Out[35]:
In [36]:
z_list.sort()
z_list
Out[36]:
In [37]:
z_list.reverse()
z_list
Out[37]:
In [38]:
y_tuple = ('john', '2.', '1')
type(y_tuple)
Out[38]:
In [39]:
y_list
Out[39]:
In [40]:
y_list[0] = 'Erik'
y_list
Out[40]:
In [41]:
y_tuple[0] = 'Erik'
In [42]:
tinydict = {'name': 'john', 'code':6734, 'dept': 'sales'}
type(tinydict)
Out[42]:
In [43]:
print(tinydict)
print(tinydict.keys())
print(tinydict.values())
In [44]:
tinydict['code']
Out[44]:
In [45]:
tinydict['surname']
In [46]:
tinydict['dept'] = 'R&D' # update existing entry
tinydict['surname'] = 'Sloan' # Add new entry
In [47]:
tinydict['surname']
Out[47]:
In [48]:
del tinydict['code'] # remove entry with key 'code'
In [49]:
tinydict['code']
In [50]:
tinydict.clear()
del tinydict
When duplicate keys encountered during assignment, the last assignment wins
In [51]:
dic = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
dic
Out[51]:
Finding the total number of items in the dictionary:
In [52]:
len(dic)
Out[52]:
Produces a printable string representation of a dictionary:
In [53]:
str(dic)
Out[53]:
In [54]:
def mean(mylist):
"""Calculate the mean of the elements in mylist"""
number_of_items = len(mylist)
sum_of_items = sum(mylist)
return sum_of_items / number_of_items
In [55]:
type(mean)
Out[55]:
In [56]:
z_list
Out[56]:
In [57]:
mean(z_list)
Out[57]:
In [58]:
help(mean)
In [59]:
mean?
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. In Python a block is delimitated by intendation, i.e. all lines starting at the same space are one block.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
In [60]:
count = 0
while (count < 9):
print('The count is: ' + str(count))
count += 1
print('Good bye!')
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.
In [61]:
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print('Current fruit :', fruit)
Sometimes one also needs the index of the element, e.g. to plot a subset of data on different subplots. Then enumerate
provides an elegant ("pythonic") way:
In [62]:
for index, fruit in enumerate(fruits):
print('Current fruit :', fruits[index])
In principle one could also iterate over an index going from 0 to the number of elements:
In [63]:
for index in range(len(fruits)):
print('Current fruit:', fruits[index])
for
loops can be elegantly integrated for creating lists
In [64]:
fruits_with_b = [fruit for fruit in fruits if fruit.startswith('b')]
fruits_with_b
Out[64]:
This is equivalent to the following loop:
In [65]:
fruits_with_b = []
for fruit in fruits:
if fruit.startswith('b'):
fruits_with_b.append(fruit)
fruits_with_b
Out[65]:
In [66]:
for x in range(1, 3):
for y in range(1, 4):
print(f'{x} * {y} = {x*y}')
In [67]:
x = 'Mark'
if x in ['Mark', 'Jack', 'Mary']:
print('present!')
else:
print('absent!')
In [68]:
x = 'Tom'
if x in ['Mark', 'Jack', 'Mary']:
print('present!')
else:
print('absent!')
We can also use one or more elif
statements to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE
In [69]:
x = 'Tom'
if x in ['Mark', 'Jack', 'Mary']:
print('present in list A!')
elif x in ['Tom', 'Dick', 'Harry']:
print('present in list B!')
else:
print('absent!')
else
statements can be also use with while
and for
loops (the code will be executed in the end)
You can also use nested if
statements.
It terminates the current loop and resumes execution at the next statement. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
In [70]:
var = 10
while var > 0:
print('Current variable value: ' + str(var))
var = var -1
if var == 5:
break
print('Good bye!')
The continue
statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop (like a "skip").
The continue statement can be used in both while
and for
loops.
In [71]:
for letter in 'Python':
if letter == 'h':
continue
print('Current Letter: ' + letter)
The pass
statement is a null operation; nothing happens when it executes. The pass
is also useful in places where your code will eventually go, but has not been written yet
In [72]:
for letter in 'Python':
if letter == 'h':
pass
print('This is pass block')
print('Current Letter: ' + letter)
print('Good bye!')
pass
and continue
could seem similar but they are not. The printed message "This is pass block", wouldn't have been printed if continue had been used instead. pass
does nothing, continue
goes to the next iteration.
In [73]:
for letter in 'Python':
if letter == 'h':
continue
print('This is pass block')
print('Current Letter: ' + letter)
print('Good bye!')