And don't forget that with Python, programming is fun again!
In [4]:
print("Hello, world!")
In [5]:
2 + 3
Out[5]:
In [6]:
5 * (7 + 2)
Out[6]:
You can assign numbers to variables:
In [7]:
width = 5
height = 2 + 6
width * height
Out[7]:
You can change variables:
In [8]:
height = 12
width * height
Out[8]:
mc_wheels is better than just wheels or number_of_wheels_on_a_motorycle.l and the uppercase letters O and I in places where they could be confused with the numbers 1 and 0. And never use them as single character variable names.You'll have to be careful about the datatype (sometimes)
In [9]:
width / 2
Out[9]:
In [10]:
width // 2
Out[10]:
You can convert an int to a float:
In [11]:
float(width)
Out[11]:
This kind of type casting works for most datatypes in Python!
In [12]:
bla = 'bla bla bla'
bla
Out[12]:
In [13]:
print(bla)
In [14]:
blub = "bla blub"
print(blub)
This allows you to make strings that contain quotations.
In [15]:
quote = "Linus Torvalds once said, 'Any program is only as good as it is useful.'"
print(quote)
Use \ to continue your command on the next line.
In [16]:
bla = 'bla bla\
bla bla'
print(bla)
Use \n to put a newline into the string.
In [17]:
bla = 'bla bla\n\
bla bla'
print(bla)
Or use multi line strings in triple quotes (either ''' or """) to do both.
In [18]:
bla = '''bla bla
bla bla'''
print(bla)
You can concatenate strings:
In [19]:
blub = 'bla ' + blub
blub
Out[19]:
In [20]:
blub * 3
Out[20]:
In Ipython (and Ipython Notebook) you can see all the string functions by tabbing them.
In [21]:
blub.title?
In [22]:
blub.title()
Out[22]:
In [23]:
my_unicode = 'Hellö World!'
my_unicode
Out[23]:
Some unicode strings can not be cast to strings.
While most Error messages are easy to understand, it might also be a good idea, to google (or whatever) them. Other questions occuring during programming are also likely to have been asked before (so, google!). Answers on stackoverflow.com are often useful.
If you absolutely want to convert to string, you can do it like that:
In [24]:
my_list = blub.split()
my_list
Out[24]:
Lists can be indexed and sliced.
In [25]:
my_list[0]
Out[25]:
In [26]:
my_list[-1]
Out[26]:
In [27]:
my_list = my_list + ['more', 'and', 'more', 'words', 'plus', 'a', 'number', 4]
my_list
Out[27]:
In [28]:
my_list[2:6]
Out[28]:
In [29]:
my_list[0:2]
Out[29]:
In [30]:
my_list[:2]
Out[30]:
In [31]:
my_list[4:-2]
Out[31]:
In [32]:
my_list[4:-2:3]
Out[32]:
The indexing and slicing works for all built-in sequence types. (Also strings!)
In a list, you can change elements or slices. (Lists are mutable, strings for example are immutable.)
In [33]:
my_list[-4:] = ['a']
my_list
Out[33]:
You can add new items to the end of the list with the append() method:
In [34]:
my_list.append(4)
my_list
Out[34]:
You can nest lists:
In [35]:
nested = [my_list, ['another', 'list']]
nested
Out[35]:
In [36]:
nested[1][0]
Out[36]:
In [37]:
my_list
Out[37]:
In [38]:
my_set = set(my_list)
my_set
Out[38]:
In [39]:
'bla' in my_list
Out[39]:
In [40]:
'turtle' in my_set
Out[40]:
In [41]:
phonebook = {'Max': 8389, 'Jannis': 8389, 'Thomas': 8325}
phonebook['Max']
Out[41]:
In [42]:
phonebook['Katharina'] = 8592
phonebook
Out[42]:
In [43]:
phonebook.keys()
Out[43]:
In [44]:
if 1:
print('yes!')
If the boolean statement is True, the code below is executed.
In [45]:
x = int(input("Please enter an integer: "))
In [46]:
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
In [47]:
if []:
print('empty list!')
print('Never True!')
In [48]:
if not []:
print('That list isn\'t empty!')
print('Always True!')
You should use 4 spaces, not a tab!!
If you are presenting your code, be sure the indentation is right!
In [49]:
i = 5
while i > 0:
print(i**2)
i = i - 1
In [50]:
my_list
Out[50]:
In [51]:
for element in my_list:
print(element, len(element))
In [52]:
my_first_lc = [len(element) for element in my_list[:-1]]
my_first_lc
Out[52]:
In [ ]:
range?
In [ ]:
range(4)
In [ ]:
range(4,9)
In [ ]:
list(range(4, 9, 2))
range() is often used in for-loops
In [ ]:
for i in range(len(my_list)):
print(i, my_list[i])
But using xrange() is the smarter solution. It does not return a list, but an object generating the numbers on demand. In Python 3, there is only range(), but behaving like xrange(). So, if you need the list, type list(range(4)).
And always keep in mind, that you can loop over the elements in a list in an easy, pythonic way. No need to use the indices.
In [ ]:
for i in range(len(my_list)): # NOOOO!
print(my_list[i])
for element in my_list: # YES!!
print(element)
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
In [ ]:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
The continue statement, also borrowed from C, continues with the next iteration of the loop:
In [ ]:
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
In [ ]:
x = int(input("Please enter an integer: "))
In [ ]:
if x < 0:
pass
elif x == 42:
pass #TODO must fill the answer to life, the universe, and everything here later
else:
print('More')
In [ ]:
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n.""" # docstring
a, b = 0, 1 # multiple assignement
while a < n:
print(a, end=' ') # prevents the newline
a, b = b, a+b # another multiple assignement
fib(500)
The keyword def introduces a function definition. It has to be followed by the function name and the paranthesized list of formal parameters.
In [ ]:
def fib2(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
f100 = fib2(100) # call it
f100 # write the result
The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.
In [ ]:
def parrot(voltage, state='a stiff', action='voom', type_='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type_)
print("-- It's", state, "!")
parrot(1000) # 1 positional argument
state, action, and type_ have default values, so they can be omitted from the function call.
In [ ]:
parrot(voltage=1000, action='jump') # 2 keyword arguments
You can call the function using keyword arguments, positional arguments, or mix both.
In [ ]:
parrot('a lot of', 'bereft of life') # 2 positional arguments
In [ ]:
parrot('a lot of', type_='Lory', state='pushing up the daisies') # 1 positional and 1 keyword argument
The sentences are actually from a Monty Pythons episode. You can watch it later: https://www.youtube.com/watch?v=4vuW6tQ0218
In [ ]:
my_list[20]
Exceptions come in different types, which are given in the message. The type of this exception is IndexError.
So, let's handle that exception!
In [ ]:
def handle_index_error(i):
try:
print(my_list[i])
except IndexError:
print(my_list[-1])
handle_index_error(20)
In [ ]:
handle_index_error(5)
In [ ]:
handle_index_error('some useless string')
Style guide for Python code
A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.
In [ ]:
spam(ham[1], {eggs: 2}) # YES!
spam( ham[ 1 ], { eggs: 2 } ) # NO!!
x, y = y, x # YES!
x , y = y , x # NO!!
counter = counter + 1 # YES!
counter=counter+1 # NO!!
result = add(x+1, 3) # YES!
result = add(x + 1, 3) # YES!
def complex(real, imag=0.0): # YES!
return magic(r=real, i=imag)
def complex(real, imag = 0.0): # NO!!
return magic(r = real, i = imag)
And of course, there is more: https://www.python.org/dev/peps/pep-0008/
In [ ]:
import this