Chapter 1, 2, 3 Flashcards

(88 cards)

1
Q

A set of instructions that a computer follows to perform a task

A

Program

Alternate Names:
- Software (e.g. Microsoft Word and PPT)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does a computer’s hardware include?

A
  • CPU (microprocessors)
  • RAM (main memory)
  • Secondary Storage Devices (e.g. traditional disk drives, solid-state drives) => internal to the computer
  • External Storage Devices
  • Input devices (e.g. keyboard, mouse, camera, scanner)
  • Output devices (printer, displays, monitors, disk drives)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the CPU’s function

A

to RUN or EXECUTE programs

  • most important component in a computer
  • need to be told what to do via programs written in machine language
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the RAM’s function?

What is the physical device called?
Is it permanent storage?

A

Random-Access Memory

  • computer’s “work area”
  • volatile type of memory for TEMPORARY STORAGE WHILE the program is running
  • contents of RAM are erased when your computer is turned off
  • Stored as memory chips
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What types of Software exist?

Definitions of each?

A
  1. SYSTEM Software: Control and manage the BASIC OPERATIONS of a computer
  • Operating System (controls INTERNAL OPERATIONS of computer’s hardware, manages all connected devices, and allows other programs to run on the computer)
  • Utility Programs (specialized tasks to enhance computer’s operations or safeguard data, like virus scanners, file compression programs)
  • Software Development Tools (assemblers, compilers, and interpreters) for programmers to create, modify and test software
  1. Application Software: programs that make the computer USEFUL for everyday tasks
    e. g. Chrome, Word, PPT, excel, games
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do computers store data?

A

Data is stored in a sequence of 0s and 1s, called Machine Language (binary numbers)

Stored in locations called BYTES (8 bits)

  • bits = on and off switches (binary digit)
  • characters (letters, punctuation marks) are CONVERTED to decimal value, then CONVERTED to binary and stored
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you convert a decimal number to Binary?

e.g. 79

A

Binary structure:

  • base 2
  • Right to Left, starting with 2^0 (or 1)
  • 1(2^x) or 0(2^x)
  • positions of 0s and 1s are important!
  • SUM of positions should equal decimal value

How to convert decimal to Binary:
- start with the LARGEST power, then go all the way back to 2^0

e.g.
79 = 1(2^6) + 0(2^5) + 0(2^4) + 1(2^3) + 1(2^2) + 1(2^1) + 1*(2^0) = 1001111

PYTHON CHECK: bin(79)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to interpret Numeric Types:

Binary (2)

Octal (8)

Hexadecimal (16)

  • digit ranges
  • Python form
A

In Python:
0b____ (0 or 1)
0o____ (0 to 7)
0x____ (0 to 9, A, B, C, D, E, F)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How many numeric codes are in the ASCII?

A

128 numeric codes for lower case and upper case letters, punctuation, spaces etc.
- starts with 0, ends with 127

  1. convert character to decimal value using the ASCII chart
  2. Convert decimal value into binary
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

If binary can only represent positive integer numbers, how do computers store negative numbers and fractional numbers?

A

Use encoding schemes along with binary numbering system

NEGATIVE numbers are encoded using TWO’S COMPLEMENT

REAL numbers are encoded using FLOATING-POINT NOTATION

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does “digital” refer to?

A

Anything that uses BINARY NUMBERS
(digital devices, digital data)

> need to be converted to binary first

e. g. Images = Pixels => converted to numeric code => stored in memory as a binary number
e. g. song samples = converted to binary number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Define instruction set

A

the entire set of instructions for each operation the CPU is capable of performing

*each brand of microprocessor has its own unique machine language instruction set

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How does the secondary storage device, RAM and CPU work together to run programs?

What is the cycle the CPU engages in to execute programs called?

A
  1. Program is stored in the secondary storage device (disk drive)
  2. When the program is run, it is COPIED from the secondary storage to main memory
  3. Fetch-Decode-Execute cycle
    - fetch the next instruction from the main memory to the CPU
    - decode instructions
    - execute and perform the operation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the name of the language that uses SHORT WORDS known as MNEMONICS?

