Python Final

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

Numbers

100 #> 100 -100 #> -100 0.45 #> 0.45 Numeric functions include the usual arithmetic operators: 100 + 5 #> 105 100 - 5 #> 95 100 * 5 #> 500 100 / 5 #> 20 100 + 5 * 2 #> 110 (100 + 5) * 2 #> 210 Round round(4.5) #> 5.0 round(4.49) #> 4.0 other way - round(4.49, 0) #> 4.0 round(4.49, 1) #> 4.5 round(4.49, 2) #> 4.49 Use string formatting to control how numbers will display when printed: 'the price is ${0:.2f}'.format(6.5) #> 'the price is $6.50' Boolean equality operators also apply: 100 == 100 #> True 100 == 100.0 #> True 100 == 99 #> False 100 == (99 + 1) #> True True == 1 #> True False == 0 #> True

Lists

A List represents a numbered, ordered collection of items. A List may contain zero or more items. A list can contain items of any datatype, but as a best practice, all items in a list should share a datatype and structure: # DO: [] [1,2,3,4] [100, 75, 33] ["fun", "times", "right?"] [ {"a":1, "b":2}, {"a":5, "b":6}] # lists can contain dictionaries [ [1,2,3], [4,5,6], [7,8,9]] # lists can be "nested" inside other lists # DON'T: [100, "fun"] [ {"a":1, "b":2}, {"x":5, "z":6}] Like other languages, individual list items can be accessed by their index. List item indices are zero-based, meaning the index of the first list item is 0. arr = ["a", "b", "c", "d"] arr[0] #> "a" arr[1] #> "b" arr[2] #> "c" arr[3] #> "d" arr[4] #> IndexError: list index out of range arr.index("a") #> 0 arr.index("b") #> 1 arr.index("c") #> 2 arr.index("z") #> -1 (applies to any item not found in the list) Equality operators apply: [1,2,3] == [1,2,3] #> True [1,2,3] == [3,2,1] #> False Inclusion operators apply: arr = [1,2,3,4,5] 3 in arr #> True 3 not in arr #> False Common list functions and operators include the following built-in Python functions: arr = [6,3,9,7] len(arr) #> 4 min(arr) #> 3 max(arr) #> 9 Add an element to the end of a list: arr = ["a", "b", "c", "d"] arr.append("e") # this is a mutating operation arr #> ["a", "b", "c", "d", "e"] Remove an element from a list by providing the index of the item you would like to remove: arr = ["a", "b", "c", "d"] del arr[1] # this is a mutating operation arr #> ['a', 'c', 'd'] Concatenate two lists: arr = ["a", "b", "c", "d"] arr2 = ["x", "y", "z"] arr3 = arr + arr2 arr3 #> ["a", "b", "c", "d", "x", "y", "z"] Remove duplicate values in a list by converting it to another datatype called a "Set" and then converting it back to a "List": arr = [1,2,2,2,3] arr2 = list(set(arr)) arr2 #> [1, 2, 3] list(set(["hello", "hello", "hello"])) #> ['hello'] Sorting Sort a list: arr = [6,3,8] arr.sort() # this is mutating arr #> [3, 6, 8] arr.reverse() # this is mutating arr #> [8, 6, 3] If you have a list of dictionaries, you should be able to sort it based on dictionary values: teams = [ {"city": "New York", "name": "Yankees"}, {"city": "New York", "name": "Mets"}, {"city": "Boston", "name": "Red Sox"}, {"city": "New Haven", "name": "Ravens"} ] def team_name(team): return team["name"] def sort_by_hometown(team): return team["city"] def sort_special(team): return team["city"] + "-" + team["name"] teams2 = sorted(teams, key=team_name) teams2 #> [{'city': 'New York', 'name': 'Mets'}, {'city': 'New Haven', 'name': 'Ravens'}, {'city': 'Boston', 'name': 'Red Sox'}, {'city': 'New York', 'name': 'Yankees'}] teams3 = sorted(teams, key=sort_by_hometown) teams3 #> [{'city': 'Boston', 'name': 'Red Sox'}, {'city': 'New Haven', 'name': 'Ravens'}, {'city': 'New York', 'name': 'Yankees'}, {'city': 'New York', 'name': 'Mets'}] teams4 = sorted(teams, key=sort_special) teams4 #> [{'city': 'Boston', 'name': 'Red Sox'}, {'city': 'New Haven', 'name': 'Ravens'}, {'city': 'New York', 'name': 'Mets'}, {'city': 'New York', 'name': 'Yankees'}] Alternatively for simple attribute-based sorting, you could use the operator module's itemgetter() function, for example: import operator teams = [ {"city": "New York", "name": "Yankees"}, {"city": "New York", "name": "Mets"}, {"city": "Boston", "name": "Red Sox"}, {"city": "New Haven", "name": "Ravens"} ] teams = sorted(teams, key=operator.itemgetter('city')) teams #> [{'city': 'Boston', 'name': 'Red Sox'}, {'city': 'New Haven', 'name': 'Ravens'}, {'city': 'New York', 'name': 'Yankees'}, {'city': 'New York', 'name': 'Mets'}] Iteration Reference: https://docs.python.org/3/tutorial/datastructures.html?#list-comprehensions https://docs.python.org/3/tutorial/datastructures.html?highlight=lists#list-comprehensions https://docs.python.org/3/tutorial/controlflow.html#for-statements A list can be iterated, or "looped" using a for ... in ... statement: for letter in ["a", "b", "c", "d"]: print(letter) #> a #> b #> c #> d A common pattern is to loop through one list to populate the contents of another: arr = [1, 2, 3, 4] arr2 = [] for i in arr: arr2.append(i * 100) arr #> [1, 2, 3, 4] arr2 #> [100, 200, 300, 400] Lists can be looped "in-place" using Python's built-in map() function. The map() function takes two parameters. The first parameter is the name of a pre-defined function to perform on each item in the list. The function should accept a single parameter representing a single list item. The second parameter is the actual list to be operated on. arr = [1, 2, 3, 4] def enlarge(num): return num * 100 arr2 = map(enlarge, arr) # Python 2.x: arr2 #> [100, 200, 300, 400] # Python 3.x: arr2 #> <map object at 0x10c62e710> list(arr2) #> [100, 200, 300, 400] NOTE: remember to use the return keyword in your mapping function! Filtering Reference: https://docs.python.org/2/library/functions.html#filter. Use the filter() function to select a subset of items from a list - only those items matching a given condition. The filter function accepts the same parameters as the map() fuction: arr = [1,2,4,8,16] def all_of_them(i): return True # same as ... return i == i def equals_two(i): return i == 2 def greater_than_two(i): return i > 2 def really_big(i): return i > 102 # Python 2.x: filter(all_of_them, arr) #> [1, 2, 4, 8, 16] filter(equals_two, arr) #> [2] filter(greater_than_two, arr) #> [4, 8, 16] filter(really_big, arr) #> [] # Python 3.x: filter(all_of_them, arr) #> <filter at 0x103fa71d0> list(filter(all_of_them, arr)) #> [1, 2, 4, 8, 16] list(filter(equals_two, arr)) #> [2] list(filter(greater_than_two, arr)) #> [4, 8, 16] list(filter(really_big, arr)) #> [] Note: the filter() function returns a list, even if it is empty or only contains one item. When using the filter function, observe this alternative filtering syntax involving the keyword lambda: arr = [1,2,4,8,16] # Python 2.x: filter(lambda i: i > 2, arr) #> [4, 8, 16] # Python 3.x: list(filter(lambda i: i > 2, arr)) #> #> [4, 8, 16] If your list is full of dictionaries, you can filter() based on their attribute values: teams = [ {"city": "New York", "name": "Yankees"}, {"city": "New York", "name": "Mets"}, {"city": "Boston", "name": "Red Sox"}, {"city": "New Haven", "name": "Ravens"} ] def yanks(obj): return obj["name"] == "Yankees" def from_new_york(obj): return obj["city"] == "New York" def from_new_haven(obj): return obj["city"] == "New Haven" def from_new_something(obj): return "New" in obj["city"] # Python 2.x: filter(yanks, teams) #> [{...}] filter(from_new_york, teams) #> [{...}, {...}] filter(from_new_haven, teams) #> [{...}] filter(from_new_something, teams) #> [{...}, {...}, {...}] # Python 3.x: list(filter(yanks, teams)) #> [{...}] list(filter(from_new_york, teams)) #> [{...}, {...}] list(filter(from_new_haven, teams)) #> [{...}] list(filter(from_new_something, teams)) #> [{...}, {...}, {...}] If you need to implement complex filtering conditions, consider using a list comprehension, or "lambda" syntax, or consider writing out your function the long way: teams = [ {"city": "New York", "name": "Yankees"}, {"city": "New York", "name": "Mets"}, {"city": "Boston", "name": "Red Sox"}, {"city": "New Haven", "name": "Ravens"} ] # using a list comprehension def teams_from(city): return [team for team in teams if team["city"] == city] # using "lambda" syntax def teams_from2(city): return filter(lambda team: team["city"] == city, teams) # the long way def teams_from3(city): matches = [] for team in teams: if team["city"].upper() == city.upper(): matches.append(team) return matches teams_from("New York") #> [{...}, {...}] teams_from2("New York") #> [{...}, {...}] You might have to first convert this to a list depending on your Python version (see examples above). teams_from3("New York") #> [{...}, {...}] Reference the itertools module for additional operations.

