Python Flashcards
algorithm
A set of specific steps for solving a category of problems
token
basic elements of a language(letters, numbers, symbols)
high-level language
A programming language like Python that is designed to be easy for humans to read and write.
low-level langauge
A programming language that is designed to be easy for a computer to execute; also called machine language or assembly language
keyword
define the language's syntax rules and structure, and they cannot be used as variable names
statement
instruction that the Python interpreter can execute
operators
special tokens that represent computations like addition, multiplication and division
modulus operator
%, works on integers (and integer expressions) and gives the remainder when the first number is divided by the second
evaluate
To simplify an expression by performing the operations in order to yield a single value.
int
A Python data type that holds positive and negative whole numbers
float
A Python data type which stores floating-point numbers. Floating-point numbers are stored internally in two parts: a base and an exponent. When printed in the standard format, they look like decimal numbers
flow of execution
The order in which statements are executed during a program run.
function
A named sequence of statements that performs some useful operation. Functions may or may not take parameters and may or may not produce a result
fruitful function
A function that returns a value when it is called.
local variable
A variable defined inside a function. A local variable can only be used inside its function. Parameters of a function are also a special kind of local variable.
parameter
A name used inside a function to refer to the value which was passed to it as an argument.
boolean function
A function that returns a Boolean value. The only possible values of the bool type are False and True.
None
A special Python value. One use in Python is that it is returned by functions that do not execute a return statement with a return argument.
block
A group of consecutive statements with the same indentation.
boolean expression
An expression that is either true or false.
conditional statement
A statement that controls the flow of execution depending on some condition. In Python the keywords if, elif, and else are used for conditional statements.
conditional statement
One program structure within another, such as a conditional statement inside a branch of another conditional statement
type conversion
An explicit function call that takes a value of one type and computes a corresponding value of another type.
definite iteration
A loop where we have an upper bound on the number of times the body will be executed. Definite iteration is usually best coded as a for loop
increment
Both as a noun and as a verb, increment means to increase by 1.
iteration
Repeated execution of a set of programming statements.
nested loop
A loop inside the body of another loop.
trace
To follow the flow of execution of a program by hand, recording the change of state of the variables and any output produced.
aliases
Multiple variables that contain references to the same object.
clone
To create a new object that has the same value as an existing object. Copying a reference to an object creates an alias but doesn't clone the object.
compound data type
A data type that is itself made up of elements that are themselves values.
decrement
To subtract one from a variable.
dictionary
A collection of key/value pairs that maps from keys to values.
exception
Raised by the runtime system if something goes wrong while the program is running.
file
A named entity, usually stored on a hard drive, floppy disk, or CD-ROM, that contains a stream of characters.
format operator
The % operator takes a format string and a tuple of values and generates a string by inserting the data values into the format string at the appropriate locations.
global variable
Can be seen through a program module, even inside of functions.
immutable type
A compound data type whose elements can NOT be assigned new values.
iteration
To repeat a section of code.
mutable type
A compound data type whose elements can be assigned new values.
nested list
A list that is itself contained within a list.
operator
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
pixel
Smallest addressable element of a picture.
proprioception
on a robot, internal sensing mechanisms. On a human, a sense of the relative positions of different parts of ones own body.
recursion
The process of calling the currently executing function.
robot
mechanism or an artificial entity that can be guided by automatic controls.
sequence
A data type that is made up of elements organized linearly, with each element accessed by an integer index.
short circuit evaluation
When a boolean expression is evaluated the evaluation starts at the left hand expression and proceeds to the right, stopping when it is no longer necessary to evaluateany further to determine the final outcome.
slice
A copy of part of a sequence specified by a series of indices.
traverse
To repeat an operation on all members of a set from the start to the end.
argument
a value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
integer division
An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.
element
One of the values in a list (or other sequence). The bracket operator selects elements of a list.
lambda
A piece of code which can be executed as if it were a function but without a name.(It is also a keyword used to create such an anonymous function.)
module
A file containing definitions and statementsintended to be imported by other programs.
What is the disadvantage of coding in one long sequence structure?
If parts of the duplicated code have to be corrected, the correction has to be made many times.
What type of loop structure repeats the code a specific number of times
Count-controlled loop
What type of loop structure repeats the code based on the value of the Boolean expression
Condition-controlled loop
What is the format for the while clause in Python
while condition : statement
The variable used to keep the running total
Accumulator
_____ is the process of inspecting data that has been input to a program to make sure it is valid before it is used in a computation.
Input validation
What is the structure that causes a statement or a set of statements to execute repeatedly?
Repetition
When will the following loop terminate?while keep_on_going != 999 :
When keep_on_going refers to a value not equal to 999
Which of the following represents an example to calculate the sum of the numbers (accumulator)?
total += number
The while loop is known as a(n) ?? loop because it tests conditions before performing an iteration.
Pretest
The process known as the _____ cycle is used by the CPU to execute instructions in a program.
fetch-decode-execute
The following is an example of an instruction written in which computer language? 10110000
Machine language
What is the encoding technique called that is used to store negative numbers in the computer's memory?
two's complement
The disk drive is a secondary storage device that stores data by _____ encoding it onto a spinning circular disk.
magnetically
True/False: A computer is a single device that performs different types of tasks for its users.
False
True/False: All programs are normally stored in ROM and loaded into RAM as needed for processing.
False
_______________ are small central processing unit chips.
micro processors
_______________ is a type of memory that can hold data for long periods of time, even when there is no power to the computer.
secondary storage
The Python _______________ is a program that can read Python programming statements and execute them.
interpreter
The output of the following print statement is:print 'I\'m ready to begin'
I'm ready to begin
What is the output of the following print statement?print('The path is D:\\sample\\test.')
The path is D:\sample\test
The % symbol is the remainder operator and it is also known as the _______________ operator.
modulus
The decision structure that has two possible paths of execution is known as _____.
double alternative
Boolean variable can reference one of two values: _____.
true or false
A(n) _______________ decision structure provides only one alternative path of execution.
single alternative
In a decision structure, the action is _______________ executed because it is performed only when a certain condition is true.
conditionally
A(n) _______________ operator determines whether a specific relationship exists between two values.
relational
variable
stores a piece of data and gives it a specific name
boolean
a data type that is like a light switch. it can only have two values: true, false
modulo
%. Returns the remainder from a division.
data types
i.e. numbers and booleans
whitespace
separates statements
exponent
**
string
can contain letters, numbers, and symbols
\
tells Python not to end the string
index
the number that each character in a string is assigned
string methods
let you perform specific tasks on strings
What's the difference between = and == in Python?
= is the assignment operator.== is the equality operator.
What does % when printing string
they allow the variables outside the string to enter into the string
integer vs. float
integer is a number w/out a decimal; float is a number with a decimal
indentations in python
mean that there is a code block
%d
Converts a signed integer decimal
%s
Converts String (converts any Python object using str())
%r
String (converts any Python object using repr())
\n
moves whatever's after it to a new ling
"""
to display things as they're written in the .txt file
{}.format(something)
Is the new string.format in Python 3. This is how indexing works: "My first name is {0} and my last name is {1}. You can call me {0}".format("John","Doe").
list_name.append("")
appends thing to lists
for loops
"for x in list_name" ... applies something to every item in a list
my_list.sort()
sorts a list from lowest to highest, or alphabetical
len(my_list)
finds the length of a list
len[2] = 3
The 2nd term of the list is now equal to 3
my_list.insert(4, "cat")
Inserts the string "cat" at the 4th position in a list
my_list[:]
gives you the entire list
my_list[0:]
gives you the whole list, starting at the 0 position
my_list[1:3]
gives you the list starting at the 1st position and ending at the 2nd position
my_list[-1]
gives you the last term in the list
%r is used for...
debugging and display
%s is used for
display
optparse first command
import optparseparser = optparse.OptionParser
adding parser options
parser.add_option('-n, '--new')
after we've added options (in parser)
(options, args) = parser.parse_args()
github steps
1. git status2. git add (adds to staging)3. git commit -m "What you've done"4. git push -u origin master
raw_input()
Raw input prompts the user for an input and then turns that input into a string. In between "(" and ")" the programmer writes the prompt that will prompt the user. When you set raw_input() equal to a variable, that variable becomes what the user inputs.
What is sys.argv?
It allows you to input parameters from the command line.
Control flow statements
if, for, while
Order of Conditionals
1. not2. and3. or
What's a dictionary?
A list of tuples in curly brackets: {"x:y"}; x is a key, y is a value; dictionaries are unordered.
==
means equal to
!=
means doesn't equal
<, <=, >, >=
less than, less than or equal to, greater than, greater than or equal to
and
means that both conditions must be true
or
means one of the conditions must be true
not
gives the opposite of the statement; i.e. "Not True is False"
Order of Precedence
(*), (,/,%), (+,-)
^
matches the beginning of a string
$
matches the end of a string
\b
matches a word boundar
\d
matches any numeric digit
\D
matches any non-numeric character
x?
matches an option x character (in other words, it matches an x wero or one times)
x*
matches x zero or more times
x+
matches x one or more times
x{n,m}
matches an x character at least n times, but not more than m times
(a|b|c|)
matches either a or b or c
(x)
in general is a remembered group. You can get the value of what matched by using the groups() method of the object returned by re.search
basic regex syntax
match = re.search(pattern, text)
round()
function rounds floating point numbersround(1.773) = 2
%r
String format character; use for debugging
%s
String format character; use for user formatting
%d
Integer format character
How many characters to a line?
80 characters
\n
line character; creates new line in string
""" ............."""
String for multiple lines of text; can be multi-line comment
\
escape; tells python to ignore following character, or puts difficult characters into strings when used with specific escape sequences
\t
tab character
raw_input('prompt:')
Reads a line of input from user and returns as string
modules
-aka libraries-feature sets you can import into a program
argv
- argument variable- variable holds arguments passed to script when running itscript, first, second, third = argv (line 3)- script = name of python script- first, second, third = 3 variables arguments assigned to
open()
- function opens a file- Required argument is filename- Default access_mode is read(r)- Does not return actual content; creates/reads fileObject-
input()
Assumes input is valid python expression, returns evaluated result
read()
- method reads a string from an open file- fileObject.read([count])- Count = # of bytes to read, reads as much as possible if not given
close()
- method flushes unwritten information and closes file object- Not necessary, but important best practice
readline()
Reads one line of text file
truncate()
Empties the file
write(stuff)
Writes stuff to file
len(input)
Return the number of items from a sequence or characters in a string
exists()
Returns TRUE if file in argument exists, FALSE if not
function
1. Names code like variables name strings/numbers2. Takes arguments the way scripts take argv3. Using 1 and 2, allows for mini-commands
def
Defines a functiondef function1(): print "this is function 1"
int()
Convert a string to an integerint(raw_input(> ))
x += y
ADD ANDx = x + y
**
exponent
5 % 3
Modulo;remainder of the division5 % 3 = 2 (3 goes into 5 once, remainder 2)
split()
Method splits a string into separate phrases- Default is to split on whitespacesplit(str, num)str = separator (optional)numb = number of separations (optional)
sorted()
Sorts a list from smallest to highest or a string alphabeticallysorted(str, reverse=True) <- Sorts backwards
pop()
method removes and returns the last object from a list
!=
not equal
floating point numbers
-Scientific notation in computers-Allows very large and small numbers using exponents-Made up of:Significand: 5, 1.5, -2.001Exponent: 2, -2-Put decimal after integers to make floating point1 ~ 1.0
close()
- method flushes unwritten information and closes file object- Not necessary, but important best practice
append()
Adds input to the end of a list
Ordinal Numbers
Start at 1; First, second, third
Cardinal Numbers
Start at 0
Else must have a...
die function that prints out an error message, in case the else doesn't make sense. Shows errors.
Never nest if-statements more than..
..two deep. Try to do one deep (put inside another function).
Treat if statements like...
..paragraphs. Each if, elif, and else grouping is like a set of sentences. Put blank lines before and after.
Boolean tests should be..
...simple. If complex, move calculations to variables earlier in function and use a good name for the variable.
A while-loop is...
an infinite loop. "while True" ~ "While true is true, run this:"
A for-loop is...
...
upper()
converts a string to uppercase
lower()
converts a string to lowercase
print to console
while
controls flow of the program with truth statements. Statements inside the while loop are executed until the expression evaluates false.
for
iterate over items of a collection in order they appear
break
interrupt the (loop) cycle
continue
used to interrupt the current cycle, without jumping out of the whole cycle. New cycle will begin.
if
Used to determine, which statements are going to be executed
elif
stands for else if. if the first test evaluates to False, continues with the next one
else
optional. Used after elif to catch other cases not provided for.
is
tests for object identity
not
negates a boolean value
as
if we want to give a module a different alias
from
for importing a specific variable, class or a function from a module
def
used to create a new user defined function
return
exits the function and returns a value
lambda
creates a new anonymous function
global
access variables defined outside functions
try
specifies exception handlers
except
catches the exception and executes codes
finally
is always executed in the end. Used to clean up resources.
raise
create a user defined exception
del
deletes objects
pass
does nothing
assert
used for debugging purposes
class
-way of producing objects with similar attributes and methods.-used to create new user defined objects-an object is an instance of a class
exec
executes Python code dynamically
yield
is used with generators
\\
backslash (\)
\'
Single Quote (')
\"
Double-quote (")
\a
ASCII Bell-may cause receiving device to emit a bell or warning of some kind
\b
ASCII Backspace (BS)- Erases last character printed
\f
ASCII FormFeed (FF)- ASCII Control character. Forces printer to eject current page and continue printing at top of another.
\n
ASCII LineFeed (LF)- Goes to next line-newline escape
\r
ASCII Carriage Return (CR)- Resets position to beginning of a line of text
\t
ASCII Horizontal Tab (TAB)- 8 horizontal spaces; tab
\v
ASCII Vertical Tab (VT)- 6 vertical lines; 1 inch
%d
signed integer decimal
%i
signed integer decimal
%o
unsigned octal
%u
unsigned decimal
%x
Unsigned hexadecimal (lowercase)
%X
Unsigned Hexadecimal (uppercase)
%e
Floating point exponential format (lowercase)
%E
Floating point exponential format (uppercase)
%f
Floating point decimal format (lowercase)
%F
Floating point decimal format (UPPERCASE)
%g
Same as "e" if exponent is greater than -4 or less than precision
%G
Same as "E" if exponent is greater than -4 or less than precision
%c
Single character-accepts integer or single char string
%r
String -converts any python object using repr()
%s
String-Converts any python object using str()
%
no argument converted, results in "%" in the result
// (operator)
Floor Division. Numbers after the decimal in the quotient are removed- 9//2 = 4
<>
Value of two operands not equal?-Similar to !=
+=
Add AND. Adds right operand to the left and assigns the result to the left. A += B ~ A = A + B
-=
Subtract AND. Subtracts right operand from left and assigns the result to the left.A-=B ~ A = A - b
*=
Multiply AND. Multiplies left operand by right and assigns product to left operandA=B ~ A = AB
%=
Modulus AND. Takes modulus using two operands and assigns the result to left operandA%=B ~ A = A%B
**=
Exponent AND. Performs exponential calculation on operators and assigns value to left operand.A*=B ~ A = A*B
dictionary
A list whose objects can be accessed with a key instead of an index. Key can be any string or number.d = {'key1' : 1, 'key2' : 2}
items()
Returns a list of a dict's tuple pairs (key, value)
get()
Returns a value for the given key. If key is not available, returns default of 'none'.
function argument
passed in for function parameterfunction(argument)
function parameter
Variable name for passed in argmentdef function(parameter):
universal import
Imports all functions and variables from a module- Can cause conflicts with user defined functions and vars- Better to import only necessary functionsfrom module import *
sort()
sorts a list from smallest to greatest
"mutable"
can be changed after created
del keyword
deletes key/value pairs from dict
.remove()
removes items from list
range()
Returns a list of numbers from start up to (but not including) stopstart defaults to 0 and step defaults to 1range(stop)range(start, stop) range(start, stop, step)
Syntax to index 2 nested lists?
list[x][y]
enumerate()
gives an index number to each element in a list
zip()
Combines two or 3 lists to return all values in for loops
tuple
An immutable sequence of Python objects-Immutable; can't be changed-Similar to list, but can't be modified- Uses (), ends in ;tuple1 = ('word', 1, False);
items()
Returns an array of dict key/value pairs
keys()
Returns an array of dict's keys
values()
Returns an array of dict's values
list comprehension
Python rules for creating lists intelligentlys = [x for x in range(1:51) if x%2 == 0][2, 4, 6, 8, 10, 12, 14, 16, etc]
list slicing
Way to access elementslist[start:end:stride]-stride = count by __'s-any term can be omitted, will be set to default- a negative stride progresses through list backwards
filter()
-filters a list for terms that make the function truefilter(function, list)filter(lambda x: x%3 ==0, my_list)-for anonymous (throwaway) functions
5 >> 4
bitwise right shift-shifts turned on bits to the right0b010 >> 1 = 0b001
5 << 1
bitwise left shift-shifts turned on bits to the left0b001 << 1 = 0b010
8 & 5
bitwise ANDTurns on bits turned on in BOTH inputs0b100 & 0b101 = 0b100
9 | 4
Bitwise ORTurns on bits if turned on in either input0b001 | 0b100 = 0b101
12 ^ 42
Bitwise XOR, EXCLUSIVE ORTurns bits on if EITHER but not BOTH bits of inputs are turned on0b1010 ^ 0b1101 = 0b0111
~88
Bitwise NOTflips all bits in a numberfor integers, effectively adds 1 and makes negative
bit mask
variable used to determine if bits are on or off in an input-sort of works like a multiple choice test key-can be used with | to turn bits on if off-use with ^ and 11111111 to flip all bitsdef check_bit4(input): mask = 0b1000 desired = input & mask if desired > 0: return "on" return "off"
method
function of an object
global variable
available everywhere
member variables
variables only available to members of certain class
instance variable
variable only available to one instance of a class
=
assigns values from right side operands to left side operand
sys
module - contains important objects and functions
os
module - OS routines for NT or POSIX
seek()
move to a new position in file, reads bytes
variable
a name for a place to store strings, numbers etc.
from .... import ....
imports specific attributes from a module
module
a file containing Python definitions, statements or scripts, can be user defined or from a built-in library
#
Octothorpeuse for comments on the code, use to disable codeplacing a # at the beginning of a line or in the middle of a line tells python to ignore whatever is written on the line after the #
PEMDAS
Order of Operations:Mode of Operations:Parentheses Exponents Multiplication Division Addition Subtraction
Floating Point Number
any number with a decimal point showing one or more digits behind the decimal point.e. "4.0" or "0.087"
%
Modulusis NOT used as a "percentage" sign in the programming language
%d, %i
Signed integer decimal
%o
Signed octal value
%x
Signed hexidecimal
%e
Floating point exponential format
%c
Single character
''',"""
Free-form strings
"
Every time you put " (double-quotes) around a piece of text you have been making a string. A string is how you make something that your program might give to a human. You print strings, save strings to files, send strings to web servers, and many other things.' (single-quotes) also work for this purpose.
"""
Use to make a string that needs multiple lines for the string text.
variables
can only start with a character (not a number)
%d
digit
Write comments on code ...
No, you write comments only to explain difficult to understand code or why you did something. Why is usually much more important, and then you try to write the code so that it explains how something is being done on its own. However, sometimes you have to write such nasty code to solve a problem that it does need a comment on every line. In this case it's strictly for you to practice translating code to English.
TrueFalse
Python recognizes True and False as keywords representing the concept of true and false. If you put quotes around them then they are turned into strings and won't work.
%f
floatFloating point decimal format
\uxxxx
Character with 16-bit hex value xxxx (Unicode only)
\ooo
Character with octal value ooo
\Uxxxxxxxx
Character with 32-bit hex value xxxxxxxx (Unicode only)
How do I get a number from someone so I can do math?
That's a little advanced, but try x = int(raw_input()) which gets the number as a string from raw_input() then converts it to an integer using int()
,
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
\xhh
Character with hex value hh
from sys import argv
Called an "import."This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts as documentation for other programmers who read your code later.May access features other than "argv"
argv
the "argument variable," a very standard name in programming, that you will find used in many other languages. This variable holds the arguments you pass to your Python script when you run it.You know how you type python ex13.py to run the ex13.py file? Well the ex13.py part of the command is called an "argument." What we'll do now is write a script that also accepts arguments.What's the difference between argv and raw_input()?The difference has to do with where the user is required to give input. If they give your script inputs on the command line, then you use argv. If you want them to input using the keyboard while the script is running, then use raw_input().Line 3: script, first, second, third = argvLine 3 "unpacks" argv so that, rather than holding all the arguments, it gets assigned to four variables you can work with: script, first, second, and third. This may look strange, but "unpack" is probably the best word to describe what it does. It just says, "Take whatever is in argv, unpack it, and assign it to all of these variables on the left in order." (ex13.py)
strings
A string is usually a bit of text you want to display to someone, or "export" out of the program you are writing. Python knows you want something to be a string when you put either " (double-quotes) or ' (single-quotes) around the text. You saw this many times with your use of print when you put the text you want to go inside the string inside " or ' after the print to print the string.Strings may contain the format characters you have discovered so far. You simply put the formatted variables in the string, and then a % (percent) character, followed by the variable. The only catch is that if you want multiple formats in your string to print multiple variables, you need to put them inside ( ) (parenthesis) separated by , (commas). It's as if you were telling me to buy you a list of items from the store and you said, "I want milk, eggs, bread, and soup." Only as a programmer we say, "(milk, eggs, bread, soup)."
import
This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts as documentation for other programmers who read your code later.
.read()
reads the specified fileuse by entering at the end of the variable used to specify the file you have 'opened'.
Variable
A letter or word for a value that can vary or change
Data type
The type of data being used. Could be any of those below
Integer
A whole number
Floating Point
A decimal
String
A text value such as a word or name
Selection
A choice or decision. This is where the code uses "If", "else" or "elif" to decide what to do.
Iteration
A Repeat or Loop. This is where the code uses "while" or "for" loops
List/Array
A list of possible values for a variable. In the fortune teller there was an array of jobs.
Syntax error
An error in the code that means it will not run. Incorrect spelling of keywords, leaving off speech marks or brackets, not using colons for "if" statements.
Logic error
An error that means the code will run, but will not do what is expected.
Function
Some code that has been grouped together so that it can be reused by "calling" the function name. Like a mini-program within a program.
FOR Loop
To repeat a commands a set number of times.
WHILE Loop
To repeat while a condition is true (e.g. while score < 100)
IF Statement
To test if a condition is true (e.g. if age >17)
pwd
print working dictionary
hostname
my computer's network name
mkdir
make directory
cd
change directory
ls
list directory
rmdir
remove directory
pushd
push directory
popd
pop directory
cp
copy a file or directory
mv
move a file or directory
less
page through a file
cat
print the whole file
xargs
execute arguments
find
find files
grep
find things inside files
man
read a manual page
apropos
find what man page is appropriate
env
look at your environment
echo
pint some arguments
export
export/set a new environment variable
exit
exit the shell
sudo
DANGER! become super use root! DANGER!
Boolean Operators
Order: Not, And, Or
Conditional Statement: if
if is a conditional statement that executes some specified code after checking if its expression is True.
Conditional Statement: Else
executes some specified code after finding that the original expression was False (or opposite of the if command)
Conditional Statement: Elif
short for else if...otherwise, if the following expression is true, do this!
Comparators
<><=>===!=
raw_Input
accepts a string, prints it, and then waits for the user to type something and press Enter (or Return).
.isalpha()
is a letter
.lower
makes lowercase
.upper
makes uppercase
concatenation
combine
Functions
1) HEADER def function and add parameters2) add additional """COMMENT here""" that explains the function3)BODY describes procedures the function carries out, is indented
generic import
ex: import math (import module)
use imported function from module
ex: math.sqrt() (module.function)
function import
import a function from a module (from module import function)
universal import
access to all variables and functions in an import without having to type math.function constantly. (from module import *) con: fill your program with a ton of variables and functions and may not link them correctly to the module (your functions and their functions may get confused)
max()
takes largest out of a set of numbers and returns it
min()
takes smallest out of a set of numbers and returns it
abs()
gives absolute value of that number (distance from zero)
type()
returns what "type" of data ex: int, float, str
assignment statement
replaces item in list list_name[index number] = "reassignment"
list.append()
add to a list by typing list_name.append()
slicing lists
letters = ['a', 'b', 'c', 'd', 'e']slice = letters[1:3]print sliceprint letters**when slicing if you wanted numbers 1 and 2 you would slice [0:2] so the code would include both the index 0 and 1
strings
list of characters
[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last items
.index(item)
Find the index of an item
.insert(index, item)
insert a certain item into a list at a certain index
for loop
applies function to every item in listfor x in a: print xcan sort functionsfor number in my_list print number #prints out every number on its own line
key
similar to index but uses a string or number
dictionary
similar to a list but you access values by looking at a key rather than an indexuseful for information using strings and values i.e. phonebook, email databases (passwords, and usernames)
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
dictionary **not curly braces
access dictionary values
list[item]
mutable
can be changed after created
how to loop through dictionaries keys
d = {"foo" : "bar"}for key in d: print d[key]
algorithm
A set of specific steps for solving a category of problems
comment
in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program
high-level language
A programming language like Python that is designed to be easy for humans to read and write.
A function used in a program or script that causes the Python interpreter to display a value on its output device.
runtime error
An error that does not occur until the program has started to execute but that prevents the program from continuing.
semantic error
An error in a program that makes it do something other than what the programmer intended.
semantic
the meaning of a program
syntax
The structure of a program
syntax error
An error in a program that makes it impossible to parse â and therefore impossible to interpret.
str
converts to a string
argument
a value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
integer division
An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.
element
One of the values in a list (or other sequence). The bracket operator selects elements of a list.
module
A file containing definitions and statementsintended to be imported by other programs.
What type of loop structure repeats the code a specific number of times
Count-controlled loop
What type of loop structure repeats the code based on the value of the Boolean expression
Condition-controlled loop
What is the format for the while clause in Python
while condition : statement
The variable used to keep the running total
Accumulator
_____ is the process of inspecting data that has been input to a program to make sure it is valid before it is used in a computation.
Input validation
What is the structure that causes a statement or a set of statements to execute repeatedly?
Repetition
When will the following loop terminate?while keep_on_going != 999 :
When keep_on_going refers to a value not equal to 999
Which of the following represents an example to calculate the sum of the numbers (accumulator)?
total += number
Programs are commonly referred to as
software
What type of volatile memory is usually used only for temporary storage while running a program?
RAM
The Python _______________ is a program that can read Python programming statements and execute them.
interpreter
Boolean variable can reference one of two values: _____.
true or false
In a decision structure, the action is _______________ executed because it is performed only when a certain condition is true.
conditionally
/
Slash: used for division
%
Percent: used for modulus. The modulus operation finds the remainder after division of one number after another.Example: 75 % 4 = 3, because 4 * 18 is 72, with 3 remaining
*
Asterisk: used for miltiplication
<=
Less than or equal to
>=
Greater than or equal
PEDMAS
Order of operations: parentheses, exponents, multiplication, division, addition, subtraction
Formatter
Placeholders that "punch out a hole in the code% is the character for this
raw_input
Pauses the script at the point it shows up, gets the answer from the keyboard, then continues the script.It is one of python's built-in functionsLooks something like: var = raw_input("Enter_Something")Where "Enter_Something" is what the prompt is, asking you to enter some text, and var is where the text is stored Remember the %r in the prompt
Modules
Python's built-in features are called modules.Also called "libraries" by some programmers.Example speech: "you want to use the sys module."
script
Will input the name of the script into your code when called
prompt
A formatter text that is used to give the user the ability to type in a question
close
A method/function/command to close the file
read
A method/function/command to read the file
readline
A method/function/command to read just one line of a text file
truncate
A method/function/command to empty the file. Be careful if you care about the file
open(argument, 'w')
Open a file with an extra parameter. Python has several open parameters that open a file different ways
os.path
Operating system path module: allows many functions to occur on a specified path.Ex: os.path exists will return a true or false if a file does or doesn't exist
variable
A variable is something that holds a value that may change. In simplest terms, a variable is just a box that you can put stuff in. You can use variables such as numbers.Ex: lucky = 7print(lucky)7
string
A string is a list of characters inside of quotes.Strings can be made of single, double or triple quotes.