Python

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

"""

"""-> you can put as many lines of text as you want until you end with another """ again. Example: fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """

def

"Define a function" - It's a code within code and you can call as many times as you want. Example: def f(x): return x * x y = f(2) print (y) # Order of Execution: # 1. Define a function -> def f(x): # 2. Call the function -> y = f(2) # 3. Once we call the function, it goes back and evaluate the body of the function -> return x * x # 4. Finally we jumped to the last line after the "function call" -> print (y)

String: Advanced substitution - Formatting

# Formatting expression (all) >>> '%s, eggs, and %s' % ('spam', 'SPAM!') 'spam, eggs, and SPAM!' # Formatting method (2.6+, 3.0+) >>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') 'spam, eggs, and SPAM!' # Numbers optional (2.7+, 3.1+) >>> '{}, eggs, and {}'.format('spam', 'SPAM!') 'spam, eggs, and SPAM!'

Combine 2 or more String Methods

# Remove whitespace characters on the right side >>> line = 'aaa,bbb,ccccc,dd\n' >>> line.rstrip() 'aaa,bbb,ccccc,dd' # Combine two operations >>> line.rstrip().split(',') ['aaa', 'bbb', 'ccccc', 'dd'] Notice the last command here—it strips before it splits because Python runs from left to right, making a temporary result along the way.

String: "RSTRIP" Method

# Remove whitespace characters on the right side Example: >>> line = 'aaa,bbb,ccccc,dd\n' >>> line.rstrip() 'aaa,bbb,ccccc,dd'

String: "SPLIT" Method

# Split on a delimiter into a list of substrings # use split() to chop a string into a list by some separator string Example: >>> line = 'aaa,bbb,ccccc,dd' >>> line.split(',') ['aaa', 'bbb', 'ccccc', 'dd'] Example: >>> birthday = '1/6/1952' >>> birthday.split('/') ['1', '6', '1952'] Example: >>> splitme = 'a/b//c/d///e' >>> splitme.split('/') ['a', 'b', '', 'c', 'd', '', '', 'e'] If you had used the two-character separator string // instead, you would get this: Example: >>> splitme = 'a/b//c/d///e' >>> splitme.split('//') >>> ['a/b', 'c/d', '/e']

String: "UPPER" Method

# Upper- and lowercase conversions >>> S = 'spam' >>> S.upper() 'SPAM'

Dictionary Pop()

# pop a dictionary by key >>> D {'eggs': 3, 'muffin': 5, 'toast': 4, 'spam': 2, 'ham': 1} >>> D.pop('muffin') 5 # Delete and return from a key >>> D.pop('toast') 4 >>> D {'eggs': 3, 'spam': 2, 'ham': 1} ------------------------------------------------------------------------------ # pop a list by position >>> L = ['aa', 'bb', 'cc', 'dd'] # Delete and return from the end >>> L.pop() 'dd' >>> L ['aa', 'bb', 'cc'] # Delete from a specific position >>> L.pop(1) 'bb' >>> L ['aa', 'cc']

range()

# range() can be used two ways: 1. range(start, stop) Example: range(10) [0,1,2,3,4,5,6,7,8,9] range(1, 11) [1,2,3,4,5,6,7,8,9,10] 2. range(start, stop, step) Example: range(0, 30, 5) [0,5,10,15,20,25] range(0, 10, 3) [0,3,6,9]

Python Loop Control: IF, WHILE & FOR

