• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/102

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

102 Cards in this Set

  • Front
  • Back

Floor division

>>> //

Modulus

>>> x % y

Convert to string

>>> str(x)

Convert to integer

>>> int(x)

Convert to float

>>> float(x)

Length of string

>>> len("string")




#returns the number of characters in the string

Convert string to lowercase

>>> string.lower()

Convert string to uppercase

>>> string.upper()

User input

>>> input("User prompt: ")




#This is changed from Python2, and fulfills the function of raw_input()

Display current date/time (datetime)

>>> from datetime import datetime


>>> date = datetime.now()


>>> print ("%02d/%02d/%04d" % (date.month, date.day, date.year))


>>> print ("%02d:%02d:%02d" % (date.hour, date.minute, date.second))

CPython
CPython is Guido van Rossum's reference version of the Python computing language. It's most often called simply "Python"; speakers say "CPython" generally to distinguish it explicitly from other implementations.

Jython

Jython is a Python interpreter implemented in Java. It can be fully integrated into existing Java applications; alternatively, Python applications can be compiled into a collection of Java classes. Python programs running on the Jython virtual machine have full access to the Java classes and APIs.

IronPython

IronPython is an open source implementation of Python for the .NET CLR and Mono, originally created by Jim Hugunin. IronPython is a Python compiler. It compiles Python code to in memory bytecode before execution (which can be saved to disk, making binary only distributions possible).

Stackless
An enhanced Python implementation that doesn't use the C stack and is oriented toward concurrency. It is easier to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines.
PyPy
PyPy is an alternative implementation of Python. It often runs faster because it is a just-in-time compiler. Functionally, PyPy is designed around the technique known as meta-tracing, which transforms an interpreter into a tracing just-in-time compiler. Since interpreters are usually easier to write than compilers, but run slower, this technique can make it easier to produce efficient implementations of programming languages.
Cython
Cython is a programming language that aims to be a superset of the Python programming language, designed to give C-like performance with code that is written mostly in Python with optional additional C-inspired syntax
Shed Skin
Shed Skin is a Python to C++ programming language compiler. It is experimental, and can translate pure, but implicitly statically typed Python programs into optimized C++. It can generate stand-alone programs or extension modules that can be imported and used in larger Python programs.
Psyco

Psyco was a specializing just-in-time compiler for Python originally developed by Armin Rigo and further maintained and developed by Christian Tismer. Development ceased in December, 2011. It was not just another Python implementation, but rather a component that extends the byte code execution model to make programs run faster.

Frozen Binaries

Frozen binaries bundle together the byte code of your program files, along with the PVM (interpreter) and any Python support files your program needs, into a single package. There are some variations on this theme, but the end result can be a single binary executable program that can easily be shipped to customers. (pythonstudio.us)
Import module & attributes

>>> import module #Grab the whole module


>>> from module import attribute #Import specific




