Introduction to Python for Developers
George Boorman
Curriculum Manager, DataCamp
# Prices list prices = [9.99, 8.99, 35.25, 1.50, 5.75]
prices[0] > 10
False
prices[0] < 5
False
prices[0] >= 5 and prices[0] <= 10
True
for value in sequence:
action
for
each value
in sequence
, perform action
action
is indented because of the colon in the previous linesequence
= iterable e.g., list, dictionary, etc
value
= iterator, i.e., the indexi
is common.# Prices list prices = [9.99, 8.99, 35.25, 1.50, 5.75]
# Print each value in prices for price in prices:
print(price)
9.99
8.99
35.25
1.5
5.75
for price in prices:
for price in prices:
# Check if the price is more than 10 if price > 10:
for price in prices:
# Check if the price is more than 10 if price > 10: print("More than $10")
for price in prices:
# Check if the price is more than 10 if price > 10: print("More than $10") # Check if the price is less than 5 elif price < 5: print("Less than $5")
for price in prices:
# Check if the price is more than 10 if price > 10: print("More than $10") # Check if the price is less than 5 elif price < 5: print("Less than $5") # Otherwise print the price else: print(price)
9.99
8.99
More than $10
Less than $5
5.75
username = "george_dc"
# Loop through username and print each character for char in username: print(char)
g
e
o
r
g
e
_
d
c
products_dict = {"AG32":87.99, "HT91":21.50, "PL65":43.75, "OS31":19.99, "KB07":62.95, "TR48":98.0}
# Loop through keys and values for key, val in products_dict.items(): print(key, val)
AG32 87.99
HT91 21.5
PL65 43.75
OS31 19.99
KB07 62.95
TR48 98.0
# Loop through keys
for key in products_dict.keys():
print(key)
AG32
HT91
PL65
OS31
KB07
TR48
# Loop through values
for val in products_dict.values():
print(val)
87.99
21.5
43.75
19.99
62.95
98.0
for
loops to update variablesrange(start, end + 1)
start
= inclusiveend
= not inclusivefor i in range(1, 6):
print(i)
1
2
3
4
5
# No visits yet visits = 0
# Loop through numbers 1-10 for i in range(1, 11):
# Add one to visits during each iteration visits += 1 # Same as visits = visits + 1
print(visits)
10
Introduction to Python for Developers