1. # Simple FOR loop to print all the names in the list ## "name" is the variable chosen (you can pick anything) ### "word" is the variable chosen for the second example Example 2-1: names = ["Alice", "Bob", "Castle", "Diane", "Ellen"] for name in names: print (name) Alice Bob Cassie Diane Ellen Example 2-2: for word in names: print ("Hello " + word) Hello Alice Hello Bob Hello Cassie Hello Diane Hello Ellen 2. # Print a list if the first character is a vowel # name[0] is the abbreviation of name[0] in ["A", "E", "I", "O", "U"] Example: names = ["Alice", "Bob", "Castle", "Diane", "Ellen"] for name in names: if name[0] in "AEIOU": print(name + " starts with a vowel") Alice starts with a vowel Ellen starts with a vowel 3. #Build up a list of names start with vowels ## We need an empty variable storage so we gonna use: vowel_names ### use APPEND to store the vowel names in the empty variable storage: vowel_names Example: vowel_names = [] for name in names: if name[0] in "AEIOU": vowel_names.append(name) print Vowel_names ['Alice', 'Ellen'] 4. # Add up everything ## start "total" as an empty variable storage chosen so we can loop all the prices ### total = total + price (means we add all the prices and store it in total) #### you can use build in function SUM() to add up too: sum(prices) prices = [1.5, 2.35, 5.99, 16.49] total = 0 for price in prices: total = total + price print total 26.33

General Rules for IF-Statements

1. Every if-statement must have an else. 2. if this else would never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors. 3. never nest IF-Statements more than two deep and always try to to them one deep. 4. Treat IF-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after. 5. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.

General Rules for Loops

1. Use a WHILE-loop only to loop forever, and that means probably never. This only applies to Python; other languages are different. 2. Use a FOR-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.

= and ==

= (single-equal) assigns the value on the right to a variable on the left. == (double-equal) tests if two things have the same value.

String (Immutability)

>>> S 'Spam' >>> S[0] = 'z' # Immutable objects cannot be changed ...error text omitted... TypeError: 'str' object does not support item assignment >>> S = 'z' + S[1:] # But we can run expressions to make new objects >>> S 'zpam' >>> S = 'shrubbery' >>> L = list(S) # Expand to a list: [...] >>> L ['s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y'] >>> L[1] = 'c' # Change it in place >>> ''.join(L) # Join with empty delimiter 'scrubbery' >>> B = bytearray(b'spam') # A bytes/list hybrid (ahead) >>> B.extend(b'eggs') # 'b' needed in 3.X, not 2.X >>> B # B[i] = ord(c) works here too bytearray(b'spameggs') >>> B.decode() # Translate to normal string 'spameggs'

String (methods)

>>> S = 'Spam' >>> S.find('pa') # Find the offset of a substring in S 1 >>> S 'Spam' >>> S.replace('pa', 'XYZ') # Replace occurrences of a string in S with another 'SXYZm' >>> S 'Spam' >>> line = 'aaa,bbb,ccccc,dd' >>> line.split(',') # Split on a delimiter into a list of substrings ['aaa', 'bbb', 'ccccc', 'dd'] >>> S = 'spam' >>> S.upper() # Upper- and lowercase conversions 'SPAM' >>> S.isalpha() # Content tests: isalpha, isdigit, etc. True >>> line = 'aaa,bbb,ccccc,dd\n' >>> line.rstrip() # Remove whitespace characters on the right side 'aaa,bbb,ccccc,dd' >>> line.rstrip().split(',') # Combine two operations ['aaa', 'bbb', 'ccccc', 'dd'] >>> '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting expression (all) 'spam, eggs, and SPAM!' >>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting method (2.6+, 3.0+) 'spam, eggs, and SPAM!' >>> '{}, eggs, and {}'.format('spam', 'SPAM!') # Numbers optional (2.7+, 3.1+) 'spam, eggs, and SPAM!' >>> '{:,.2f}'.format(296999.2567) # Separators, decimal digits '296,999.26' >>> '%.2f | %+05d' % (3.14159, −42) # Digits, padding, signs '3.14 | −0042'

String (sequence operations)

>>> S = 'Spam' # Make a 4-character string, and assign it to a name >>> len(S) # Length 4 >>> S[0] # The first item in S, indexing by zero-based position 'S' >>> S[1] # The second item from the left 'p' >>> S[-1] # The last item from the end in S 'm' >>> S[-2] # The second-to-last item from the end 'a' >>> S # A 4-character string 'Spam' >>> S[1:3] # Slice of S from offsets 1 through 2 (not 3) 'pa' >>> S[1:] # Everything past the first (1:len(S)) 'pam' >>> S # S itself hasn't changed 'Spam' >>> S[0:3] # Everything but the last 'Spa' >>> S[:3] # Same as S[0:3] 'Spa' >>> S[:-1] # Everything but the last again, but simpler (0:-1) 'Spa' >>> S[:] # All of S as a top-level copy (0:len(S)) 'Spam' >>> S 'Spam' >>> S + 'xyz' # Concatenation 'Spamxyz' >>> S # S is unchanged 'Spam' >>> S * 8 # Repetition 'SpamSpamSpamSpamSpamSpamSpamSpam'