Classes

A class is a representation of one or more objects which share the same or similar properties. Each class is like its own custom data type with properties defined by the developer. In Python, class definition requires a specific function called __init__() to initialize, or create a new member of the object class. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state. Example The objects are all made of strings i.e. all variables must be of the same nature class BaseballTeam(): """ bt = BaseballTeam({"city": "Little Town", "name": "Tots", "league":"little", "players": ["JJ", "Zhang", "Margaret", "Ryan", "Joey"]}) """ # optional docstring def __init__(self, params): self.city = params["city"] self.name = params["name"] self.league = params["league"] self.players = params["players"] def full_name(self): return self.city + " " + self.name

Booleans

Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. Examples are True and True; True or True The most relevant boolean operator is the equality operator, ==. Its functionality is represented by the phrase, "Is this equal to that?" The converse is the inequality operator, !=. Its functionality is represented by the phrase, "Is this not equal to that?"

Layout

First few questions are open ended - conceptional more emphasis on python coding questions — approximately half The end of the final will be more conceptional questions

Write a for loop by hand to print out each item in a given list

For i in my_list: print(i)

Dictionaries

Many programming languages provide an "associative array" datatype which provides an opportunity to create objects with named attributes. In this way, an associative array is similar to a row in a CSV-formatted spreadsheet or a record in a database, where the associative array's "keys" represent the column names and its "values" represent the cell values. associative arrays are said to have "key/value" pairs, where the "key" represents the name of the attribute and the "value" represents the attribute's value. Python's implementation of the associative array concept is known as a "dictionary". A Python dictionary comprises curly braces ({}) containing one or more key/value pairs, with each key separated from its value by a colon (:) and each key/value pair separated by a comma (,). Example teams = [ {"city": "New York", "name": "Yankees", "league":"major"}, {"city": "New York", "name": "Mets", "league":"major"}, {"city": "Boston", "name": "Red Sox", "league":"major"}, {"city": "New Haven", "name": "Ravens", "league":"minor"}

