- Python Basics
- Collections
- Control Flow
- Functions
- Classes
- Modules
- Generators and Decorators
- Python Next
Example code based on
LearnXinYminutes
and licensed under
CC Attribution-Share 3
Control Flow
Collapse Content
Show 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
Iavor Dekov
Mar 21, 10:58 PMI 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?
Learneroo
Mar 22, 8:44 PM@Iavor, you probably mean
==
.Iavor Dekov
Mar 22, 8:49 PMThank you, I somehow missed that.
Fei
Jul 29, 5:36 PMIt works on my computer interpreter, but at here got a syntax error,SyntaxError: invalid syntax.
Fei
Jul 29, 5:45 PMdef do_stuff(ar):
#print array if you want:
str1 = ""
for n in ar:
if n%3 == 0:
str1 = str1 + "no3"+" "
else:
str1 = str1 + str(n) +" "
print(str1)
A correct but ugly answer.