A

Assembly Language

  • type of LOW-level language (very close to ML)
  • e.g. “add”, “mul”, “mov” have special meaning
  • each brand of microprocessor has its own assembly language as well

(like you are assembling parts together using basic words)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Can the CPU directly understand Assembly Language?

A

No

- need an ASSEMBLER to translate an assembly language to a machine language program

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are high-level languages?

What are the pre-defined words used to write a program called?

A
  • allow humans to create powerful, complex programs without writing low-level instructions
    e. g. Python, C++, C#, Java etc.
  • pre-defined words called KEY WORDS or RESERVED WORDS
    (cannot be used for other purposes like variable, function names)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Can the CPU directly understand high-level languages?

What is the translation device called?

A

No
- need either a COMPILER or INTERPRETER to translate into ML

Compiler - 1. compile (translates into machine language program) 2. then execute
(two SEPARATE processes)
- machine language program can be executed at any time

Interpreter - program that translates AND executes the instructions

  • no separate machine language program
  • immediately executes instructions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does source code mean?

A

Statements written in a high-level language

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does a syntax error mean? Can the code run?

“An error in a program that involves a violation of language rules will be detected at____”

A

Code containing at least one syntax error CANNOT be compiled or interpreted or executed

(interpreter will just stop)
- error will be detected at COMPILE stage

  • different than a logical error (program will run, but produce incorrect results)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Python Interpreter versus IDLE

A
  • Interpreter (black screen) has two modes (1. Interactive Mode and Script Mode)
  • IDLE (integrated development environment) also has an Interactive mode (Python Shell) and Script mode
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

An extensive encoding scheme that can represent characters for many languages in the world is _____

A

Unicode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

In the ____ part of the fetch-decode-execute cycle, the CPU determines which operation it should perform

A

Decode

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

T/F any piece of data that is stored in a computer’s memory must be stored as a binary number?

A

True

  • data is stored in bytes, which comprise of eight bits equalling 0 or 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Q: Convert the following message in binary to normal text:

1001000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100 100001

A

E.g. 1001000