Functions that return vs functions that dont return - know about returning

Not every function needs to return a value. Some just don't. If all you want is to print the number, then you don't really need to return it. function i_return(x): print x return x function i_dont(x): print x i_return(5) # prints 5 i_dont(5) # prints 5 But consider another scenario, where you'd want to use the returned value (the output) inside another calculation or expression: print i_return(5) + 2 # prints 7 print i_dont(5) + 2 # causes an Error See, now there's trouble. To come back to the functions you asked about, you can, for instance, use the smallest_number in another expression, and you can only do that because of the return keyword:

Examples of Python packages

Pandas, Django, Sendgrid, Tkinter

Strings

Strings represent textual information, including words and alpha-numeric characters. "Hello World" "username123" Don't be confused if you see multi-line strings: str = """ Some Multi-line String """ str #> '\nSome\nMulti-line\nString\n' print(str) #> #> Some #> Multi-line #> String #> Example string functions: "Hello" + " " + "World" #> "Hello World" (string concatenation) "{0} {1}".format("Hello", "World") #> "Hello World" (string interpolation) "hello world".upper() #> "HELLO WORLD" "Hello World".lower() #> "hello world" "hello world".title() #> "Hello World" " Hello World ".strip() #> "Hello World" "Hello World".replace("Hello", "Goodbye") #> "Goodbye World" Strings also support equality, inclusion, and matching operators: "Hello World" == "Hello World" #> True "Hello World" == "hello world" #> False "Hello" in "Hello World" #> True "hello" in "Hello World" #> False "Hello World".count("l") #> 3 Strings are iterable objects comprised of multiple characters. Once you have learned about arrays, or "lists", you can perform additional array-related string operations: "Hello World"[0] #> "H" "Hello World"[6] #> "W" "Hello World"[-1] #> "d" "Hello World"[-3] #> "r" for character in "Hello World": print(character) #> #> H #> e #> l #> l #> o #> #> W #> o #> r #> l #> d "Hello World".split() #> ["Hello", "World"] "My Title - My Subtitle".split(" - ") #> ['My Title', 'My Subtitle'] "a, b, c, d".split(", ") #> ['a', 'b', 'c', 'd'] str = """ Some Multi-line String """ str.strip().split("\n") #> ['Some', 'Multi-line', 'String']

