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!"

Loops

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):
    print(i)
This prints:
0
1
2
3

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

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

Exceptions

Handle exceptions with a try/except block

try:
    # 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.

Challenge

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.

Comments

  • I get the following compile error:

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

    cont...
  • @Iavor, you probably mean ==.

  • Thank you, I somehow missed that.

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