Please enable JavaScript to use CodeHS

Karel's Built in Commands

Commands

move()
Python
 
turn_left()
Python
put_ball()
Python
 
take_ball()
Python

Functions

Writing a Function

Writing a function is like teaching karel a new word.

Naming Functions: You can name your functions whatever you want, but you can't have spaces in the function name.

Remember that commands in functions must be indented one level

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

def turn_around():
    turn_left()
    turn_left()

def your_function_name():
  # Code that will run when you make a call to
  # this function.
Python

Calling a Function

You call a function to tell the computer to actually carry out the new command.

# Call the turn_around() function once
turn_around()

# Call the turn_right() function 2 times
turn_right()
turn_right()
Python

Conditional Statements

Remember that commands in conditional statements must be indented one level.

If statements

if condition:
    #code that will run if the condition is true
Python

If/Else statements

if condition:
    #code that will run if the condition is true
else:
    #code that will run if condition is not true
Python

Example of if statements

if front_is_clear():
  move()

if balls_present():
  take_ball()
else:
  move()
Python

Karel Conditions

Don't forget the () at the end!
front_is_clear()
left_is_clear()
right_is_clear()

facing_north()
facing_south()
facing_east()
facing_west()

balls_present()
            
Python
 
front_is_blocked()
left_is_blocked()
right_is_blocked()

not_facing_north()
not_facing_south()
not_facing_east()
not_facing_west()

no_balls_present()
            
Python

Loops

Remember that commands in a loop statement must be indented one level.

While Loops

while CONDITION:
  # Code that will run while the CONDITION is true.
  # Once the CONDITION is no longer true,
  # it will stop.
Python

Example of while loops

# This moves Karel to a wall
while front_is_clear():
    move()
Python

For Loops

for i in range(COUNT):
  # Code that will run 'COUNT' times
Python

Example of for loops

# This puts down 10 balls */
for i in range(10):
    put_ball()
Python
You can have multiple statements or function calls in a for loop.
# This puts down five balls and moves after each one
for i in range(5):
    put_ball()
    move()
Python
Use for-loops when you want to repeat something a fixed number of times.
Use while-loops when you want to repeat something as long as a condition is true.

Comments

Comments

"""
A multi-line comment describes your code
to someone who is reading it.
"""

# Use single line comments to clarify code.
Python