########################
Interactive Notes
Interactive notes have been seperated.
########################
#! /usr/bin/env python import random # import a module to use random numbers later # Left off 175/562 ###################################################### # # (exec(open('python_crash_course_notes.txt').read())) # ###################################################### print("Can you see me?") # Print something answer = "Why should I?" print(answer) # Store a variable and print it print() name = "douglas engelbart" print(name.title()) print(name.upper()) print(name.lower()) # Print each word with a capital letter # Print all uppercase then all lowercase print('\nConcat') first_name = "jack" last_name = "parsons" full_name = first_name + " " + last_name print(full_name) print("Excuse me Mr. " + full_name.title() + "!") get_his_attn = "Hey... hey! " + full_name.title() + "!" print(get_his_attn) # Concatenate two strings print('\nWhitie') print("Indent me") print("\tIndent me please") # Indent with tabs print("Dare you\nto put this\non one line!") # Newlines print("Cool Peeps:\n\tNikola Tesla\n\tBenjamin Franklin\n\tSteve Wozniak") # Indent after newlines print('\nStrippers') stripper = "saida " print(stripper) print(stripper + "Spaced right out") print(stripper.rstrip() + "Eat right whitespace") stripper = stripper.rstrip() print(stripper + "Eat right whitespace") # Strip whitespace on right side another_stripper = " avantika " print("!!!" + another_stripper + "!!!") print("!!!" + another_stripper.rstrip() + "!!!") print("!!!" + another_stripper.lstrip() + "!!!") print("!!!" + another_stripper.strip() + "!!!") # Strip right, left, both sides whitespace print('\nNums') print(3 + 2) print(4 - 3) print(2 * 5) print(5 / 2) print(4 ** 8) print(3 ** 4) print(10 ** 4) print(4 + 2 * 8) print((4 + 2) * 8) # Some number stuff cucumbers = 22 stringed_cucumbers = "I used " + str(cucumbers) + " last time!" print(stringed_cucumbers) # Concatenate int with string #print('\nZen of Py') #import this # Prints out the zen of python print('\nLists') classes = ['drawing', 'arabic', 'algebra', 'nap time', 'day dreaming'] print(classes) print(classes[1]) print(classes[3].title()) print(classes[-1]) class_brag = "My last class was a " + classes[0].upper() + " class." print(class_brag) classes[1] = 'persian' print(classes) classes.append('logic') print(classes) # Create list and print it print('\nAppend, remove list items') habits = [] habits.append('guzzling alcohol') habits.append('loving love') habits.append('breathing crack') print(habits) habits.insert(0, 'lying ass off') print(habits) del habits[2] print(habits) # Create empty list and stuff and unstuffing it print('\nPopping lists') gurus = ['buddha', 'osho', 'bashar', 'laozi'] print(gurus) popped_guru = gurus.pop() print(gurus) print('I popped ' + popped_guru.title() + ' for good luck!') popped_guru_again = gurus.pop(1) print(gurus) print('I got a reward for popping ' + popped_guru_again + '!') # Popping list to keep removed value print('\nRemoving items from list') pets = ['roach', 'rabbit', 'flea', 'rat'] print(pets) eat_too_much = 'rabbit' pets.remove(eat_too_much) print(pets) print(eat_too_much.title() + 's are too expensive to feed!') # Use remove() to delete by value; when index is not known # Remove() only removes the first occurence of a value. print('\nSort a list') order = ['first', 'second', 'third', 'fourth'] print(order) order.sort() print(order) order.sort(reverse=True) print(order) # Sort a list permanently print('\nReverse sort list') order_temp = ['3rd', '1st', '4th', '2nd'] print(order_temp) print(sorted(order_temp)) print(sorted(order_temp, reverse=True)) print(order_temp) print('\nReverse a list') mayan_lang = ['chontal', 'tzeltal', 'jakaltek', 'akatek'] print(mayan_lang) mayan_lang.reverse() print(mayan_lang) print(len(mayan_lang)) print('\nFor in loop list') meanies = ['bullies', 'principals', 'exes', 'mornings'] for meanie in meanies: print(meanie.title() + ' are horrible!') print('May the gods destroy all ' + meanie + '...') # For loop to spit out list content print('\nRange roving') for value in range(1,10): print(value, end=' ') print() # print 1 through 9 with range # Use a space instead of newline with end print('\nRange gulped by list') gulpeddigits = list(range(1,11)) print(gulpeddigits) # Create list of numbers with range print('\nOdd range list') odd_nums = list(range(1,22,2)) print(odd_nums) # Make an odd list of numbers with range print('\nCubed range') cubes = [] for val in range(1,14): cube = val**3 cubes.append(cube) print(cubes) # Print cubes with range print('\nQuaded more concisely') quaded = [] for val in range(1,11): quaded.append(val ** 4) print(quaded) # Shorter version of above cubes print('\nList comprehnsion squares') squares = [val**2 for val in range(1,16)] print(squares) print('\nMin, max, sum nums of a list') worst_nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(min(worst_nums)) print(max(worst_nums)) print(sum(worst_nums)) # Get the min, max, and sum of a list of nums print('\nSlicing a list') cry_babies = ['alexander', 'genghis', 'caesar', 'pope'] print(cry_babies[1:4]) print(cry_babies[:2]) print(cry_babies[2:]) print(cry_babies[-3:]) # Slice a list to get the items needed; into a new list print('\nLooping a slice') lickables = ['breasts', 'eyes', 'tongues', 'toes'] for lickable in lickables[-3:]: print('Licking ' + lickable + ' will attract you some freaks!') # Use a slice to choose what is looped out a list print('\nCopy a list') cool_clouds = ['cirrus', 'cirrocumulus', 'altocumulus', 'cumulonimbus'] clouds = cool_clouds[:] clouds.extend(['cumulus', 'stratocumuls']) print(cool_clouds) print(clouds) # Copy a list by using blank index in a slice # If you don't use a slice it will just point to the other list print('\nImmutable tuple') avg_coffin_dim = (84, 28, 23) print('The average coffin length is ' + str(avg_coffin_dim[0]) + ' width is ' + str(avg_coffin_dim[1]) + ' height is ' + str(avg_coffin_dim[2]) + '.') # Length, width, height # Values in a tuple cannot change # Although you could redefine the tuple print('\nIfing through a list') comp_parts = ['mamaboard', 'cpu', 'video card', 'ethernet card', 'ram'] for part in comp_parts: if part == 'cpu': print(part.upper()) else: print(part.title()) # For through a loop and alter output with an if statement print('\nNot equal') man = 'nerd' if man != 'nerd': print('Send over the party!') else: print('Send over the books!') # ! is not != is not equal print('\nAnd Condition') given_kisses = 0 gotten_kisses = 0 if given_kisses == 0 and gotten_kisses < 1: print('Less mouth germs!') # Use and to make logical comparison print('\nConditionOr') used_conditioner = 'yes' bathed_in_lotion = 'no' if (used_conditioner == 'yes') or (bathed_in_lotion == 'yes'): print('Yous slimmy!') # Use logical or print('\nIs it in my list?') soup_ingredients = ['water', 'peas', 'carrots', 'corn', 'doggie'] if 'peas' in soup_ingredients: print('How dare you pea in my soup!') # Check to see if value in a list print('\nBetter not be in my list...') in_stomach = ['water', 'rice', 'walnuts', 'fingernail'] if 'milk' not in in_stomach: print('No animal juice in here!') # Use not in to make sure value is not in list print('\nIfing again else') bar_min_age = 25 if bar_min_age >= 25: print('You are old enough to party here.') print('So come on in.') else: print('Gonna have to grow a little to come in here.') print('Feel free to give us your money, then.') # Simple if else print('\nElif my gift') roadkill = 'possum' if roadkill == 'coon': print('Eatin good tahnite!') elif roadkill == 'possum': print('We eatin ' + roadkill + ' babies!') else: print('Get your bowls, we slurpin ' + roadkill + ' gumbo!') # A little elif never hurt nobody print('\nMuseum cost') age = 23 if age < 6: admission = 0 nickname = 'little one' elif age < 13: admission = 3 nickname = 'know it all' elif age < 65: admission = 20 nickname = 'money bags' else: admission = 5 nickname = 'crusty' print('Hey ' + nickname + ' you owe ' + str(admission) + ' dolla!') # More consise elif; when print statement will be same for all options. # As soon as one test passes, the rest of the tests are abandoned. # There does not have to be an else. Another elif could be used # to make sure code is only executed with specific input. print('\nDo em all') body_types = ['chunky style', 'skin and bones', 'nice and fit'] for body_type in body_types: print('I\'m nailing ' + body_type + '...') print("Need a break; I'm done in for the night.") print('\nI scream') ice_cream_toppings = [] if ice_cream_toppings: for ice_cream_topping in ice_cream_toppings: print('You get some ' + ice_cream_topping + ' in my ice cream!') print('Here you go, enjoy your goodies.') else: print('Hope you enjoy your boring ice cream.') # Check to see if list is empty and let if statement alter what is # printed. Empty list will evaluate to false. print('\nYou scream') avail_ice_tops = ['fugde','caramel','m&ms','praline','peanut butter cups', 'sprinkles','whipped cream','cookie dough','reeses'] wanted_ice_tops = ['caramel','cookie dough','kitten toes'] for wanted_ice_top in wanted_ice_tops: if wanted_ice_top in avail_ice_tops: print('You gettin some ' + wanted_ice_top + '.') else: print("Hell nah, we don't put " +wanted_ice_top+ " on ice cream!") print('All yours, lick it up.') # Check if items in one list are in another. print('\nDictionaries') student_0 = {'race': 'fast', 'smart': 'yes', 'active': 'no'} print(student_0['race']) print(student_0['smart']) print(student_0['active']) # Create a dictionary and print values by calling keys # Dict values can be: numbers, strings, lists, another dictionary, # any object you can create in python. print('\nAdd to existing dict') print(student_0) student_0['doable'] = 1 student_0['pet'] = 'no' print(student_0) # New key-value pairs can be added to a dictionary at any time. print('\nEmpty dictionary') hare_0 = {} hare_0['length_in'] = 20 hare_0['speed_mph'] = 38 hare_0['mass_lb'] = 18 hare_0['life_span_yr'] = 5 print(hare_0) # Can start with empty dict and add to it. Useful when autogenerating # or with user input. print('\nModify dict value') hare_0['length_in'] = 22 print(hare_0) # Modify a previous value in a dictionary print('\nDict play') hamster_0 = {'x_pos': 0, 'y_pos': 20, 'predator': 'snake'} print("Start position in ft: " + str(hamster_0['x_pos'])) # Hamster scurries to the right # How far the hamster runs in fear based on predator. if hamster_0['predator'] == 'scorpion': x_distance_ft = 10 elif hamster_0['predator'] == 'snake': x_distance_ft = 20 else: x_distance_ft = 2 # Hamster jolts to start position + x_distance_ft hamster_0['x_pos'] = hamster_0['x_pos'] + x_distance_ft print('Hamster bolted ' + str(hamster_0['x_pos']) +' ft ' + 'from ' + hamster_0['predator'] + '!') # Modify values in a dict; similar to a way a game may. print('\nRemove key-value pair from dictionary') chicken_enemies = {'sly': 'fox', 'agile': 'cat', 'airborne': 'hawk'} print(chicken_enemies) print('Farmer kills the agile enemy.') del chicken_enemies['agile'] print(chicken_enemies) # Delete a key value pair from a dictionary. print('\nDictionary of survey objects') fav_prog_langs = { 'person01': 'common lisp', 'person02': 'ruby', 'person03': 'smalltalk', 'person04': 'clojure', 'person05': 'c', 'person06': 'assembly', } print('The sixth person polled chose ' + fav_prog_langs['person06'] + '.') for surveyed, fav_lang in fav_prog_langs.items(): print(surveyed.title() + "'s favorite language is " + fav_lang.title() + ".") # Dictionaries can contain similar values, like those that would # be given in a poll. print('\nIs value in list a dictionary value also?') suck_langs = ['common lisp', 'assembly'] for fav_lang in fav_prog_langs.values(): if fav_lang in suck_langs: print('Um... ' + fav_lang.title() + ' are you insane! ' + list(fav_prog_langs.keys()) [list(fav_prog_langs.values()).index(fav_lang)].title() + '?') # Continued from fav_prog_langs above # Check to see if values in a list are in a dictionary. # Use a list to get the key by the value of a dictionary print('\nNot in dict') if 'python' not in fav_prog_langs.values(): print('Geez is Python that bad?') # Continued from fav_prog_langs above print('\nLooping all key-value pairs in a dict') pet_0 = { 'type': 'turtle', 'name': 'thurtle', 'color': 'green', 'home': 'aquarium', } for k, v in pet_0.items(): print('Key: ' + k) print('Value: ' + v) # Print all keys and values in a dictionary using a for loop print('\nLoop through dict; keys only') students = { 'ralph': 'history', 'sara': 'art', 'george': 'spanish', 'callie': 'math', } # for name in students: for name in students.keys(): print(name.title()) # Loop through a dictionary only print out keys # keys are the default when looping, so: # for name in students.keys(): # could be rewritten as: # for name in students: print('\nSort a dictionary') for first_name in sorted(students.keys()): print(first_name.title()) # Continued from student dictionary above # Sort a dictionary by key with sorted print('\nLoop through only the values in a dictionary') print('Here is a list of majors declared this semester') for major in students.values(): print(major.title()) # Continued from student dictionary above # Print out the values only in a dictionary with a for loop. print('\nUse "set" to remove dupes from a dictionary; values only') players = { 'mekel': 'sniper', 'ariadnai': 'berserker', 'vjay': 'sniper', 'xmb': 'collector', } for player in set(players.values()): print(player.title()) # Using set() will remove duplicate values from a looped dictionary # It builds a set of unique items print('\nStuff several dictionaries in a list') dnd_girl_0= {'race': 'elf', 'class': 'bard', 'hp': 30, 'dex': 10} dnd_girl_1 = {'race': 'dwarf', 'class': 'druid', 'hp': 40, 'wis': 10} dnd_girl_2 = {'race': 'gnome', 'class': 'wizard', 'hp': 25, 'int': 10} dnd_girls = [dnd_girl_0, dnd_girl_1, dnd_girl_2] for dnd_girl in dnd_girls: print(dnd_girl) # Create three dictionaries and put them in a list print('\nUse range to create dictionaries to put in a list') slime_gang = [] special_attacks = {'chew': 6, 'smack': 3, 'acid': 4} i = 0 for slime in range(random.randint(3,11)): special_attack = random.choice(list(special_attacks.keys())) new_slime = { 'name': 'slime' + str(i), 'hp': random.randint(5,20), 'atk_dmg': random.randint(1,6), special_attack: random.randint(1,special_attacks[special_attack]), } i += 1 slime_gang.append(new_slime) for slime in slime_gang: print(slime) super_slime = 0 for slime in slime_gang[-3:]: if ( (slime['hp'] == 20) and (slime['atk_dmg'] == 6) ): super_slime = 1 print("You come across a gang of " + str(len(slime_gang)) + ' slimes!') print('Prepare for battle...') if super_slime == 1: print('Super slime jumps out and devours your party!') # Use range to automatically create a dict for each slime # and create a list of a gang of all the slimes. # Each slime stats will be randomish. # random.choice(special_attacks.keys()) would work before python 2.x . # In python 3 it no longer creates a list, now this creates # an iterator so it needs to be: # random.choice(list(special_attacks.keys())) # Which will turn in into a list and let us get the key # from the value in the dict. # Super slime will be victor if any of the last three slimes # Have health of 20 and atk_dmg of 6. print('\nUse a list inside a dictionary value') hero_party = { 'num_members': 5, 'mem_names': ['vlado', 'vjay', 'avantika', 'ariana', 'laozi'], } print('These are the ' + str(hero_party['num_members']) + ' members in your party:') for hero in hero_party['mem_names']: print('\t' + hero) # Use a list as the values for a key in a dictionary and loop through # them. print('\nUse serveral list as values in a dict') spoken_langs = { 'mekel': ['english', 'romanian'], 'vjay': ['english', 'spanish'], 'ariana': ['spanish', 'french'], 'laozi': ['chinese'], 'avantika': ['hindi'], 'vlado': ['english', 'spanish', 'czech'], } for name, langs in spoken_langs.items(): print(name.title() + ' speaks:') for lang in langs: print(' ' + lang.title()) # Use lists as the values to dictionary keys print('\nDictionary inside a dictionary') super_freaks = { 'dengelbart': { 'first': 'douglas', 'last': 'engelbart', 'invented': ['mouse', 'on-line system', 'hypertext'], }, 'marvel': { 'first': 'jack', 'last': 'parsons', 'invented': ['jet propulsion laboratory', 'aerojet engineering corporation', 'castable composite rocket propellant engine'] }, } for freak, freak_info in super_freaks.items(): print('\nMoniker: ' + freak) freak_name = freak_info['first'] + ' ' + freak_info['last'] invented = freak_info['invented'] print('\t' + freak_name.title() + ' was a super freak! ' + 'That invented: ') for invent in invented: print('\t' + invent.title()) # Use a dictionary as the key value pair in a dictionary # that includes a list as one of its values. print('\nWhile down loop') count_down = 10 while count_down >= 0: print(count_down) count_down -= 1 if count_down < 0: print('Lift down!') # Example while loop # Use Ctrl-c to get out of an infinite loop print('\nCountiue to beginning of while loop') all_lovers = ['saida', 'mekel', 'bethany', 'nutz', 'avantika', 'vjay', 'enoch', 'azazael', 'trina'] secret_lovers = ['mekel', 'enoch', 'azazael', 'nutz'] i = 0 while i < len(all_lovers): if all_lovers[i] in secret_lovers: i += 1 continue print(all_lovers[i]) i += 1 # Use continue to skip rest of code and jump back to # beginning of while loop, so secret lovers are not # printed about for all to see. print('\nWhile looping through lists') creatures_alive = ['dung beetle', 'praying manits', 'dragonfly'] creatures_assassinated = [] while creatures_alive: current_creature = creatures_alive.pop() print("Whack! Whack! " + current_creature.title() + " assassinated!") creatures_assassinated.append(current_creature) print('The following pests have been assassinated:') for creature_assassinated in creatures_assassinated: print(creature_assassinated.title()) # List should not be altered with for loops. You should # use while loops when altering data in a list or dictionary. # Use a while loop to move items from one list to another. print('\nWhiley remove all instances of a value in a list') sashimis = ['ahi', 'aji', 'amaebi', 'anago', 'aoyagi', 'binochi', 'aoyagi', 'aoyagi'] print(sashimis) while 'aoyagi' in sashimis: sashimis.remove('aoyagi') print(sashimis) # Use a while loop to .remove all instances of a value in a list # one at a time. print('\nDefine a function that flirts') def perv_flirt(): """Get them gals with words!""" print('Nice shorts, can I test the zipper?') perv_flirt() # Create a function easy reuse of code # """inside here is a docstring for the function""" print('\nFunction call with an arguEment to a perv') def shrug_off_perv(dis): """Tell perv to hit road!""" print('Help! Help! That ' + dis + ' tried to dig in my drawers!') shrug_off_perv('old bastard') # Create a function that is called with a argument. print('\nPositional arguments in a function') def gossip_him(guy_job, guy_name): """Talk a little gossip about a guy.""" print("That guy is a " + guy_job + "!") print("That " + guy_job + "'s name is " + guy_name.title() + "...") gossip_him('gigolo', 'george') gossip_him('fireman', 'fred') # Create a function that takes positional arguments # that need to be passed in the right order. # *** Using same function above *** print('\nKeyword Arguments called with a function') gossip_him(guy_name='sammie', guy_job='bartender') # By passing keyword arguments; the order does not matter. print('\nDefault value for a function parameter') def gossip_her(lady_name, lady_job='wife'): """Gossip about the ladies.""" print("That lady is a " + lady_job + "!") print("That " + lady_job + "'s name is " + lady_name.title() + "...") gossip_her('sarah') gossip_her(lady_name='karen') gossip_her(lady_name='liz', lady_job='lawyer') # Default values can be used for parameters, so arguments # without a value will use the default. # Order of parameters matters when all of them don't # have a default value; parameters with default values # need to come after parameters without a default value. print('\nReturn value from function') def sprinkle_toppings(first,second,on_top_of='ice cream'): """Return toppings""" topped_off = on_top_of+ ' toppings are: ' +first+', ' +second+ '!' return topped_off rakasha_order = sprinkle_toppings('reeses', 'chocolate') jasmine_order = sprinkle_toppings('peanuts', 'walnuts', 'french fry') print(rakasha_order) print(jasmine_order) # Create a function with a return value # Print the return vaule after assinging it print('\nFunction with optional argument') def cult_greeting(salutation, secret_handshake=''): """Function with optional argument""" if secret_handshake: greeting = salutation + ' **you perform: ' + secret_handshake else: greeting = salutation + ' ...' return greeting commoner = cult_greeting('hey') pope_guroo = cult_greeting('yo', 'pinky index ring twist rub a nub shake') print(commoner) print(pope_guroo) # Create a function with optional arguments print('\nReturn a dictionary with a function') def create_skater(fname, lname, company): """Return a dictionary of info about a skater.""" skater = {'first': fname, 'last': lname, 'company': company} return skater first_place = create_skater('matt', 'hensley', 'h-street') second_place = create_skater('rodney', 'mullen', 'powell peralta') print(first_place) print(second_place) # Use a function to return a dictionary print('\nReturn a dictionary from function with optional value') def create_detailed_skater(fname, lname, company, stance='', aka=''): skater = {'first name': fname, 'last name': lname, 'company': company} if stance: skater['stance'] = stance if aka: skater['aka'] = aka return skater cali_skater = create_detailed_skater('eric', 'koston', 'girl', 'goofy') florida_skater = create_detailed_skater('alan', 'gelfand', 'powell peralta', 'regular', 'ollie') cali_skater02 = create_detailed_skater('jeremy', 'wray', 'blockhead') print(cali_skater) print(florida_skater) print(cali_skater02) # Use a funtion to return a dictionary that has # optional values print('\nCreate a function that iterates on a list') def fire_employees(people): """Fire a list of employees""" for person in people: scream = person.title() + "! You are fired!!!" print(scream) disgruntled = ['jake', 'envia', 'taizya', 'avantika'] fire_employees(disgruntled) # Use a list as an argument to a function # to display a message to each person print('\nBuild some robots with list, while, for') unbuilt_robots = ['spider', 'snake', 'shark', 'hummingbird', 'octopus'] completed_robots = [] # Simulate building each robot. # After building a robot move it to the completed_robots list # and print it while unbuilt_robots: current_robot = unbuilt_robots.pop() print("Constructing the " + current_robot.title() + " robot...") completed_robots.append(current_robot) # Show all completed robots print("\nThese robots have been built:") for completed_robot in completed_robots: print(completed_robot) print('\nBuild some drones with list and functions:') def build_drones(unbuilt_drones, completed_drones): """ Simulate building each drone. Move each drone to completed_drones function after building. """ while unbuilt_drones: current_drone = unbuilt_drones.pop() # Simulate building a drone print("Building " + current_drone + " drone now") completed_drones.append(current_drone) def display_completed_drones(completed_drones): """Display each drone that was built""" print("\nLook at each drone we built!") for completed_drone in completed_drones: print(completed_drone) unbuilt_drones = ['helicopter', 'plane', 'car', 'submarine', 'space'] completed_drones= [] build_drones(unbuilt_drones, completed_drones) display_completed_drones(completed_drones) # build_drones(unbuilt_drones[:], completed_drones) # Called this way unprinted_designs would be a copy of # the list; instead of moving them over. # Coping the list is more resource hungry. # Create two functions to build and display drones # Another way to write the code above these functions print('\nFunction with unknown number of arguments; listing them') def have_crush_on(*crushies): """Print list of crushies I have crushes on""" print(crushies) for crushie in crushies: print("I have a crush on: " + crushie + "s!") have_crush_on('tarantula') print('----------') have_crush_on('scorpion', 'june bug', 'beetle') # Create a function that takes a list an arbitrary # number of arguments and prints them with a for loop def order_tv_dinner(main_dish, size, *side_dishes): """Order dinner from tv dinner vending machine.""" print("\nDispensing a " + str(size) + " " + main_dish + " tv dinner with the followng sides:") for side_dish in side_dishes: print("- " + side_dish) order_tv_dinner('salisbury steak', 'jumbo', 'mashed potatoes', 'cinnamon roll', 'kimchi') # When mixing arbitray and positional arguments, arbitrary # arguments must come last (in this case side dishes)
########################
Interactive Notes
Interactive notes have been seperated.
########################