= 1(2^6) + 1(2^3) = 64 + 8 = 72 = H

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q: Convert 0o173 from octal to decimal
1*(8^2) + 7*(8^1) + 3*(8^0) = 64 + 56 + 3 = 123
26
Q: Convert 143 from decimal to hexadecimal
Base 16 (0 to 9, A 10, B 11, C 12, D 13, E 14, F 15) = 8*(16^1) + 15*(16^0) = 8*(16^1) + F*(16^0) = 8F or 0x8F
27
During the design phase, programmers use tools such as ______ and ______ to create models of programs
Pseudocode Flowcharts - informal - no syntax rules - not meant to be compiled or executed
28
What are the five phases of the Program Development Cycle?
1. Design the program (e.g. pseudocode, flowcharts) 2. Write the code 3. Correct syntax errors 4. Test the program 5. Correct logical errors (repeat)
29
What are the tasks that the program must perform in order to satisfy the "customer" called?
Software Requirements
30
What are the series of well-defined logical steps called?
Algorithm - algorithms are sequentially ordered
31
In flow charts what do the following shapes represent: - parallelogram - ovals - rectangle - arrows
Paralleogram = Input or Output symbol ("get" or "display") Ovals = terminal symbols (start and end of a program) Rectangle = Processing Symbol Arrows = connect symbols to represent the "flow" of the program
32
Quotation marks inside string literals: Write the code to display the following statements; 1. Don't fear! 2. Your assignment is to read "Hamlet" by tomorrow 3. I'm reading "Hamlet" tonight. Using different quotes and escape characters
1. print("Don't fear!") 2. print('Your assignment is to read "Hamlet" by tomorrow') 3. print("""I'm reading "Hamlet" tonight""") Alternative: 1. print('Don\'t fear!') 2. print("Your assignment is to read \"Hamlet\" by tomorrow") 3. print('I\'m reading \"Hamlet\" tonight.')
33
How do you add a space in between strings? e.g. Your final output is (variable)
Print statement: Use a comma to separate strings with a space e.g. print('Your final output is', variable)
34
Variable naming rules: - first character - multi-word names - numbers - special characters - spaces? - is Python case sensitive
- First character must be underscore, lower case letter, or Uppercase letter (cannot be number) - Subsequent characters can either be underscore, lower case letter, Uppercase letter, or number CANNOT be: - spaces - other special characters ($, %, &, #, >) - Keywords (as, assert, break, class, continue, def, del...except, False, finally, from, global, import, in, is, lambda, None, nonlocal, not, pass, raise, return, try, with, yield) Python is CASE sensitive Typically use camelCase
35
How do you pass a variable through the print statement?
- don't enclose the variable name in quotes print(variableName) - variable value is automatically converted to a string
36
Which of the following is not a keyword? a) eval b) assert c) nonlocal d) pass
a) eval ``` To see the full list: type help() >>>> keywords ```
37
After performing a variable reassignment, Python interpreter automatically removes the original value from memory via a process known as _____
garbage collection
38
How do you tell the type of a value?
type()
39
Can you have $, spaces, or commas in numeric literals (like floats, integers?) e.g. value = $4,352
NO Must represent $, spaces, or commas in strings
40
Given two already defined variables, i and j, write a statement that swaps their associated values.
i, j = j, i
41
Q: Given two variables iVal and fVal, containing respectively an integer and a float value, write a statement that writes both of their values to standard output in the following format: i=iVal f=fVal. For example, if iVal is assigned 5 and fVal is assigned 2.4, the statement should print the following: i=5 f=2.4
print("i=" + str(iVal), "f=" + str(fVal)) CAN'T USE ALL COMMAS otherwise it will give us spaces Use concactenation
42
How do you retrieve a user's input?
input() function - argument is a prompt (string) - e.g. input('Enter your name: ') - typically store input as a variable (automatically stored as a STRING) - therefore, will often be the argument of an int() or float()
43
What is the difference between int() and // in terms of dealing with decimals?
int() always truncates the decimals for both positive and negative numbers ``` // is a floor division: > if the result is positive, the value is truncated (e.g. 2.9 = 2) > if the result is negative, the value is rounded to the nearest whole number away from 0 (e.g. -2.9 = -3) ```
44
Math operators in Python Exception to operator precedence? 2**3**4
``` + addition - subtraction * multiplication ** exponentiation / float division // floor division (integer division) % remainder ``` *operator precedence based on PEMDAS or BEDMAS > use brackets! > left to right Exception: 2**3**4 is evaluated as 2**(3**4)
45
Calculation rules for floating-point and integer numbers What about float // int?
Operation performed on two int = int output Operation performed on two float values = float output Operation performed on 1 int and 1 float value = FLOAT output (mixed type expression) e.g. 5 * 2.0 = 10.0 Floating-point division: FLOAT output (regardless of whether two int, two float, or mixed) Floor Division: Float // Int will result in a floating point value with .0 ending (truncates it)
46
What is the value of 10 / 2 - 3
10 / 2 - 3 = 5.0 - 3 = 2.0
47
Using the remainder operator example: Create code that converts total number of seconds to hours, minutes and seconds
totalSeconds = float(input('Enter a number of seconds: ')) ``` #Get total number of hours using floor division hours = totalSeconds // 3600 ``` ``` #Get remaining number of minutes by first calculating number of minutes, then finding remainder after accounting for # of whole hours minutes = (totalSeconds // 60) % 60 ``` ``` #Get remaining number of seconds by finding the remainder after accounting for # of whole minutes seconds = total seconds % 60 ```
48
Is this allowed in Python: (2)(4) = 8
NO > need to use one of the math operators, such as *
49
How do you break very long statements into multiple lines?
Line continuation character (backslash) \ e.g. print('This is a very long sentence.', \ 'But we can make it across multiple lines.') > just execute the statement as if \ wasn't there (no need to put another comma before 'But') *any part of a statement enclosed in parenthese can be broken into multiple lines without \ e.g. (value 1 + value 2 + value 3 + value 4)
50
How do you prevent a new line of output after the following print functions execute? print('One') print('Two') print('Three') Goal: One Two Three
end' ' (adds a space) end'' (no space) Passed as an argument in the print function print('One', end' ') print('Two', end' ') print('Three')
51
What about escape characters
> All escape characters are placed INSIDE a string > don't add spaces around the escape character (just ignore it is there) \n --> new line (e.g. 'I\nlove\nyou') I love you \t --> tab (e.g. 'I\tlove\tyou!') I love you \' --> inserts a single quote (e.g. 'I\'m in love') I'm in love \" --> inserts a double quote (e.g. "She said \"SO COOL\"") She said "SO COOL" \\ --> inserts a backslash (e.g. "A\\B") A\B
52
What about item separators
Passed as another argument in the print function sep' ' (separates each individual string with a space) sep'' (REMOVES a space from each string) > great for removing space after dollar sign! sep'&' (separates each individual string with &) > double quotes after also work
53
String concactenation + When to use over comma ?
Doesn't automatically add a space between strings, just APPENDS one string to another one Can also help a lengthy string literal span multiple lines!!
54
How do we use the format() function? What are the parameters (in order)? What is the output type? Other than floating point values, what else can you format the output to?
used to ROUND floating outputs to specified decimal points, add comma separators, and specify minimum field width (left to right or alphabetically, C, D, F) > dollar signs must be added as text > output is a STRING e.g. format(argument, ',.2f') > f represents the data type of the outcome number (floating-point number) > e represents exponential data type e.g. 1.23e+04 > % represents formatting a decimal as a percentage (times 100 and adds % sign following it) e.g. format(0.5, '.0%') = 50% > d represents integers (cannot specify decimals, but can add commas and minimum field) e.g. format(123456, '10,d') Minimum field width example: '12,.2f' > minimum # of SPACE that should be used to display the value
55
Format the following to two decimal places and commas: 1234.5678
format(1234.5678, ',.2f')
56
Format the following with commas: 12345678
format(12345678, ',d')
57
Format the following as a percentage with 1 decimal place: 0.12
format(0.12, '.1%')
58
Named constants
Variable equal to a number > purpose is for easy reassignment later on
59
What is the name of this literal value: | 4, 5.2, "hello"
tuple
60
What is the name of this literal value: [True, 6, 3]
List
61
What is the name of this literal value: {1, 2, 3}
set
62
What is the name of this literal value: {'Name': 'Alan', 'Age': 21}
Dict (dictionary)
63
What is the difference between keywords and functions in Python? Is range a function or keyword?
Keywords don't have round brackets e.g. while versus e.g. print(), range()
64
Which are the literal values? result = number * 2 if result > 1000: salary = int(input('Enter your salary: ')) for counter in range(5):
Literal values include numeric literals and string literals 2 (int) 1000 (int) 'Enter your salary: ' (string) 5 (int)
65
Which are the Variables? result = number * 2 if result > 1000: salary = int(input('Enter your salary: ')) for counter in range(5):
result number salary counter
66
Which are operators? result = number * 2 if result > 1000: salary = int(input('Enter your salary: ')) for counter in range(5):
= (assignment operator) * (math operator) > (relational operator) = (assignment operator)
67
Which are punctuation? result = number * 2 if result > 1000: salary = int(input('Enter your salary: ')) for counter in range(5):
(spaces) :
68
Which are functions? result = number * 2 if result > 1000: salary = int(input('Enter your salary: ')) for counter in range(5):
int() input() range()
69
Which are keywords? result = number * 2 if result > 1000: salary = int(input('Enter your salary: ')) for counter in range(5):
if for in
70
What are decision structures? Examples?
Decision structures (aka selection structures) is a specific action that is ONLY performed if a certain condition is TRUE Single Alternative Decision structures - only one alternative path of execution e.g. IF statement > if the Boolean expression is False, the block of code is SKIPPED to the next code Dual Alternative Decision structures - two paths of execution (one path if expression is True, another path is expression is False) e.g. IF Else
71
What are control structures?
Control structure is a LOGICAL DESIGN that CONTROLS the ORDER in which the statements are executed 1. Sequence Structure --> execute in the order they appear (top to bottom) 2. Single Alternative Decision structure 3. Dual Alternative Decision structure
72
What is the expression that is tested in an IF-ELIF statement called? e.g. age <= 1
Boolean expression (returns True or False) > uses relational operators like (> < >= <= == !=) > Boolean expression DOES NOT INCLUDE THE 'IF" > if the expression is TRUE --> statement and block of code are executed
73
What can relational operators compare?
Integers and floats Strings with other strings (based on numeric code in ASCII) e.g. Password programs CANNOT compare strings with numbers
74
Write an if statement that decreases the value of shelf_life by 4 if the value of outside_temperature is greater than 90.
if outside_temperature > 90: | shelf_life -= 4
75
Will Python execute all if statements when there is no else statement?
YES - when there are multiple if statements one after the other, ALL statements will be checked
76
What will this evaluate to? 'Jennifer' > 'Jen'
True 1. First, compare the numeric codes of each letter from Left to Right > Same 2. Next, only compare the matching characters (e.g. up to 2 characters) 3. If they are identical still, the SHORTER string is considered SMALLER than the longer string
77
What would the following code display? ``` s1 = 'New York' s2 = 'Boston' if s1 > s2: print(s2) print(s1) else: print(s1) print(s2) ```
s1 > s2 looks at whether New York > Boston - N is larger than B, so s1 > s2 Output: Boston New York
78
Nested decision structures - what do they look like?
Nested decision structures are used to test MORE THAN ONE CONDITION - can either nest the if-else statements inside the IF statement or inside the Else statement ``` if salary >= min_salary: if years_on_job >= min_years: print('Yay!') else: print('Aw no!') else: print('Boo') ``` ``` OR: if salary >= min_salary: print('You qualify!') else: if years_on_job >= min_years: print('So close!') else: print('Aw no!') ```
79
T/F: When you have more than one condition to test, you should always use if-elif-else statements
F - elif-else statements are NEVER required - this is because the same output can be accomplished using nested if-else statements
80
What are logical operators? What do they allow programmers to do?
Logical operators are used to create COMPLEX BOOLEAN EXPRESSIONS Include: - and - or - not( ) Logical operators 'and' and 'or' CONNECT boolean expressions to create compound boolean expressions 'not' reverses the truth of a Boolean expression > needs brackets! (however code will still run without them)
81
What will the output be? temperature = 30 ``` if not(temperature > 100): print('This is below the max temperature') else: print('This is above the max temperature') ```
Since temperature > 100 is FALSE, the first if statement will EXECUTE not(false) = True This is below the max temperature
82
Write code to check whether your age is between 19 and 25, inclusive
if age >= 19 and age <= 25:
83
Write code to check whether your age is outside 19 and 25, inclusive
if age < 19 or age > 25: | **CANNOT be 'and' it is impossible for age to be less than 19 and greater than 25
84
Assume x refers to an int. Write a Boolean expression that is True if the variable x refers an even number.
x % 2 == 0
85
What are the two names to describe a variable containing only the values True and False?
Boolean variable Flag When the flag variable is set to True (e.g. hungry = True), the condition exists
86
When checking whether a condition exists using bool variables, you need to use == relational operator e.g. if sales_quota_met == True:
NO if sales_quota_met: works too!
87
Assume that a variable hoursWorked has been initialized. Write a statement that assigns the value True to the variable workedOvertime if hoursWorked is greater than 40 and False otherwise. Show 2 solutions
if hoursWorked > 40: workedOvertime = True OR workedOvertime = hoursWorked > 40
88
Running programs in Interactive mode (shell) versus running from file (editor)
Interactive mode goes through: read > evaluate > print Running programs from file require a PRINT statement