> For the complete documentation index, see [llms.txt](https://python.microcisco.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://python.microcisco.com/python-bootcamp/100-days/day-6-python-functions-and-karel.md).

# Day 6: Python Functions and Karel

Functions, Code Blocks and While Loops

## Resource:&#x20;

[Reeborg's World](https://reeborg.ca/reeborg.html?lang=en\&mode=python\&menu=worlds%2Fmenus%2Freeborg_intro_en.json\&name=Alone\&url=worlds%2Ftutorial_en%2Falone.json)

## Functions

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMZb7HoxgGnXK7UTJm3%2F-MMfPt6uLdtm-nR5Bmfe%2Fimage.png?alt=media\&token=b9bbfbbf-fd93-47db-9e28-c8b22e8d9d89)

As seen above these are some of the built-in functions that python provides. \
Functions are defined as a word or name followed by parenthesis such as **`print( )`** etc.

NOW !!! What if we wanted to make our OWN functions??? OK, cool - but HOW??

To make our own function we need to DEFINE it by using the keyword\
&#x20;**`def <name> ( )`**  for example **def my\_function( ): -------> dont forget the colon!!!**

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMZb7HoxgGnXK7UTJm3%2F-MMgANy-T0iem9y_eQgO%2Fimage.png?alt=media\&token=884622f8-0ac9-4ec3-a318-cb1b5a4e48bd)

The function is like creating a recipe and then storing it for later. When you need it you **"call"** the function (recipe) by specifying the name and a set of parentheses  and this is then activated.\
Instead of having to write out the whole recipe EVERY time you need it somewhere in your code, you just pull it out when you need it and this saves you loads of time and make your code easier to read.

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMgpDhLlp_bW5ssxWUP%2F-MMgqX8PLcUmWvW989Wz%2Fimage.png?alt=media\&token=a996a135-6ca1-4900-b76e-bef339814c93)

{% tabs %}
{% tab title="Code" %}

```
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def steps():
    move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()

for jump in range(6):
    steps()
```

{% endtab %}
{% endtabs %}

## While Loops

The while loop, the loop that will continue going while a particular condition is TRUE!

We have seen 2 flavours of the "FOR loop:

* One, where we are looping through a **LIST** of items to do something with each item in that list.
  * **`for item in list-of-items:`**\
    &#x20;  **`do something to each item`**
* and the other is using a RANGE function where we create a range between  a and b , and then we use every number in that range to do something.&#x20;

  * **`for number in range(a ,b)`**\
    &#x20;   **`print(number)`**

  &#x20;              &#x20;

The WHILE loop can be written as

* **`while something something_is_true:`**\
  &#x20;    **`do something repeatedly unti the condition chnages to FALSE and then it will jump out of the loop`**

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMyXy70jKiEdMnlPB-W%2Fimage.png?alt=media\&token=61f2abb3-73e3-4234-b970-4cdfe621bb62)

{% tabs %}
{% tab title="Code 2" %}

```
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def steps():
    move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()

number_of_hurdles = 6
while number_of_hurdles > 0:
    steps()
    number_of_hurdles -= 1
    print(number_of_hurdles)
```

{% endtab %}
{% endtabs %}

### Example:1

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMy_TxIQBkssp16qldC%2Fimage.png?alt=media\&token=202f6b18-50d4-4024-bbc3-d20cef5ca5cf)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMysgoj68XRndbUM9Bj%2Fimage.png?alt=media\&token=bb5c6185-0823-4bd2-8c8f-1135f56f7ec0)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMyv90TQxUUSQIlFYQ8%2Fimage.png?alt=media\&token=8e0b5ccf-be9f-4e28-b5bd-54dd35afcc12)

### When to use For Loops and When to use  While  Loops:

Remember - for loops are good for iterating over something and you need to do something  with each thing you are **iterating over**. So for example we are iterating through a list of fruits and we want to **DO SOMETHING WITH EACH** of the items in the list we have to use FOR LOOPS

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMzCIJcwmEG1ftQTBsa%2Fimage.png?alt=media\&token=2c2dad8c-e758-4ed9-8b12-2e840b64d559)

Similarly we have use the RANGE function such as the one below, its easier to do with a FOR LOOP than a WHILE loop

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMzDTeGC7a5jerJoGvK%2Fimage.png?alt=media\&token=7d23d85b-785f-4cfa-8a6a-8664360e86a6)

Now you want to be using a WHILE loop when you don't really CARE what number in a sequence you're in, which item you are iterating through in a list or you just simply want  to carry out some sort of functionality many, many times until some sort of condition that you set has been achieved or met.