>>> exec(open("module.py").read() #executes the module once without importing it

Reload module

>>> reload(module)




#reloads for file changes

Fetch module names

>>> dir(module)




#fetches a list of names available in a module

Python Hierarchy

1. Programs are composed of modules


2. Modules contain statements


3. Statements contain expressions


4. Expressions create and process objects

Numbers (example literals)

1234, 3.1415, 3+4j, 0b111, Decimal(), Fraction()

Strings (example literals)

'spam'


"Monty's"


'Monty\'s'


b'a\x01c'


u'sp\xc4m'

Lists (example literals)

[1, [2, 'three'], 4.5], list(range(10))

Dictionaries (example literals)

{'food': 'spam', 'taste': 'yum'}, dict(hours=10)

Tuples (example literals)

(1, 'spam', 4, 'U'), tuple('spam'), namedtuple

Files (example literals)

open('eggs.txt'), open(r'C:\ham.bin', 'wb')

Sets (example literals)

set('abc'), {'a', 'b', 'c'}

Printing/returning floats

# Like many objects, there is a precise and user-friendly form


>>> 3.1415 * 2; 6.283000000000004 #repr: as code


>>> print(3.1415 * 2); 6.283 #str: user-friendly

Indexing strings

>>> string_var[0] #first character in string




>>> string_var[-1] #last character in string


(OR: string_var[len(string_var) - 1] #the 'hard way'




>>> string_var[-2] #second-to-last

Slicing strings

#string[first_index_inclusive:to_last_index_noninclusive]




>>> string_var = "string"


>>> string_var[1:4]; "tri"


>>> string_var[:3] #prints index 0-2


>>> string_var[:-1] #prints all but the last


>>> string_var[:] # all of string_var as a top-level copy (0:len(S))

String concatenation

>>> 'string one' + ' and two'




>>> string.__add__('and two') #the underlying method, not recommended for use

String immutability

Strings are immutable; a new variable must always be assigned, or a new string is always created.




>>> string[0] = 'x' #WRONG


TypeError: 'str' object does not support item assignment




>>> string = 'x' + string[1:] #RIGHT

Immutable objects

Numbers, strings, and tuples are immutable; they cannot be changed in place after they are created.

Find offset in string

>>> string = 'string'


>>> string.find('tr'); 1

Replace occurrence in a string

>>> string.replace(substring, replacement)



>>> string = 'string'


>>> string.replace('i', 'o')


>>> string; 'strong'

Split string on a delimiter into a list of substrings

>>> string.split(delimiter)



>>> string = 's,t,r,i,n,g'


>>> string.split(','); ['s', 't', 'r', 'i', 'n', 'g']

Content tests on strings

returns True or False




>>> string.isalpha()


#test for alphabetic


>>> string.isdigit()


#test for numeric

String - strip characters

string.xstrip("chars") #"chars" is optional




>>> string = 'sstrings'


>>> string.rstrip() #removes whitespace from right side


>>> string.lstrip("s"); "trings" #removes "s"s from left side


>>> string.strip("s"); "tring" #removes "s"s from both sides


>>> string.strip("s").split("i"); ["tr", "ng"] #combining operations

Formatting expressions

>>> '%s, eggs, and %s' % ('spam', 'SPAM!')


>>> '{0}, eggs, and {1}'.format('spam', 'SPAM!')


>>> '{}, eggs, and {}'.format('spam', 'SPAM!')


>>> '{x}, eggs, and {y}'.format(x='spam', y='SPAM!')

Formatting digit strings

>>> '{:,.2f}'.format(296999.2567)


'296,999.26' # Separators, decimal digits




>>> '%.2f | %+05d' % (3.14159, -42)


'3.14 | -0042' # Digits, padding, sign

Paragraph formatting in strings

\n : end-of-line


\t : tab

Unicode formatting in strings

>>> u'sp\xc4m'; 'spÄm' #Unicode


>>> b'a\x01c'; b'a\x01c' #byte


>>> u'sp\u00c4m'; 'spÄm' #2.X Unicode, works in 3.3+


>>> string.encode('utf8') #encode to 4 bytes in UTF-8


>>> string.encode('utf16') #encode to 10 bytes in UTF-16

List

General sequence, ordered collection of arbitrarily typed objects. Mutable and no fixed size.




>>> list = [item, 'item', 1734]

Indexing lists

>>> list[0] # index by position


>>> list[:-1] #slicing returns a new list

Concatenating lists

>>> list = [1, 2, 3]


>>> list + [4, 5, 6]


[1, 2, 3, 4, 5, 6] #generates a new list


>>> list * 2


[1, 2, 3, 1, 2 ,3]

Add object to end of list

>>> list.append(object)

Delete object from list

>>> list.pop(2) #removes object at index 2


>>> del list[2] #also works

Nested lists and matrices

>>> list = [[1, 2, 3],


. . . [4, 5, 6],


. . . [7, 8, 9]]

List comprehension expression on matrices

>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


>>> column2 = [row[1] for row in matrix]


[2, 5, 8] # finding a column


>>> [row[1] + 1 for row in matrix if row[1] != 2]


[6, 9] #complex expressions


>>> diagonal = [matrix[i][i] for i in [0, 1, 2]]


[1, 5, 9] #finding a diagonal

List comprehension/iteration over a string

>>> string = 'string'

>>> doubled = [c * 2 for c in string]


['ss', 'tt', 'rr', 'ii', 'nn', 'gg']

Range

list(range(start_inclusive, end_noninclusive, interval))


>>> list(range(-6, 7, 2)


[-6, -4, -2, 0, 2, 4, 6]

Add together all items in an iterable

sum(iterable, start) #the 'start' is a number to be added in addition to objects in the iterable (default 0)



>>> list = [1, 2, 3]


>>> sum(list); 6


>>> sum(list, 1); 7

Reverse a list or tuple

>>> list[::-1] #the most idiomatic way

Check that x is a multiple of y

>>> if x % y == 0

Pure vs impure functions

Pure functions return a value that depends on only their arguments.


>>>def pure_function(x, y): temp = x + 2*y return temp / (2*x + y)



>>> some_list = []


>>> def impure(arg):


. . . some_list.append(arg)

Reasons for using pure functions

Using pure functions has both advantages and disadvantages. Pure functions are:


- easier to reason about and test.


- more efficient. Once the function has been evaluated for an input, the result can be stored and referred to the next time the function of that input is needed, reducing the number of times the function is called. This is called memoization. - easier to run in parallel.

Map

The function map takes a function and an iterable as arguments, and returns a new iterable with the function applied to each argument.



>>> list_result = list(map(func, iterable))


>>> result2 = map(lambda, iterable))

Filter

The function filter filters an iterable by removing items that don't match a predicate (a function that returns a Boolean).



>>> filtered_list = list(filter(function, iterable))

Magic methods for operators

__sub__ for -


__mul__ for *


__truediv__ for /


__floordiv__ for //


__mod__ for %


__pow__ for **


__and__ for &


__xor__ for ^


__or__ for |

r Methods

:)

Magic methods for comparisons

__lt__ for <


__le__ for <=


__eq__ for ==


__ne__ for !=


__gt__ for >


__ge__ for >=



If __ne__ is not implemented, it returns the opposite of __eq__.

Garbage collection

The process of deleting objects when they are no longer needed

Using lists as stacks

>>> list.append(item)


>>> list.pop()

Using lists as queues

SLOW method:


>>> queue.insert(0, item)


>>> queue.pop(0)



PREFERRED method:


>>> from collections import deque


>>> queue = deque(["Eric", "John", "Michael"])


>>> queue.append("Terry")


>>> queue.popleft()


'Eric'


>>> queue


deque(['Michael', 'Terry', 'Graham'])

List comprehension

>>> squares = []


>>> for x in range(10):


... squares.append(x**2)


# leaves behind a variable x



>>> squares = list(map(lambda x: x**2, range(10))


# Cleaner.



# Or, equivalently:


>>> squares = [x**2 for x in range(10)]

Join items in list

>>>seperator.join(list)



>>> print(", ".join(["spam", "eggs", "ham"]))#prints "spam, eggs, ham"

Replace substring

>>> string.replace(substring, replacement)



>>> print("Hello ME".replace("ME", "world"))#prints "Hello world"

Check if a string starts or ends with a particular substring

>>> string.startswith(substring))


>>> string.endswith(substring))


