- Python Basics
- Control Flow
- Generators and Decorators
- Python Next
Example code based on
and licensed under
CC Attribution-Share 3
# 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)
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)
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
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.
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
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:
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Iavor DekovMar 21, 10:58 PM
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
py_compile.PyCompileError: SyntaxError: ('invalid syntax', ('prog.py', 5, 12, '\t\tif i % 3 = 0:\n'))
What could the problem be?
LearnerooMar 22, 8:44 PM
@Iavor, you probably mean
Iavor DekovMar 22, 8:49 PM
Thank you, I somehow missed that.
FeiJul 29, 5:36 PM
It works on my computer interpreter, but at here got a syntax error,SyntaxError: invalid syntax.
FeiJul 29, 5:45 PM
#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.