{% hint style="danger" %}
"While Loops" are more dangeorus than "FOR loops" because in FOR Loops you're setting ahead of time how many times something is going to run. Its going to stop once it reaches the end of a list of items in this case and if the For Range loop it will stop once it reaches the upper bound of the range.\
BUT ....for "WHILE" loops, they will continue running until a particular condition switches either from True to False or False to True. If a condition somehow never switches you could be caught in an **INFINITE LOOP**
{% endhint %}

### Example 2

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MMzKS6qwZFdZlWqCjC0%2Fimage.png?alt=media\&token=dbd003a4-8d79-4402-acb2-dab54c5181ca)

***REMEMBER IF STATEMENTS CAN GO INSIDE LOOPS -- IDIOT!!!!!***

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN-tVsSrqwyE6o6hTfq%2Fimage.png?alt=media\&token=05409b7b-cb49-402c-b29d-897523671066)

{% tabs %}
{% tab title="Code - Hurdle 3" %}

```
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def steps():
    #move()
    turn_left()
    move()
    turn_right()
    move()
    turn_right()
    move()
    turn_left()


#while at_goal() != True:
#    steps()
#print(at_goal)

while not at_goal():
    if wall_in_front():
        steps()
    else:
        move()
```

{% endtab %}
{% endtabs %}

### Example 3:

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN04hfI5vC8dg2htbFE%2Fimage.png?alt=media\&token=e92ad845-3ed1-4263-b4e5-291e1ae675c0)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN04QqeEs6T_YejJwpW%2Fimage.png?alt=media\&token=8d320f69-124e-4033-954d-36c40efe0899)

{% tabs %}
{% tab title="Hurdles 4" %}

```
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
def steps():
    #move()
    turn_left()
    while wall_on_right():
        move()
        
    turn_right()
    move()
    turn_right()
    while front_is_clear():
        move()
    turn_left()
 
#while at_goal() != True:
#    steps()
#print(at_goal)

while not at_goal():
    if wall_in_front():
        steps()
    else:
        move()

```

{% endtab %}
{% endtabs %}

## Project of the Day: Escaping the Maze

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN07eWcOC2S6MLPnToY%2Fimage.png?alt=media\&token=c8377159-14d9-4930-9c69-7eabc7a39b58)

There are a few things here at play:

* At the start of play, the direction the robot is going to face is random
* The position of the robot within in the maze will also be random
* The secret to complete the maze (see above) is to have the robot move along the right edge of the maze, TURNING RIGHT if it can and going STRAIGHT AHEAD if it cant turn right and turning LEFT as the last resort

By doing this will eventually get you to the destination. This is called a **STRATEGY** or rather in **programming called an ALGORITHM**.

So **following along the right side of the wall, and if the RIGHT side is CLEAR, to CONTINUE moving right until its no longer clear at which point it should turn LEFT**<br>

### Step1: Turn Right

This step is to define a function - using the **`def <name>()`** method,  of turning right

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN0MX1FUkOj9Xsq5vJo%2Fimage.png?alt=media\&token=ded115a7-f1d0-49e1-9d85-a26f76081171)

### Step2:

The next thing to do, is we need to tell the robot to do things and to check for things until it reaches its goal. So we use a "while loop" to get the robot to continue working until it reaches the goal. To define that we will say **`while not at_goal():`** *(*&#x62;asically keep repeating the instructions inside this "while loop" until  **`at_goal`** becomes TRUE )

So what we were told was to follow along the right edge. We should test to see if the right side is clear, and if it is we should turn right and go straight\
Lest use an "if statement" to test **`if right_is_clear():`** we are going to turn right and then once facing right, to move forward.

![Stuck in an infinite loop !!](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN0RGrdVbGpR2Q_usy6%2Fimage.png?alt=media\&token=3ee90cf7-6a58-4447-a71a-b32b8d184dc6)

To fix this we need an alternative condition, when the RIGHT is not clear, what should it do? So we will provide an **`elif`** statement, saying, "if the right is NOT clear, maybe we should check if the FRONT is clear? If it is then simply move forwards

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN0U0_Y3aghbEJCCOH-%2Fimage.png?alt=media\&token=9e4cba00-8cb1-4a21-9552-54e77d453971)

![](https://3018064759-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LudO0LP3BbNbyBiBB3l%2F-MMyIhOnpQZJH0OhGSGi%2F-MN0UkrY1rtL0bZktDNS%2Fimage.png?alt=media\&token=da5a734c-1a7d-45e2-ad0a-d778cd7e2658)

```
def turn_right():
    turn_left()
    turn_left()
    turn_left()
    

while not at_goal():
    if right_is_clear():
        turn_right()
        move()
    
    elif front_is_clear():
            move()
            
    else:
        turn_left()
```
