Computer Science: Python
for loops
"for x in list_name" ... applies something to every item in a list
[:2]
# Grabs the first two items
my_list[3:]
# Grabs the fourth through last items
modulus operator
%, works on integers (and integer expressions) and gives the remainder when the first number is divided by the second
modulo
%. Returns the remainder from a division.
Order of Precedence
(**), (*,/,%), (+,-)
after we've added options (in parser)
(options, args) = parser.parse_args()
Which mathematical operator is used to raise five to the second power in Python?
**
exponent
**
exponents in python
**
argv
- argument variable - variable holds arguments passed to script when running it script, 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 -
close()
- method flushes unwritten information and closes file object - Not necessary, but important best practice
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
floating point numbers
-Scientific notation in computers -Allows very large and small numbers using exponents -Made up of: *Significand*: 5, 1.5, -2.001 *Exponent*: 2, -2 -Put decimal after integers to make floating point 1 ~ 1.0
modules
-aka libraries -feature sets you can import into a program
filter()
-filters a list for terms that make the function true filter(function, list) filter(lambda x: x%3 ==0, my_list) -for anonymous (throwaway) functions
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
Boolean tests should be..
...simple. If complex, move calculations to variables earlier in function and use a good name for the variable.
Treat if statements like...
..paragraphs. Each if, elif, and else grouping is like a set of sentences. Put blank lines before and after.
Never nest if-statements more than..
..two deep. Try to do one deep (put inside another function).
What are the values that the variable num contains through the iterations of the following for loop? for num in range(4)
0, 1, 2, 3
Functions
1) HEADER def function and add parameters 2) add additional """COMMENT here""" that explains the function 3)BODY describes procedures the function carries out, is indented
function
1. Names code like variables name strings/numbers 2. Takes arguments the way scripts take argv 3. Using 1 and 2, allows for mini-commands
github steps
1. git status 2. git add (adds to staging) 3. git commit -m "What you've done" 4. git push -u origin master
Order of Conditionals
1. not 2. and 3. or
What are the values that the variable num contains through the iterations of the following for loop? for num in range(2, 9, 2)
2, 4, 6, 8
If value1 is 2.0 and value2 is 12, what is the output of the following command? print(value1 * value2)
24.0
What is the largest value that can be stored in one byte?
255
The program development cycle is made up of _____ steps that are repeated until no errors can be found in the program.
3
After the execution of the following statement, the variable price will reference the value _____. price = int(68.549)
68
When applying the .3f formatting specifier to the following number, 76.15854, the result is _______________.
76.159
How many characters to a line?
80 characters
Comparators
< > <= >= == !=
What is not an example of an augmented assignment operator
<=
What's the difference between = and == in Python?
= is the assignment operator. == is the equality operator.
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
Iteration
A Repeat or Loop. This is where the code uses "while" or "for" loops
Selection
A choice or decision. This is where the code uses "If", "else" or "elif" to decide what to do.
dictionary
A collection of key/value pairs that maps from keys to values.
immutable type
A compound data type whose elements can NOT be assigned new values.
mutable type
A compound data type whose elements can be assigned new values.
slice
A copy of part of a sequence specified by a series of indices.
compound data type
A data type that is itself made up of elements that are themselves values.
sequence
A data type that is made up of elements organized linearly, with each element accessed by an integer index.
Floating Point
A decimal
module
A file containing definitions and statements intended to be imported by other programs.
prompt
A formatter text that is used to give the user the ability to type in a question
boolean function
A function that returns a Boolean value. The only possible values of the bool type are False and True.
fruitful function
A function that returns a value when it is called.
A function used in a program or script that causes the Python interpreter to display a value on its output device.
block
A group of consecutive statements with the same indentation.
Variable
A letter or word for a value that can vary or change
List/Array
A list of possible values for a variable. In the fortune teller there was an array of jobs.
What's a dictionary?
A list of tuples in curly brackets: {"x:y"}; x is a key, y is a value; dictionaries are unordered.
nested list
A list that is itself contained within a list.
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}
nested loop
A loop inside the body of another loop.
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
close
A method/function/command to close the file
truncate
A method/function/command to empty the file. Be careful if you care about the file
readline
A method/function/command to read just one line of a text file
read
A method/function/command to read the file
parameter
A name used inside a function to refer to the value which was passed to it as an argument.
file
A named entity, usually stored on a hard drive, floppy disk, or CD-ROM, that contains a stream of characters.
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
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.)
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
algorithm
A set of specific steps for solving a category of problems
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.
operator
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
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.
string
A string is a list of characters inside of quotes. Strings can be made of single, double or triple quotes.
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)."
String
A text value such as a word or name
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.
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 = 7 print(lucky) 7
Integer
A whole number
x += y
ADD AND x = x + y
The _____ coding scheme contains a set of 128 numeric codes that are used to represent characters in the computer memory.
ASCII
\b
ASCII Backspace (BS) - Erases last character printed
\a
ASCII Bell -may cause receiving device to emit a bell or warning of some kind
\r
ASCII Carriage Return (CR) - Resets position to beginning of a line of text
\f
ASCII FormFeed (FF) - ASCII Control character. Forces printer to eject current page and continue printing at top of another.
\t
ASCII Horizontal Tab (TAB) - 8 horizontal spaces; tab
\n
ASCII LineFeed (LF) - Goes to next line -newline escape
\v
ASCII Vertical Tab (VT) - 6 vertical lines; 1 inch
The variable used to keep the running total
Accumulator
+=
Add AND. Adds right operand to the left and assigns the result to the left. A += B ~ A = A + B
append()
Adds input to the end of a list
semantic error
An error in a program that makes it do something other than what the programmer intended.
syntax error
An error in a program that makes it impossible to parse — and therefore impossible to interpret.
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.
runtime error
An error that does not occur until the program has started to execute but that prevents the program from continuing.
Logic error
An error that means the code will run, but will not do what is expected.
type conversion
An explicit function call that takes a value of one type and computes a corresponding value of another type.
boolean expression
An expression that is either true or false.
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);
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.
Which computer language uses short words known as mnemonics for writing programs?
Assembly
input()
Assumes input is valid python expression, returns evaluated result
*
Asterisk: used for miltiplication
~88
Bitwise NOT flips all bits in a number for integers, effectively adds 1 and makes negative
9 | 4
Bitwise OR Turns on bits if turned on in either input 0b001 | 0b100 = 0b101
12 ^ 42
Bitwise XOR, EXCLUSIVE OR Turns bits on if EITHER but not BOTH bits of inputs are turned on 0b1010 ^ 0b1101 = 0b0111
increment
Both as a noun and as a verb, increment means to increase by 1.
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"
global variable
Can be seen through a program module, even inside of functions.
\uxxxx
Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx
Character with 32-bit hex value xxxxxxxx (Unicode only)
\xhh
Character with hex value hh
\ooo
Character with octal value ooo
zip()
Combines two or 3 lists to return all values in for loops
When the + operator is used with two strings, it performs string _______________.
Concatenation
A(n) ??-controlled loop causes a statement or set of statements to repeat as long as a condition is true.
Condition
What type of loop structure repeats the code based on the value of the Boolean expression
Condition-controlled loop
int()
Convert a string to an integer int(raw_input(> ))
%s
Converts String (converts any Python object using str())
%d
Converts a signed integer decimal
What type of loop structure repeats the code a specific number of times
Count-controlled loop
sudo
DANGER! become super use root! DANGER!
def
Defines a function def function1(): print "this is function 1"
Which of the following is not a microprocessor manufacturing company?
Dell
\"
Double-quote (")
Which of the following is considered to be the world's first programmable electronic computer
ENIAC
truncate()
Empties the file
"
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.
**=
Exponent AND. Performs exponential calculation on operators and assigns value to left operand. A**=B ~ A = A**B
True/False: A computer is a single device that performs different types of tasks for its users.
False
True/False: According to the behavior of integer division, when an integer is divided by an integer, the result will be a float.
False
True/False: All programs are normally stored in ROM and loaded into RAM as needed for processing.
False
True/False: Both of the following for clauses would generate the same number of loop iterations: for num in range(4): for num in range(1,5):
False
True/False: In Python, an infinite loop usually occurs when the computer accesses the wrong memory address.
False
True/False: Python allows you to compare strings, but it is not case sensitive.
False
True/False: Python formats all floating-point numbers to two decimal places when outputting using the print statement.
False
True/False: Short-circuit evaluation is performed with the not operator.
False
True/False: The CPU is able to quickly access data stored at any random location in ROM.
False
True/False: The Python language is not sensitive to block structuring of code.
False
True/False: The Python language uses a compiler, which is a program that both translates and executes the instructions in a high level language.
False
True/False: The not operator is a unitary operator and it must be a compound expression.
False
.index(item)
Find the index of an item
%F
Floating point decimal format (UPPERCASE)
%f
Floating point decimal format (lowercase)
%e
Floating point exponential format
%e
Floating point exponential format (lowercase)
%E
Floating point exponential format (uppercase)
// (operator)
Floor Division. Numbers after the decimal in the quotient are removed - 9//2 = 4
In Python, you would use the ?? statement to write a count-controlled loop.
For
''',"""
Free-form strings
The acronym ?? refers to the fact that the computer cannot tell the difference between good data and bad data.
GIGO
>=
Greater than or equal
The output of the following print statement is: print 'I\'m ready to begin'
I'm ready to begin
The _______________ statement is used to create a decision structure.
If
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.
universal import
Imports all functions and variables from a module - Can cause conflicts with user defined functions and vars - Better to import only necessary functions from module import *
A(n) ?? validation loop is sometimes called an error trap or an error handler.
Input
_____ 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
my_list.insert(4, "cat")
Inserts the string "cat" at the 4th position in a list
%d
Integer format character
{}.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").
What is sys.argv?
It allows you to input parameters from the command line.
<=
Less than or equal to
The following is an example of an instruction written in which computer language? 10110000
Machine language
Where does a computer store a program and the data that the program is working with while the program is running?
Main memory
split()
Method splits a string into separate phrases - Default is to split on whitespace split(str, num) str = separator (optional) numb = number of separations (optional)
5 % 3
Modulo; remainder of the division 5 % 3 = 2 (3 goes into 5 once, remainder 2)
%
Modulus is NOT used as a "percentage" sign in the programming language
%=
Modulus AND. Takes modulus using two operands and assigns the result to left operand A%=B ~ A = A%B
aliases
Multiple variables that contain references to the same object.
*=
Multiply AND. Multiplies left operand by right and assigns product to left operand A*=B ~ A = A*B
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.
#
Octothorpe use for comments on the code, use to disable code placing 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 #
element
One of the values in a list (or other sequence). The bracket operator selects elements of a list.
conditional statement
One program structure within another, such as a conditional statement inside a branch of another conditional statement
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
When using the _____ operator, one or both subexpressions must be true for the compound expression to be true.
Or
PEMDAS
Order of Operations: Mode of Operations: Parentheses Exponents Multiplication Division Addition Subtraction
PEDMAS
Order of operations: parentheses, exponents, multiplication, division, addition, subtraction
Boolean Operators
Order: Not, And, Or
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 functions Looks 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
%
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
Formatter
Placeholders that "punch out a hole in the code % is the character for this
The while loop is known as a(n) ?? loop because it tests conditions before performing an iteration.
Pretest
The first input operation is called the _____, and its purpose is to get the first input value that will be tested by the validation loop.
Priming read
True False
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.
list comprehension
Python rules for creating lists intelligently s = [x for x in range(1:51) if x%2 == 0] [2, 4, 6, 8, 10, 12, 14, 16, etc]
Modules
Python's built-in features are called modules. Also called "libraries" by some programmers. Example speech: "you want to use the sys module."
What symbol is used to mark the beginning and end of a string?
Quotation
Main memory is commonly known as _______________.
RAM
What type of volatile memory is usually used only for temporary storage while running a program?
RAM
exception
Raised by the runtime system if something goes wrong while the program is running.
The ?? function is a built-in function that generates a list of integer values.
Range
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.
raw_input('prompt:')
Reads a line of input from user and returns as string
readline()
Reads one line of text file
iteration
Repeated execution of a set of programming statements.
A(n) ?? structure causes a statement or set of statements to execute repeatedly.
Repetition
What is the structure that causes a statement or a set of statements to execute repeatedly?
Repetition
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
items()
Returns a list of a dict's tuple pairs (key, value)
range()
Returns a list of numbers from start up to (but not including) stop start defaults to 0 and step defaults to 1 range(stop) range(start, stop) range(start, stop, step)
get()
Returns a value for the given key. If key is not available, returns default of 'none'.
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
A(n) ?? total is a sum of numbers that accumulates with each iteration of a loop.
Running
%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
A(n) ?? is a special value that marks the end of a sequence of items.
Sentinel
%x
Signed hexidecimal
%d, %i
Signed integer decimal
%o
Signed octal value
\'
Single Quote (')
%c
Single character
%c
Single character -accepts integer or single char string
/
Slash: used for division
pixel
Smallest addressable element of a picture.
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.
sorted()
Sorts a list from smallest to highest or a string alphabetically sorted(str, reverse=True) <- Sorts backwards
Cardinal Numbers
Start at 0
Ordinal Numbers
Start at 1; First, second, third
%s
String -Converts any python object using str()
%r
String -converts any python object using repr()
%r
String (converts any Python object using repr())
""" ............."""
String for multiple lines of text; can be multi-line comment
%r
String format character; use for debugging
%s
String format character; use for user formatting
-=
Subtract AND. Subtracts right operand from left and assigns the result to the left. A-=B ~ A = A - b
In Python, the variable in the for clause is referred to as the _____ because it is the target of an assignment at the beginning of each loop iteration.
Target Variable
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()
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.
len[2] = 3
The 2nd term of the list is now equal to 3
flow of execution
The order in which statements are executed during a program run.
What is the output of the following print statement? print('The path is D:\\sample\\test.')
The path is D:\sample\test
recursion
The process of calling the currently executing function.
syntax
The structure of a program
Data type
The type of data being used. Could be any of those below
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.
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.
trace
To follow the flow of execution of a program by hand, recording the change of state of the variables and any output produced.
FOR Loop
To repeat a commands a set number of times.
iteration
To repeat a section of code.
traverse
To repeat an operation on all members of a set from the start to the end.
WHILE Loop
To repeat while a condition is true (e.g. while score < 100)
evaluate
To simplify an expression by performing the operations in order to yield a single value.
decrement
To subtract one from a variable.
IF Statement
To test if a condition is true (e.g. if age >17)
True/False: A better way to repeatedly perform an operation is to write the statements for the task once, and then place the statements in a loop that will repeat the statements as many times as necessary.
True
True/False: An action in a single alternative decision structure is performed only when the condition is true.
True
True/False: Computer programs typically perform three steps: Input is received, some process is performed on the input, and output is produced.
True
True/False: Decision structures are also known as selection structures.
True
True/False: Expressions that are tested by the if statement are called Boolean expressions.
True
True/False: In Python, print statements written on separate lines do not necessarily output on separate lines.
True
True/False: In a nested loop, the inner loop goes through all of its iterations for every single iteration of an outer loop.
True
True/False: In flowcharting, the decision structure and the repetition structure both use the diamond symbol to represent the condition that is tested.
True
True/False: Nested decision structures are one way to test more than one condition.
True
True/False: Python allows programmers to break a statement into multiple lines.
True
True/False: RAM is a volatile memory used for temporary storage while a program is running.
True
True/False: The CPU understands instructions written in a binary machine language.
True
True/False: The \t escape character causes the output to skip over to the next horizontal tab.
True
True/False: The first line in the while loop is referred to as the condition clause.
True
True/False: The if statement causes one or more statements to execute only when a Boolean expression is true.
True
True/False: The instruction set for a microprocessor is unique and is typically understood only by the microprocessors of the same brand.
True
True/False: The integrity of a program's output is only as good as the integrity of its input. For this reason the program should discard input that is invalid and prompt the user to enter correct data.
True
True/False: The main reason for using secondary storage is to hold data for long periods of time, even when the power supply to the computer is turned off.
True
True/False: To get the total number of iterations of a nested loop, multiply the number of iterations of all the loops.
True
variables can be reassigned?
True
%X
Unsigned Hexadecimal (uppercase)
%x
Unsigned hexadecimal (lowercase)
"""
Use to make a string that needs multiple lines for the string text.
if
Used to determine, which statements are going to be executed
<>
Value of two operands not equal? -Similar to !=
function parameter
Variable name for passed in argment def function(parameter):
list slicing
Way to access elements list[start:end:stride] -stride = count by __'s -any term can be omitted, will be set to default - a negative stride progresses through list backwards
,
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
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 evaluate any further to determine the final outcome.
When will the following loop terminate? while keep_on_going != 999 :
When keep_on_going refers to a value not equal to 999
script
Will input the name of the script into your code when called
write(stuff)
Writes stuff to file
The line continuation character is a _____.
\
boolean
a data type that is like a light switch. it can only have two values: true, false
module
a file containing Python definitions, statements or scripts, can be user defined or from a built-in library
variable
a name for a place to store strings, numbers etc.
argument
a value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
raw_Input
accepts a string, prints it, and then waits for the user to type something and press Enter (or Return).
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)
global
access variables defined outside functions
list.append()
add to a list by typing list_name.append()
A while-loop is...
an infinite loop. "while True" ~ "While true is true, run this:"
Floating Point Number
any number with a decimal point showing one or more digits behind the decimal point. e. "4.0" or "0.087"
list_name.append("")
appends thing to lists
for loop
applies function to every item in list for x in a: print x can sort functions for number in my_list print number #prints out every number on its own line
=
assigns values from right side operands to left side operand
global variable
available everywhere
\\
backslash (\)
token
basic elements of a language(letters, numbers, symbols)
The smallest storage location in a computer's memory
bit
8 & 5
bitwise AND Turns on bits turned on in BOTH inputs 0b100 & 0b101 = 0b100
5 << 1
bitwise left shift -shifts turned on bits to the left 0b001 << 1 = 0b010
5 >> 4
bitwise right shift -shifts turned on bits to the right 0b010 >> 1 = 0b001
"mutable"
can be changed after created
mutable
can be changed after created
string
can contain letters, numbers, and symbols
variables
can only start with a character (not a number)
except
catches the exception and executes codes
cd
change directory
concatenation
combine
_______________ are notes of explanation that document lines or sections of a program.
comments
A(n) _______________ expression is made up of two or more Boolean expressions.
compound
Multiple Boolean expressions can be combined by using a logical operator to create _____ expressions.
compound
In a decision structure, the action is _______________ executed because it is performed only when a certain condition is true.
conditionally
A(n) _____ structure is a logical design that controls the order in which a set of statements execute.
control
while
controls flow of the program with truth statements. Statements inside the while loop are executed until the expression evaluates false.
lower()
converts a string to lowercase
upper()
converts a string to uppercase
str
converts to a string
cp
copy a file or directory
The _______________ is the part of a computer that actually runs programs and is the most important component in a computer.
cpu
raise
create a user defined exception
lambda
creates a new anonymous function
how to loop through dictionaries keys
d = {"foo" : "bar"} for key in d: print d[key]
Python uses _______________ to categorize values in memory.
data types
%r is used for...
debugging and display
keyword
define the language's syntax rules and structure, and they cannot be used as variable names
del keyword
deletes key/value pairs from dict
del
deletes objects
In flowcharting, the _______________ symbol is used to represent a Boolean expression.
diamond
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
dictionary **not curly braces
Else must have a...
die function that prints out an error message, in case the else doesn't make sense. Shows errors.
%d
digit
%s is used for
display
pass
does nothing
The decision structure that has two possible paths of execution is known as _____.
double alternative
Every if statement must have a(n)...
else
In a print statement, you can set the _____ argument to a space or empty string to stop the output from advancing to a new line.
end
A(n) _______________ character is a special character that is preceded with a backslash, appearing inside a string literal.
escape
\
escape; tells python to ignore following character, or puts difficult characters into strings when used with specific *escape sequences*
generic import
ex: import math (import module)
use imported function from module
ex: math.sqrt() (module.function)
xargs
execute arguments
exec
executes Python code dynamically
Conditional Statement: Else
executes some specified code after finding that the original expression was False (or opposite of the if command)
exit
exit the shell
return
exits the function and returns a value
**
exponent
export
export/set a new environment variable
The process known as the _____ cycle is used by the CPU to execute instructions in a program.
fetch-decode-execute
find
find files
grep
find things inside files
apropos
find what man page is appropriate
len(my_list)
finds the length of a list
Boolean variables are commonly used as _______________ to indicate whether a specific condition exists.
flags
After the execution of the following statement, the variable sold will reference the numeric literal value as a(n) _____ data type: sold = 256.752
float
%f
float Floating point decimal format
from
for importing a specific variable, class or a function from a module
The _______________ specifier is a special set of characters that specify how a value should be formatted.
formatting
method
function of an object
round()
function rounds floating point numbers round(1.773) = 2
abs()
gives absolute value of that number (distance from zero)
enumerate()
gives an index number to each element in a list
not
gives the opposite of the statement; i.e. "Not True is False"
my_list[:]
gives you the entire list
my_list[-1]
gives you the last term in the list
my_list[1:3]
gives you the list starting at the 1st position and ending at the 2nd position
my_list[0:]
gives you the whole list, starting at the 0 position
The term _______________ refers to all of the physical devices that a computer is made of.
hardware
data types
i.e. numbers and booleans
Python provides a special version of a decision structure known as the _______________ statement, which makes the logic of the nested decision structure simpler to write
if elif else
Conditional Statement: if
if is a conditional statement that executes some specified code after checking if its expression is True.
as
if we want to give a module a different alias
Control flow statements
if, for, while
A(n) _______________ statement will execute one block of statements if its condition is true, or another block if its condition is false.
if/else
function import
import a function from a module (from module import function)
optparse first command
import optparse parser = optparse.OptionParser
from .... import ....
imports specific attributes from a module
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
(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
The _____ function reads a piece of data that has been entered at the keyboard and returns that piece of data, as a string, back to the program.
input
The _____ built-in function is used to read a number that has been typed on the keyboard.
input()
.insert(index, item)
insert a certain item into a list at a certain index
statement
instruction that the Python interpreter can execute
integer vs. float
integer is a number w/out a decimal; float is a number with a decimal
The Python _______________ is a program that can read Python programming statements and execute them.
interpreter
break
interrupt the (loop) cycle
.isalpha()
is a letter
finally
is always executed in the end. Used to clean up resources.
yield
is used with generators
for
iterate over items of a collection in order they appear
<, <=, >, >=
less than, less than or equal to, greater than, greater than or equal to
string methods
let you perform specific tasks on strings
slicing lists
letters = ['a', 'b', 'c', 'd', 'e'] slice = letters[1:3] print slice print 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
\n
line character; creates new line in string
In Python, a comma-separated sequence of data items that are enclosed in a set of brackets is called a _____.
list
ls
list directory
strings
list of characters
access dictionary values
list[item]
Syntax to index 2 nested lists?
list[x][y]
What type of error produces incorrect results but does not prevent the program from running?
logic
env
look at your environment
A disk drive stores data by _______________ encoding it onto a circular disk.
magnetically
The disk drive is a secondary storage device that stores data by _____ encoding it onto a spinning circular disk.
magnetically
mkdir
make directory
.lower
makes lowercase
.upper
makes uppercase
basic regex syntax
match = re.search(pattern, text)
\b
matches a word boundar
x?
matches an option x character (in other words, it matches an x wero or one times)
x{n,m}
matches an x character at least n times, but not more than m times
\D
matches any non-numeric character
\d
matches any numeric digit
(a|b|c|)
matches either a or b or c
^
matches the beginning of a string
$
matches the end of a string
x+
matches x one or more times
x*
matches x zero or more times
indentations in python
mean that there is a code block
!=
means doesn't equal
==
means equal to
or
means one of the conditions must be true
and
means that both conditions must be true
robot
mechanism or an artificial entity that can be guided by automatic controls.
pop()
method removes and returns the last object from a list
_______________ are small central processing unit chips.
micro processors
os
module - OS routines for NT or POSIX
sys
module - contains important objects and functions
The % symbol is the remainder operator and it is also known as the _______________ operator.
modulus
mv
move a file or directory
seek()
move to a new position in file, reads bytes
\n
moves whatever's after it to a new ling
hostname
my computer's network name
not
negates a boolean value
%
no argument converted, results in "%" in the result
The logical _______________ operator reverses the truth of a Boolean expression.
not
!=
not equal
proprioception
on a robot, internal sensing mechanisms. On a human, a sense of the relative positions of different parts of ones own body.
else
optional. Used after elif to catch other cases not provided for.
Which logical operators perform short-circuit evaluation?
or, and
less
page through a file
adding parser options
parser.add_option('-n, '--new')
function argument
passed in for function parameter function(argument)
echo
pint some arguments
popd
pop directory
cat
print the whole file
print to console
pwd
print working dictionary
A(n) _______________ is a set of instructions that a computer follows to perform a task.
program
What is the informal language that programmers use to create models of programs that have no syntax rules and are not meant to be compiled or executed?
pseudocode
pushd
push directory
man
read a manual page
.read()
reads the specified file use by entering at the end of the variable used to specify the file you have 'opened'.
A(n) _______________ operator determines whether a specific relationship exists between two values.
relational
rmdir
remove directory
.remove()
removes items from list
assignment statement
replaces item in list list_name[index number] = "reassignment"
type()
returns what "type" of data ex: int, float, str
In _______________ mode, the interpreter reads the contents of a file that contains Python statements and executes each statement.
script
_______________ 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
whitespace
separates statements
Conditional Statement: Elif
short for else if...otherwise, if the following expression is true, do this!
%d
signed integer decimal
%i
signed integer decimal
dictionary
similar to a list but you access values by looking at a key rather than an index useful for information using strings and values i.e. phonebook, email databases (passwords, and usernames)
key
similar to index but uses a string or number
A(n) _______________ decision structure provides only one alternative path of execution.
single alternative
Programs are commonly referred to as
software
A _____ has no moving parts, and operates faster than a traditional disk drive.
solid state drive
my_list.sort()
sorts a list from lowest to highest, or alphabetical
sort()
sorts a list from smallest to greatest
operators
special tokens that represent computations like addition, multiplication and division
try
specifies exception handlers
elif
stands for else if. if the first test evaluates to False, continues with the next one
variable
stores a piece of data and gives it a specific name
\t
tab character
max()
takes largest out of a set of numbers and returns it
min()
takes smallest out of a set of numbers and returns it
\
tells Python not to end the string
is
tests for object identity
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 = argv Line 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)
semantic
the meaning of a program
index
the number that each character in a string is assigned
What does % when printing string
they allow the variables outside the string to enter into the string
"""
to display things as they're written in the .txt file
Which of the following represents an example to calculate the sum of the numbers (accumulator)?
total += number
Boolean variable can reference one of two values: _____.
true or false
What is the encoding technique called that is used to store negative numbers in the computer's memory?
two's complement
%u
unsigned decimal
%o
unsigned octal
assert
used for debugging purposes
def
used to create a new user defined function
continue
used to interrupt the current cycle, without jumping out of the whole cycle. New cycle will begin.
A(n) _______________ is a name that represents a value stored in the computer's memory.
variable
instance variable
variable only available to one instance of a class
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 bits def check_bit4(input): mask = 0b1000 desired = input & mask if desired > 0: return "on" return "off"
member variables
variables only available to members of certain class
What is the format for the while clause in Python
while condition : statement