Assigning multiple variables to Tuples

>>> marx_tuple = ('Groucho', 'Chico', 'Harpo') >>> a, b, c = marx_tuple >>> a 'Groucho' >>> b 'Chico' >>> c 'Harpo'

Find out how many items in the list using LEN()

>>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> len(marxes) 3

Tuples: Exchange values in one statement without using a temporary variable

>>> password = 'swordfish' >>> icecream = 'tuttifrutti' >>> password, icecream = icecream, password >>> password 'tuttifrutti' >>> icecream 'swordfish' >>>

return

A function can take some input (usually one or more variables or values) and return some output (usually a single value). Example: def add(a, b): print "ADDING %s + %s" % (a, b) return a + b age = add(30, 5) print "Age: %s" % age

Python Method vs Function

A very general definition of the main difference between a Function and a Method: Functions are defined outside of classes, while Methods are defined inside of and part of classes. ... A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). The one difference between methods and normal functions is that all methods have one required argument. This argument is conventionally named self; I've never seen a programmer use any other name for this variable (convention is a very powerful thing). There's nothing stopping you, however, from calling it this or even Martha.

Python List(): Extracting single value

As with strings, you can extract a single value from a list by specifying its offset: Example: >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes[0] 'Groucho' >>> marxes[1] 'Chico' >>> marxes[2] 'Harpo' Example: >>> marxes[-1] 'Harpo' >>> marxes[-2] 'Chico' >>> marxes[-3] 'Groucho' >>>

Dictionary

Dictionaries are indexed by key, and nested dictionary entries are referenced by a series of indexes (keys in square brackets). When Python creates a dictionary, it stores its items in any left-to-right order it chooses; to fetch a value back, you supply the key with which it is associated, not its relative position. Example: % python # Make a dictionary >>> D = {'spam': 2, 'ham': 1, 'eggs': 3} # Fetch a value by key >>> D['spam'] 2 # Order is "scrambled" >>> D {'eggs': 3, 'spam': 2, 'ham': 1} Notice the end of this example—much like sets, the left-to-right order of keys in a dictionary will almost always be different from what you originally typed. This is on purpose: to implement fast key lookup (a.k.a. hashing), keys need to be reordered in memory. That's why operations that assume a fixed left-to-right order (e.g., slicing, concatenation) do not apply to dictionaries; you can fetch values only by key, not by position.

String (Method) Definition

Every string operation we've studied so far is really a sequence operation—that is, these operations will work on other sequences in Python as well, including lists and tuples. In addition to generic sequence operations, though, strings also have operations all their own, available as methods—functions that are attached to and act upon a specific object, which are triggered with a call expression.

raw_input()

Example 1: print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) ***We put a , (comma) at the end of each print line. This is so print doesn't end the line with a newline character and go to the next line. Example 2: (shorter version of example 1) age = raw_input("How old are you?") height = raw_input("How tall are you?") weight = raw_input(How much do you weigh?") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)

Python Objects Programming

Example: class Point: pass p1 = Point() p2 = Point() p1.x = 5 p1.y = 4 p2.x = 3 p2.y = 6 print(p1.x, p1.y) print(p2.x, p2.y) This code creates an empty Point class with no data or behaviors. Then it creates two instances of that class and assigns each of those instances x and y coordinates to identify a point in two dimensions. All we need to do to assign a value to an attribute on an object is use the syntax<object>.<attribute> = <value>. This is sometimes referred to as dot notation. The value can be anything: a Python primitive, a built-in data type, another object. It can even be a function or another class!

