Loops
#
# loops.py
#
# Lists are declared with the square brackets, and may contain
# objects with different types.
= [7, 4.20, "juggling ball", True]
things print("things:", things)
# List indexing is 0-based, just like Java.
print("things[0]:", things[0])
print("things[2]:", things[2])
# You can also give index ranges, resulting in a "slice" of the
# list, and negative indices which count from the end.
print("things[0:2]", things[0:2])
print("things[-1]:", things[-1])
print("things[-2]:", things[-2])
# The Python for loop to iterate through a list is similar to the
# Java for-each loop.
# Important difference from Java: Python uses the colon followed by
# indented code to indicate scope, where Java uses the curly braces
# {}. You can indent any amount, but you must be consistent within
# the scope.
print("printing items")
for item in things:
print("item:", item)
# You can also use the range() function to iterate through a range
# of integers. range(begin, end) returns the integers in the
# half-open interval [begin,end). range(end) is shorthand for
# range(0, end). You can also specify a step parameter:
# range(begin, end, step).
print("printing range(5)")
for x in range(5):
print("x:", x)
print("printing range(11, 20, 2)")
for x in range(11, 20, 2):
print("x:", x)
# Conditions are checked with `if`, with scope specified by
# indentation as with `for`.
# Note that = and == are the similar to Java:
# = is assignment
# == is comparison (returns a boolean)
# However, Python is different from Java in that == compares
# values, not references.
print("printing with conditions")
for i in range(10):
if i%2 == 0:
print("Even")
elif i == 7: # "else if" in Java
print("Lucky")
else:
print(i)
Output:
things: [7, 4.2, 'juggling ball', True]
things[0]: 7
things[2]: juggling ball
things[0:2] [7, 4.2]
things[-1]: True
things[-2]: juggling ball
printing items
item: 7
item: 4.2
item: juggling ball
item: True
printing range(5)
x: 0
x: 1
x: 2
x: 3
x: 4
printing range(11, 20, 2)
x: 11
x: 13
x: 15
x: 17
x: 19
printing with conditions
Even
1
Even
3
Even
5
Even
Lucky
Even
9