Dates and Times

Use the datetime module to handle dates and times. import datetime today = datetime.date.today() str(today) #> '2017-07-02' now = datetime.datetime.now() str(now) #> '2017-07-02 23:43:25.915816' now.strftime("%Y-%m-%d") #> '2017-07-02' july_fourth = datetime.date(2017, 7, 4) str(july_fourth) #> '2017-07-04' july_fourth.year #> 2017 july_fourth.month #> 7 july_fourth.day #> 4 july_fourth.weekday() #> 1 july_fourth.strftime("%Y-%m-%d") #> "2017-07-04" some_day = datetime.datetime.strptime("2020, 12, 31", "%Y, %m, %d") str(some_day) #> '2020-12-31 00:00:00'

Participate in, and describe the advantages and disadvantages of software version control. - could be an exact question

advantages - have stopping points with functional code to easily revert back to, track the changes of any one file as far as who wrote the code and when they wrote it, collaboration that version control provides - many people can work on one project; disadvantages - upfront cost to learn it, have to remember to do it

Describe the differences between functional and object-oriented programming. - there may be a question on this

can use 2 different ways to sort -> my_list = [1,2,3,4] either use sorted(my_list) (this is functional) or mylist.sort() - if calling a function on an object then its object oriented

Include a custom defined class and either match it or write our own - basically review the classes section

class BaseballTeam(): """ bt = BaseballTeam({"city": "Little Town", "name": "Tots", "league":"little", "players": ["JJ", "Zhang", "Margaret", "Ryan", "Joey"]}) """ # optional docstring def __init__(self, params): self.city = params["city"] self.name = params["name"] self.league = params["league"] self.players = params["players"] def full_name(self): return self.city + " " + self.name

What is the purpose of a software test

did not talk about test-driven environment, ex what is the purpose of a software test - quality control for end users to make sure there are no bugs, helpful for a development team to focus on pieces of project, testing saves time; disadvantages - its labor intensive and time consuming (similar to version control)