Add/Change/Delete a Dictionary

Example: >>> D {'eggs': 3, 'spam': 2, 'ham': 1} >>> D['ham'] = ['grill', 'bake', 'fry'] # Change entry (value=list) >>> D {'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']} >>> del D['eggs'] # Delete entry >>> D {'spam': 2, 'ham': ['grill', 'bake', 'fry']} >>> D['brunch'] = 'Bacon' # Add new entry >>> D {'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']}

Delete an item in the list using DEL

Example: >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo', 'Karl'] >>> del marxes[-1] >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] NOTE del is a Python statement, not a list method—you don't say marxes[-2].del(). It's sort of the reverse of assignment (=): it detaches a name from a Python object and can free up the object's memory if that name was the last reference to it.

Combine something to strings in the list by using JOIN()

Example: >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> ', '.join(marxes) 'Groucho, Chico, Harpo' You might be thinking that this seems a little backward. join() is a string method, not a list method. You can't say marxes.join(', '), even though it seems more intuitive. The argument to join() is a string or any iterable sequence of strings (including a list), and its output is a string. If join() were just a list method, you couldn't use it with other iterable objects such as tuples or strings. If you did want it to work with any iterable type, you'd need special code for each type to handle the actual joining. It might help to remember: join() is the opposite of split(), as demonstrated here: >>> friends = ['Harry', 'Hermione', 'Ron'] >>> separator = ' * ' >>> joined = separator.join(friends) >>> joined 'Harry * Hermione * Ron' >>> separated = joined.split(separator) >>> separated ['Harry', 'Hermione', 'Ron'] >>> separated == friends True

Count occurrences of a value in list by using COUNT()

Example: >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes.count('Harpo') 1 >>> marxes.count('Bob') 0 Example: >>> snl_skit = ['cheeseburger', 'cheeseburger', 'cheeseburger'] >>> snl_skit.count('cheeseburger') 3

Python function in Dictionary

Example: >>> menu(entree='beef', dessert='bagel', wine='bordeaux') {'dessert': 'bagel', 'wine': 'bordeaux', 'entree': 'beef'}

Python LIST of LISTS

Example: >>> small_birds = ['hummingbird', 'finch'] >>> extinct_birds = ['dodo', 'passenger pigeon', 'Norwegian Blue'] >>> carol_birds = [3, 'French hens', 2, 'turtledoves'] >>> all_birds = [small_birds, extinct_birds, 'macaw', carol_birds] # List of List of all_birds >>> all_birds [['hummingbird', 'finch'], ['dodo', 'passenger pigeon', 'Norwegian Blue'], 'macaw', [3, 'French hens', 2, 'turtledoves']] # Calling out the first all_birds list Example: >>> all_birds[0] ['hummingbird', 'finch'] # Can call multiple layer: Example: >>> all_birds[1][0] 'dodo'

Python Function - Calling a function returning a "value" example 2

Example: >>> def commentary(color): ... if color == 'red': ... return "It's a tomato." ... elif color == "green": ... return "It's a green pepper." ... elif color == 'bee purple': ... return "I don't know what it is, but only bees can see it." ... else: ... return "I've never heard of the color " color "." ... >>> Call the function commentary() with the string argument 'blue'. >>> comment = commentary('blue') The function does the following: Assigns the value 'blue' to the function's internal color parameter Runs through the if-elif-else logic chain Returns a string Assigns the string to the variable comment What do we get back? >>> print(comment) I've never heard of the color blue.

from os.path import exists

Example: from sys import argv # import argument variable from module "sys" from os.path import exists # import exists command from os.path module. It basically if something (file) exist by spitting out TRUE or FALSE script, from_file, to_file = argv # same argument variable where you call out or work on multiple files print "Copying from %s to %s" % (from_file, to_file) # print out statement telling the reader you are copying from_file to to_file open(from_file) # Open from_file and assign this to variable "in_file" # Read variable in_file and assign it to indata print "The input file is %s bytes long" % len(from_file) # print out the length of the varialble indata print "Does the output file exist? %r" % exists(to_file) # ask and print out if to_file file exist or not (TRUE or FALSE) print "Ready, hit RETURN to constinue, CTRL-C to abort" raw_input() # Print out RETURN to continue or CTRL-C and you put raw_input() for reader's resonse out_file = open(to_file, 'w') # Open and truncate "to_file" and assign it to variable out_file out_file.write(from_file) # Write the out_file with the content from indata print "Alright, all done." out_file.close() # Close and save in_data.close() # Close and save

