Learning Python: Functions and if-statements

Hey and welcome to my second blog on python programming. Today we're going to talk about functions and if-statements. In the last tutotial I forgot to mention, how to actually execute python code. There are two ways:
  1. using the Interpreter: open up your console and just type 'python' (each line of code gets immeditialy executed)
  2. save your code in a .py-file, open up your console and type 'python <filename.py>' 


Functions in Python

Functions do we know already from math. We put some numbers in them and receive an output. Let's define a function called f(x) = x² and take 4 as input (argument). We get f(4) = 16 as output. Now in python:
def f(x):
  return x**2
In the first line we have our function definition. 'def' is a keyword in python and it needs a function name with parentheses and a colon afterwards. In the parentheses we can put our argument variables. Line 2 is intended, shows another keyword 'return' and the actual operation. Python works with whitespaces or indentations to signify what belongs to the function body. The function evaluates to the value behind the 'return' expression, that means we can assign functions to variables. After defining a function, python doesn't execute this function, it's just stored in memory. We have to actually call it:
output = f(4)         # output = 16  
Okay let's talk about local and global variables. All variables defined within the function including the argument variables are just available in the function. These are local variables. In comparison global variables are defined in every scope:
g = 5

def foo(x,y):
  a = x + g        # g is global; a,x,y are local variables
  return a * y     # works, because a and y are in the scope of the function

val1 = a           # a isn't defined outside the function (error) 
val2 = x           # x also not defined in that scope (error)
val3 = g           # val3 = 5 (g is global)
We can also create functions without the keyword 'return' . The function won't return anything and it wouldn't make sense to assign variables to them. When should this be useful? The answer is, if we have to repeat code over and over again. We can wrap this code inside a function and just need to call it:
def show_calculation(x,y):
  z = x * y
  z += 5
  result = z - 3
  print(result)

show_calculation(1,2)
show_calculation(3,3)

>>> 4
11
This function doesn't make sense at all, but you get the point. Maybe you didn't understand the difference between "return" and "print", just check this simple example:
def f(x):
  return x

def g(x):
  print(x)

result1 = f(3)          # result1 = 3
result2 = g(5)          # result2 = None

>>> 5
Okay result1 should be clear. We put in 3 and return 3.  Now if we call g(5), we also call print(5) and show 5 on the console, but g doesn't return anything, that's why result2 has no value. Actually it has the value 'None', which is a data type in python, what represents, having no value. It's a little bit confusing, but this type is very useful in python.
We mentioned in many of these code snippets the function 'print'. This function is built in python. There are many more of this kind. Here are some very useful python built-in functions:
name = "Peter"
length = len(name)          # length = 5 (len counts the number of characters)
word = str(5)               # word = "5"  (str turns everything into a string)
integer = int(4.3)          # integer = 4
num = int("45")             # num = 45 (int also parses strings into integers)

print(name + " " + word)

>>> Peter 5
There are much more built-in functions, but these are some useful ones. That's basically all you need to know about functions.


if-statements in Python

We talked about booleans in the last blog. They are essential for if-statements. In simple terms if-statements check, if the statement is either true or false and than take some action:
x = 3
y = 5

if x != y:                       # x != y evaluates to True
  print("x doesn't equal y")

>>> x doesn't equal y
With the keyword 'if' we start our if-statement. Then we need a boolean expression ('True', 'False') and a colon at the end. If the expression evaluates to 'True' then we execute everything in the body of the if-statement. Now we can also do this:
x = 3
y = 3

if x != y:                       # x != y evaluates to False
  print("x doesn't equal y")
else:                            # else-block is called
  print("x equals y")

>>> x equals y
The if-statement evaluates to 'False', that's why the else-block is executed. 'else' is always called, if the if-block evaluates to 'False'. Then there is this last thing:
x = 5
y = 4

if x < y:                       # x < y evaluates to False
  print("x is less than y")
elif x > y:                     # x > y evaluates to True
  print("x is greater than y")
else:                           # else-block is not called
  print("x equals y")

>>> x is greater than y
If we want to check mutliple statements, then we can add a elif-block. 'elif' is another keyword and means 'else if'. Again if all conditions are 'False', then the else-block is executed, otherwise not.

In this tutorial you learned some very useful tools. Now I want to show you an example of what cool stuff you can already build:
def minimum(x,y):
  if x < y:
    return x
  else:
    return y

print(minimum(2,7))

>>> 2

Check out my last blog, if you still struggle with the basics. Anyway, I hope you enjoyed it and learned something from it.

Comments