#returns Boolean

Find the minimum or maximum of numbers in a list or tuple

>>> min[1, 2, 3] #1


>>> max(1, 2, 3) #3

Find the absolute value

>>> abs(-47) # 47

iterate through the values and indices of a list simultaneously

>>> list = [1, 2, 10]


>>> for value in enumerate(list): print(value)


(0, 1); (1, 2); (2, 10)

Higher-order functions

Functions that take other functions as arguments


>>> def hi_func(func, arg):

Extend list by appending all items from the iterable

>>> list.extend(iterable)

Insert an item at a given position in a list

>>> list.insert(index, item)

Remove first item from a list whose value is x

>>> list.remove(x)
#raises a ValueError if there is no such item

Remove an item at a given position in a list and return it

>>> list.pop(index)




>>> list.pop() #removes and returns the last item by default




# "del list[index]" removes without returning

Remove all items from a list

>>> list.clear()




or:


>>> del list[:]

Return the index of the first item in a list with value x

>>> list.index(x, index_start, index_end)




# start and end, which act as slices, are optional


>>> list.index(x)

Return the number of times x appears in a list

>>> list.count(x)

Sort the items of a list in place

>>> list.sort()




# Has two optional arguments:


>>> list.sort(key=None, reverse=False)


# key: Default value is None. "specifies a function of one argument that is used to extract a comparison key from each element in the iterable"


# reverse: is a Boolean value. If set to True, the list is sorted in reverse

Reverse the elements of a list in place

>>> list.reverse()

Return a shallow copy of a list

>>> list.copy()




#equivalent to "a[:]"

Remove an item from a list without returning that item

>>> del list[index]

Remove a slice from a list

>>> del list[index_start: index_end]

Create a one-item tuple

>>> singleton_tuple = item,

Create an empty tuple

>>> ()

Create a tuple

>>> tuple = item_1, item_2

Create a set

>>> set = {item, item ... }


# or


>>> set(item, item ... )

Create an empty set

>>> set()




#Note: "{}" will create an empty dictionary, not an empty set

Create a dictionary

>>> {'key1': item1, 'key2', item2, ...}




# or build one via "dict()"


>>> dict([key, item], [key, item], ... )


{'key': item, 'key': item, ...}




# or use a dict comprehension


>>> {x: x**2 for x in (2, 4, 6)}


{2: 4, 4: 16, 6: 36}

Loop through a dictionary and retrieve key-value pairs

>>> for key, item in dict.items():


. . . print(key, item)

Loop through a sequence and retrieve index-value pairs

>>> for index, item in enumerate(iterable):


. . . print(index, item)

Loop over 2+ sequences at a time

>>> sequence1 = ['1', '2', '3']


>>> sequence2 = ['a', 'b', 'c']


>>> for num, lett in zip(sequence1, sequence2):


. . . print(num, lett)


1 a


2 b


3 c

Loop over a sequence in reverse

>>> for item in reversed(sequence):


. . .

Loop over a sequence in sorted order

>>> for item in sorted(sequence):


. . .

Compound data types

- strings: loosey compound in that they're composed of substrings/characters, immutable


- lists: composed of items, mutable


- tuples: composed of items, immutable


- sets: composed of items, not ordered, no duplicates


- dictionaries: consists of key:value pairs, mutable

Determining if a string comes alphabetically before another

>>> if string1 > string2:


. . .




# capital letters come alphabetically before lowercase, so make sure the words match upper or lower

Fetch unique id of a value

id(value)

String search

str.find(string, substring, starting_index)