Python Functions

Function: a named piece of code, separate from all others. A function can take any number and type of input parameters and return any number and type of output results. You can do two things with a function: Define it Call it To define a Python function, you type def, the function name, parentheses enclosing any input parameters to the function, and then finally, a colon (:). Example: >>> def do_nothing(): pass Even for a function with no parameters like this one, you still need the parentheses and the colon in its definition. The next line needs to be indented, just as you would indent code under an if statement. Python requires the pass statement to show that this function does nothing. It's the equivalent of This page intentionally left blank (even though it isn't anymore). You call this function just by typing its name and parentheses. It works as advertised, doing nothing very well: >>> do_nothing() >>>

Example of writing your own Function

Here, we have a function that accepts a first, middle, and last name. Not everyone has a middle name (or wants to enter it), so we make the default value for middle an empty string. Example: >>> def print_welcome(first, last, middle=''): ... print "Welcome, {} {} {}!".format(first, middle, last) ... print "Enjoy your stay!" ... >>> print_welcome(first = "James", last = "Grinnell") Welcome, James Grinnell! Enjoy your stay! >>> print_welcome(first = "Katie", middle = "Alison", last="Cunningham") Welcome, Katie Alison Cunningham! Enjoy your stay! Why aren't the parameters defined as (first, middle='', last)? One of the rules of setting defaults is that you define them last in the function definition. All the parameters that must be defined by whatever is calling the function should go first, so Python fills them first. After providing the parameters that have no defaults, you can start defining parameters that have defaults. So far, we've been running blocks of code, then returning to the main program. Many times, though, we want the function to give us a value. For example, what if we want a function that totals up all the values in a list and then gives us that value so we can use it later? In this case, we use return. Example: >>> def get_square_and_cube(number): ... square = number ** 2 ... cube = number ** 3 ... return square, cube ... >>> result = get_square_and_cube(5) >>> result (25, 125) or >>> def get_square_and_cube(number): ... square = number ** 2 ... cube = number ** 3 ... return square, cube ... >>> square, cube = get_square_and_cube(3) >>> square 9 >>> cube 27 Lastly, you don't need to return a value when you use a return statement. Sometimes, you just want to go back to the main program rather than run the rest of the code in the function. Here, in check_year, we return to the main program if the year is four characters long: >>> def check_year(year): ... if len(year) != 4: ... print "{} is invalid as a year.".format(year) ... return ... print "Good, that seems to work as a year!" ... >>> check_year("80") 80 is invalid as a year. Because "80" has a length of two, the function prints out an error statement and returns to the main program rather than telling the user that the value they entered is good.

Figure out where the item is positioned in the list using INDEX()

If you want to know the offset of an item in a list by its value, use index(): Example: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> marxes.index('Chico') 1

Delete an item in the list using REMOVE()

If you're not sure or don't care where the item is in the list, use remove() to delete it by value. Example: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] >>> marxes.remove('Gummo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo']

from sys import argv

Import argument variable from sys module Usage 1: (script with 1 argument) from sys import argv script, user_name = argv Usage 2: (script with 3 arguments) from sys import argv script, first, second, third = argv Example: from sys import argv script, user_name = argv prompt = '> ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name, likes = raw_input(prompt) print "Where do you live %s?" % user_name lives = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) print """ Alright, so you said %r about liking me. You live in %r. Not sure where that is. And you have a %r computer. Nice. """ % (likes, lives, computer)

Dictionary: Get()