Loop through a dictionary and print one requested attribute from each item

for product in products: print(" + " + product["name"])

Output the number of stops this person makes (i.e. 3) person = { "first": "Santa", "last": "Claus", "spouse": "Mrs. Claus:", "message": "Ho Ho Ho", "stops": ["New York", "Denver", "San Francisco"], }

len(person["stops"])

Be able to reference attributes with key names for the dictionary section

list(variable_name.keys()) list(variable_name.values()) list(variable_name.items()) person = { "first": "Santa", "last": "Claus", "message": "Ho Ho Ho", "stops": ["New York", "Denver", "San Francisco"] } person.keys() #> dict_keys(['first', 'last', 'message', 'stops']) list(person.keys()) #> ['first', 'last', 'message', 'stops'] person.values() #> dict_values(['Santa', 'Claus', 'Ho Ho Ho', ['New York', 'Denver', 'San Francisco']]) list(person.values()) #> ['Santa', 'Claus', 'Ho Ho Ho', ['New York', 'Denver', 'San Francisco']] person.items() #> dict_items([('first', 'Santa'), ('last', 'Claus'), ('message', 'Ho Ho Ho'), ('stops', ['New York', 'Denver', 'San Francisco'])]) for k, v in person.items(): print("KEY:", k, "... VALUE:", v) #> KEY: first ... VALUE: Santa #> KEY: last ... VALUE: Claus #> KEY: message ... VALUE: Ho Ho Ho #> KEY: stops ... VALUE: ['New York', 'Denver', 'San Francisco']

Output the person's full name (i.e. Santa Claus): person = { "first": "Santa", "last": "Claus", "spouse": "Mrs. Claus:", "message": "Ho Ho Ho", "stops": ["New York", "Denver", "San Francisco"], }

person["first"] + " " + person["last"]

Output the name of the last stop this person makes, irrespective of the actual number of stops the person makes (i.e. San Francisco ow wherever the last stop happens to be, in the event more stops get added later): person = { "first": "Santa", "last": "Claus", "spouse": "Mrs. Claus:", "message": "Ho Ho Ho", "stops": ["New York", "Denver", "San Francisco"], }

person["stops"][-1]

Output the name of the first stop this person makes (i.e. New York) person = { "first": "Santa", "last": "Claus", "spouse": "Mrs. Claus:", "message": "Ho Ho Ho", "stops": ["New York", "Denver", "San Francisco"], }

person["stops"][0]

What is python

programming language that is used to write software

Discuss security and privacy considerations relevant in designing and managing computer-based information systems.

protecting secret passwords and api keys using environment variables to keep them out of source control

Could match the data type or write out an example

review the different datatypes - booleans, dates, List, dictionaries

How can business derive value from software

save time and money

What is software

set of instructions that tells the compute what to do

Participate in, and describe the advantages and disadvantages of open source software.

software is openly sourced when it is viewable by the public, it is not necessarily free, advantages - collaboration and crowdsource also educational advantages; disadvantages - lack of protection of intellectual property

How to check what type of data type a variable is

type(variable)

Describe the ecosystem of tools and technologies used to plan, develop, and maintain computer-based information systems.

version control (git) - maybe a conceptional question on version control (exact question from another final exam, text editor, and terminal

example of a dictionary

{"a":"hello", "b":"hi"}


संबंधित स्टडी सेट्स

Chapter 31: Assessment of Immune Function

View Set

Grief Loss and Comfort PrepU Questions

View Set

Magoosh - Quantitative Section [Hard], Quantitative Section

View Set

PhysioEx 6/Act 2: Examining the effect of vagus nerve stimulation

View Set

World History Part A - 1.5 Post Test Study Guide

View Set

Number of Solutions for Systems of Linear Equations

View Set

Biology 1 B - Lab: Mouse Genetics (One Trait) - Assignment 100%

View Set