Control Flow

Collapse Content

If Statement

# Here's a variable
some_var = 5

# Here is an if statement. Indentation is significant in python!
# prints "some_var is smaller than 10"
if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # This elif clause is optional.
    print("some_var is smaller than 10.")
else:           # This is optional too.
    print("some_var is indeed 10.")

# if can be used as an expression
"great!" if some_var > 2 else "small" #=> "great!"


For loops iterate over lists.

for animal in ["dog", "cat", "mouse"]:
    # You can use % to interpolate formatted strings
    print("%s is a mammal" % animal)

This prints:

dog is a mammal
cat is a mammal
mouse is a mammal

range(number) returns a list of numbers from zero up to the given number

for i in range(4):
This prints:

While loops go until a condition is no longer met. This will print the same as the above:

x = 0
while x < 4:
    x += 1  # Shorthand for x = x + 1


Handle exceptions with a try/except block

    # Use "raise" to raise an error
    raise IndexError("This is an index error")
except IndexError as e:
    pass    # Pass is just a no-op. Usually you would do recovery here.


You will be given an list of numbers ar. Print each number in the order it appears, unless the number is a multiple of 3. If a number is a multiple of 3, print no3 instead.

Make sure to print everything in a given list on the same line. Note: Add a comma after print to print without adding a newline: print("hi"),

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.


  • I get the following compile error:

    Traceback (most recent call last):
    File "", line 1, in
    File "/usr/lib/python2.7/", line 117, in compile

  • @Iavor, you probably mean ==.

  • Thank you, I somehow missed that.

  • for n in ar:
        if n%3 == 0:
            print("no3",end=" ")
            print(n,end=" ")

    It works on my computer interpreter, but at here got a syntax error,SyntaxError: invalid syntax.

  • def do_stuff(ar):
    #print array if you want:
    str1 = ""
    for n in ar:
    if n%3 == 0:
    str1 = str1 + "no3"+" "
    str1 = str1 + str(n) +" "
    A correct but ugly answer.

Contact Us
Sign in or email us at [email protected]