In realistic programs that gather data as they run, you often won't be able to predict what will be in a dictionary before the program is launched, much less when it's coded. Fetching a nonexistent key is normally an error, but the get method returns a default value—None, or a passed-in default—if the key doesn't exist. It's an easy way to fill in a default for a key that isn't present, and avoid a missing-key error when your program can't anticipate contents ahead of time Example: # A key that is there >>> D.get('spam') 2 # A key that is missing >>> print(D.get('toast')) None >>> D.get('toast', 88) 88

len()

It gets the length of the string that you pass to it then returns that as a number.

Python Functions - Calling a function returning a "value"

Let's try a function that has no parameters but returns a value: Example 1 >>> def agree(): ... return True ... At this point, it's time to put something between those parentheses. Let's define the function echo() with one parameter called anything. It uses the return statement to send the value of anything back to its caller twice, with a space between: >>> def echo(anything): ... return anything ' ' anything ... >>> Now let's call echo() with the string 'Rumplestiltskin': >>> echo('Rumplestiltskin') 'Rumplestiltskin Rumplestiltskin' The values you pass into the function when you call it are known as arguments. When you call a function with arguments, the values of those arguments are copied to their corresponding parameters inside the function. In the previous example, the function echo() was called with the argument string 'Rumplestiltskin'. This value was copied within echo() to the parameter anything, and then returned (in this case doubled, with a space) to the caller. echo() -> function Rumplestiltskin -> argument anything -> parameter

Python LISTS (mutable)

Lists are mutable, meaning you can insert and delete elements with great enthusiasm. Lists are good for keeping track of things by their order, especially when the order and contents might change. A list is made from zero or more elements, separated by commas, and surrounded by square bracket Example: >>> empty_list = [ ] >>> weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] >>> big_birds = ['emu', 'ostrich', 'cassowary'] >>> first_names = ['Graham', 'John', 'Terry', 'Terry', 'Michael'] You can also make an empty list with the list() function Example: >>> another_empty_list = list() >>> another_empty_list []

palindrome (backward = forward)

Method 1: def palindrome(s): s = s.replace(' ','') # This replaces all spaces " " with no space ''. (Fixes issues with strings that have spaces) return s == s[::-1] # Check through slicing

pangram (word or sentence that contains all alphabets)

