TCM PEH Python Notes B
Conditional Statements
if the conditions are met, then this result
def drink(money):
…if money >= 2:
…,return “You got yourself a drink”
…else:
…,return “No drink for you”
print(drink(3)) # outputs You got yourself a drink
print(drink(1)) # outputs No drink for you
def alcohol(age,money):
…if (age >= 21) and (money >= 5):
…,return “We’re getting a drink”
…elif (age >= 21) and (money <5):
…,return “Come back with more money”
…elif (age <21) and (money >= 5):
…,return “Nice try, kid”
…else:
…,return “Too poor and too young”
print(alcohol(21,5)) # gets a drink
print(alcohol(21,4)) # come back more money
print(alcholo(20,4)) # too poor, too young
Lists
lists are just an array
lists live within brackets
movies = [“when harry met sally”, “the hangover”, “perks of being wallflower”]
print(movies[1]) # outputs 2nd item in the array, because 0 = 1st index
print(movies[0:2]) # will print 1st, 2nd, 3rd
print(movies[1:]) # will print entire array after the 2nd index
print(movies[:1]) # will print entire array up to 2nd index (“when harry…” only)
print(movies[-1)) # grabs last item on the list
print(len(movies))
movies.append(“jaws”) # will append jaws to end of array from this point forward
movies.pop() # this will delete last item on array
print(movies) # won’t have jaws anymore
movies.pop(0) # this will delete 1st index of array
Tuples
tuples are an immutable array, uses brackets
grade = {“a”, “b”, “c”, “f”} # now that it’s defined, it stays that way
print(grades{3}) # will still print 4th index in the tuple
Loops
ports = [21, 22, 23,80,3389]
for x in ports:
…print(x) # prints each port
y = 1
while y < 10:
…print(y)
…y += 1 # keeps going until y = 10
Let me know what you think of this article on twitter @cpardue09 or leave a comment below!