Python

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

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

(**), (*,/,%), (+,-)

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

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

Order of Conditionals

1. not 2. and 3. or

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'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.

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.

print

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.

truncate

A method/function/command to empty the file. Be careful if you care about the file

variable

A name that represents a value stored in the computer's memory.

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.

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 statements.

string

A string is a list of characters inside of quotes. Strings can be made of single, double or triple quotes.

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.

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);

// (operator)

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.

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 multiplication

~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

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"

\"

Double-quote (")

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)

In Python, you would use the ?? statement to write a count-controlled loop.

For

''',"""

Free-form strings

>=

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

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

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

*=

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.

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

The while loop is known as a(n) ?? loop because it tests conditions before performing an iteration.

Pretest

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]

What symbol is used to mark the beginning and end of a string?

Quotation

Main memory is commonly known as _______________.

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

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

%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

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

%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

Accumulator

The variable used to keep the running total

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.

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.

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: 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

concatenation

Using the + operator to combine two strings

<>

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 (\)

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

variables

can only start with a character (not a number)

except

catches the exception and executes codes

cd

change directory

_______________ 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

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

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)

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

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

^

matches the beginning of a string

$

matches the end of a string

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

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 line

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

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

function argument

passed in for function parameter function(argument)

echo

pint some arguments

popd

pop directory

cat

print the whole file

print

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 _____ 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

\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

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

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

%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


Kaugnay na mga set ng pag-aaral