Method 1: Using a def function def is_pangram(s): return not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower()) set() creates a data structure which can't have any duplicates in it, and here: The first set is the (English) alphabet letters, in lowercase The second set is the characters from the test string, also in lowercase. And all the duplicates are gone as well. Subtracting things like set(..) - set(..) returns the contents of the first set, minus the contents of the second set. set('abcde') - set('ace') == set('bd'). In this pangram test: we take the characters in the test string away from the alphabet If there's nothing left, then the test string contained all the letters of the alphabet and must be a pangram. If there's something leftover, then the test string did not contain all the alphabet letters, so it must not be a pangram. any spaces, punctuation characters from the test string set were never in the alphabet set, so they don't matter. set(..) - set(..) will return an empty set, or a set with content. If we force sets into the simplest True/False values in Python, then containers with content are 'True' and empty containers are 'False'. not also changes True -> False, and False -> True. Which is useful here, because (alphabet used up) -> an empty set which is False, but we want is_pangram to return True in that case. And vice-versa, (alphabet has some leftovers) -> a set of letters which is True, but we want is_pangram to return False for that. Then return that True/False result. Method 2: Using String Module import string def ispangram(str1, alphabet=string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(str1.lower())

Definition of Function

Most programs are made of smaller chunks of code that can be reused over and over. You can give these chunks information, which can change what is calculated, displayed, or stored. You may have a chunk that prints out a welcome message for a logged-in user. Another chunk may calculate the total of all the items in a list. We call these chunks of code functions. Functions in Python need three things: a name, a block of code, and (optionally) some variables that hold what values you send the function (we call these parameters). The format looks like this: Click here to view code image def function_name(parameter1, parameter2) code code code code

\n

New (next) line

Python Functions - Calling a function

Now, let's define and call another function that has no parameters but prints a single word: Example 1 >>> def make_a_sound(): ... print('quack') ... >>> make_a_sound() quack

Python LIST(): Convert other data types to LIST

Python's list() function converts other data types to lists. Example: >>> list('cat') ['c', 'a', 't'] Convert a TUPLE to LIST Example: >>> a_tuple = ('ready', 'fire', 'aim') >>> list(a_tuple) ['ready', 'fire', 'aim']

Tuples = Immutable list

Similar to lists, tuples are sequences of arbitrary items. Unlike lists, tuples are immutable, meaning you can't add, delete, or change items after the tuple is defined. So, a tuple is similar to a constant list.

Reorder items in list with SORT() or SORTED()

Sorted (it doesn't change the original list): >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> sorted_marxes = sorted(marxes) >>> sorted_marxes ['Chico', 'Groucho', 'Harpo'] Sort (change the order of the original list): >>> marxes ['Groucho', 'Chico', 'Harpo'] >>> marxes.sort() >>> marxes ['Chico', 'Groucho', 'Harpo'] If the items in the list are numeric, they're sorted by default in ascending numeric order. If they're strings, they're sorted in alphabetical order

Combine LIST with INSERT()

The append() function adds items only to the end of the list. When you want to add an item before any offset in the list, use insert(). Offset 0 inserts at the beginning. An offset beyond the end of the list inserts at the end, like append(), so you don't need to worry about Python throwing an exception. Example: >>> marxes.insert(3, 'Gummo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] >>> marxes.insert(10, 'Karl') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo', 'Karl']

Object-Oriented Programming: Objects Intro

The class definition starts with the class keyword. This is followed by a name (of our choice) identifying the class, and is terminated with a colon. Example: class MyFirstClass: pass Since our first class doesn't actually do anything, we simply use the pass keyword on the second line to indicate that no further action needs to be taken.

open()

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. Example: randomvariable = open (filename, 'r') ---> Default mode randomvariable = open (filename, 'w') randomvariable = open(filename, 'a')

Python List: APPEND

The traditional way of adding items to a list is to append() them one by one to the end. Example: >>> marxes.append('Zeppo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo']

%s %r %d

These are Formatters. They tell Python to take the variable on the right and put it in to replace the %s with its value. The %r is best for debugging , and the other formats are for actually displaying variables to users. %r is printing out the raw representation of what you typed, which is going to include the original escape sequences.

Creating Tuples

To make a tuple with one or more elements, follow each element with a comma. This works for one-element tuples: >>> one_marx = 'Groucho', >>> one_marx ('Groucho',) Python includes parentheses when echoing a tuple. You don't need them—it's the trailing commas that really define a tuple—but using parentheses doesn't hurt. You can use them to enclose the values, which helps to make the tuple more visible: Example: >>> marx_tuple = 'Groucho', 'Chico', 'Harpo' >>> marx_tuple ('Groucho', 'Chico', 'Harpo') >>> marx_tuple = ('Groucho', 'Chico', 'Harpo') >>> marx_tuple ('Groucho', 'Chico', 'Harpo')

Assign with "=" in the list. It will be all connected.

When you assign one list to more than one variable, changing the list in one place also changes it in the other (THEY ARE ALL CONNECTED!!) Example: >>> a = [1, 2, 3] >>> a [1, 2, 3] >>> b = a >>> b [1, 2, 3] >>> a[0] = 'surprise' >>> a ['surprise', 2, 3] >>> b ['surprise', 2, 3]

While Loop

While loop will run infinitely until break statement or exception inside loop. The basic syntax for while expression is while <expression> . Every iteration your python interpreter checks if <expression> evaluates to True . If it doesn't the loop ends. Now in case of while True expression is True and evaluates to True, always; hence running forever. For example: while i < 6: print "something something something" while TRUE

Assign using COPY() in the list. It will not be connected.

You can copy the values of a list to an independent, fresh list by using any of these methods: The list copy() function The list() conversion function The list slice [:] Example: >>> a = [1, 2, 3] >>> b = a.copy() >>> c = list(a) >>> d = a[:] >>> a[0] = 'integer lists are boring' >>> a ['integer lists are boring', 2, 3] >>> b [1, 2, 3] >>> c [1, 2, 3] >>> d [1, 2, 3]

Delete an item in the list using POP()

You can get an item from a list and delete it from the list at the same time by using pop(). If you call pop() with an offset, it will return the item at that offset; with no argument, it uses -1. So, pop(0) returns the head (start) of the list, and pop() or pop(-1) returns the tail (end), as shown here: Example: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> marxes.pop() 'Zeppo' >>> marxes ['Groucho', 'Chico', 'Harpo'] >>> marxes.pop(1) 'Chico' >>> marxes ['Groucho', 'Harpo']

Combine LIST by using EXTEND() or +=

You can merge one list into another by using extend() or += Extend() Example: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes.extend(others) >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo', 'Gummo', 'Karl'] += Example: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes += others >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo', 'Gummo', 'Karl'] Example 3: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> others = ['Gummo', 'Karl'] >>> marxes.append(others) >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo', ['Gummo', 'Karl']]

Set default parameter in Python Function

You can specify default values for parameters. The default is used if the caller does not provide a corresponding argument. This bland-sounding feature can actually be quite useful. Example: >>> def menu(wine, entree, dessert='pudding'): ... return {'wine': wine, 'entree': entree, 'dessert': dessert} #This time, try calling menu() without the dessert argument: >>> menu('chardonnay', 'chicken') {'dessert': 'pudding', 'wine': 'chardonnay', 'entree': 'chicken'} #If you do provide an argument, it's used instead of the default: >>> menu('dunkelfelder', 'duck', 'doughnut') {'dessert': 'doughnut', 'wine': 'dunkelfelder', 'entree': 'duck'}

\\ \' \"

\\ - Backslash \' - single-quote \" - double quote Example: "I am 6'2\" tall." -> escape double-quote inside string 'I am 6\'2" tall.' -> escape single-quote inside string

x += y

can be written as x = x + y

truncate() method

delete the content in the file Example: target.truncate()

from sys import exit

exit module. On many operating systems a program can abort with exit(0), and the number passed in will indicate an error or not. If you do exit(1) then it will be an error, but exit(0) will be a good exit.

String Module

import string text = "Monty Python's Flying Circus" print "upper", "=>", string.upper(text) print "lower", "=>", string.lower(text) print "split", "=>", string.split(text) print "join", "=>", string.join(string.split(text), "+") print "replace", "=>", string.replace(text, "Python", "Java") print "find", "=>", string.find(text, "Python"), string.find(text, "Java") print "count", "=>", string.count(text, "n") upper => MONTY PYTHON'S FLYING CIRCUS lower => monty python's flying circus split => ['Monty', "Python's", 'Flying', 'Circus'] join => Monty+Python's+Flying+Circus replace => Monty Java's Flying Circus find => 6 -1 count => 3

readline()

read every single line each time you call

read() method

read the whole file Example: from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read()

seek() Method

seek(0) - Moving to the start of the file seek(1) - reference point is the current file position seek(2) - reference point is the at the end of file Example: def rewind(f): f.seek(0)

.split() len() .pop() .append() .join() WHILE Loop

ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there are not 10 things in that list. Let's fix that" stuff = ten_things.split(' ') more stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next one stuff.append(next_one) print "There are %d items now." % len(stuff) print "There we go: ", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] print stuff.pop() print ' '.join(stuff) print '#'.join(stuff[3:5])

String: "FIND" Method

the string find method is the basic substring search operation (it returns the offset of the passed-in substring, or −1 if it is not present) Example: >>> S = 'Spam' >>> S.find('pa') # Find the offset of a substring in S 1

String: "REPLACE" Method

the string replace method performs global searches and replacements Example: >>> S 'Spam' >>> S.replace('pa', 'XYZ') # Replace occurrences of a string in S with another 'SXYZm'


Ensembles d'études connexes

Phases of Wound healing Acute Wound/ Wound Healing

View Set

chp.8 ,section 1: Geography and Early Japan

View Set

Personal Finance Chapter 7 Study Guide

View Set

Final Quiz - Chapter 26 and Appendix D

View Set