Comp Sci Quiz 1, Comp Sci Quiz 2, Comp Sci Midterm

¡Supera tus tareas y exámenes ahora con Quizwiz!

Indentation for if statements

All indented lines after an if statement will be executed if the test passes, and the entire block of indented lines will be ignored if the test does not pass.

In/not in keyword

Allows us to check whether an element exists in the list or is missing from the list. Example: requested_toppings= ['mushrooms', 'onions', 'pineapple'] 'mushrooms' in requested_toppings True

Comment

Allows you to add notes in English in your code. You can write a a brief description of what it is you are doing in your program and what is occurring at each step.

Computer

An electronic device and programmable machine. It stores and processes data, executes a set of instructions, and receives an input and produces an output.

Boolean expression

Another name for a conditional test. A Boolean value is either True or False.

Combining lists and strings using +

Lists and strings can be combined using + as long as they are the same data type Example: "My favorite animal is" + animal[0] + "."

Application software

Programs that make the computer useful to the user by providing a more specialized type of environment for them to work in. Examples include Word, Chrome, and games.

Type

The two types of variable data are either numbers or strings.

Main/primary/volatile memory (RAM)

The volatile, or temporary, memory of a computer is used by the operating system and apps to store data. When the computer is turned off, the data is erased, but this type of memory is much faster. The RAM contains bytes and bits that form an address made of 1s and 0s.

List

Used to store or list information, as it is more efficient than saving each piece of data in separate variables. A collection of items or information that is stored in a list. Lists are placed in square brackets and items in the list are separated by commas. A list can be of numbers, letters, or characters. Make sure the name of the list is plural. Example: cars = ['civic', 'fit', 'CRV', 'HRV']

Adding elements to a list

- Append element to the end of a list Example: animals.append('fish') - Insert element into an index Example: animals.insert(0, 'mouse')

Methods to delete elements in a list

- del: deletes an element that you know the index of such that you cannot later use it del listname[index] - pop( ): removes element from the end of the list, but allows you to use it after deleting it; listname.pop( ) - pop(index): removes an element at a certain index, but allows you to use it after deleting it; listname.pop(index) - remove( ): remove a value without knowing the index, such that you can later use that value; you can remove the value or variable containing that value within the () syntax: listname.remove(' ')

Methods to organize a list

- sort: permanently sorts elements in a list in alphabetical order; listname.sort( ) - reverse sort: permanently sorts elements in a list in reverse alphabetical order; listtname.sort(reverse = True) - sorted: temporarily sorts elements in a list in alphabetical order without changing the original list order; sorted(listname) - reverse: reverses the order of the original list; listname.reverse( )

Why should we study computer science?

- there are endless career options and fields to go into - jobs in computer science are ample and have high salaries - it allows us to become well-rounded individuals and gain critical thinking and problem solving skills - we can have a positive impact on society

Rules for naming variables

1. Can be a combination of letters, numbers, and underscores 2. Must start with a letter or underscore (cannot start with a number) 3. Cannot contain spaces 4. Don't use python keywords (like print) 5. Short but descriptive!

Steps to write a program

1. Design your program via an algorithm 2. Write your code in a programming language of your choice 3. Fix syntax errors to make your program run 4. Test the program with different inputs

Stripping whitespace methods

1. rstrip() --> removes white space on the right 2. lstrip() --> removes white space on the left 3. strip() --> removes white space on both sides, but not from the middle Example: favorite_lanugage = "\tJava" print(favorite_language.lstrip()) Java

Zen of Python

A collection of 20 guidelines or principles for how one should code in Python.

Program

A collection of instructions that performs a specific task when executed by a computer. Programs can be understood by computers.

Input Processing Output (IPO) charts

A commonly used tool in algorithm design that records the input, processing, and output of a process.

Interpreter

A computer program that reads and executes code. It translates the code into something the computer can understand and immediately executes the operation.

Flowchart

A diagram that graphically depicts the steps in a program.

Variable

A label that you can assign a value to. The variable points to a certain value stored in memory. The three components of a variable are the name/identifier, the data/value, and the type of data.

IDLE

A program that provides tools to write, execute, and test a program. It runs in interactive mode and has a built-in text editor.

High-level language

A programming language like Python or Java that is designed to be easy for humans to read and write.

Traceback

A record of where the interpreter ran into trouble with the code.

Operating system

A set of programs that manages the computer's hardware devices and controls their processes. Examples include Windows or IOS.

Programming language

A special language used to write computer programs.

Algorithm

A step-by-step procedure or method used for solving a problem, performing a calculation, or completing a task. Your outline for how you will write your program. Algorithms themselves are not understood by computers, but programs are.

Tuples

A tuple is a list that cannot be changed or modified. Thus, use tuples only when you want to store a set of values that should not be changed. You define it using parentheses rather than brackets. You can access individual elements in a tuple, but you can't change their values. However, you can redefine the entire tuple. Example: dimensions = (200, 50) dimensions = (400, 100)

Float

A type of number that contains a decimal point, like 5.0.

Integer

A type of number that is a whole number and not a fraction, like 2.

Number

A type of variable that contains numbers only and that is used to store numerical information during calculation.

String

A type of variable that is a combination of letters (characters) and numbers. Strings must be placed in double or single quotes. If you want to put apostrophes inside of a string, make sure they are different from the starting and ending quotes. Example: "That's mine!"

Constant

A variable whose value stays the same throughout the program. We denote a constant by using all capital letters. Example: MAX_VALUE = 5000

Conditional test

Allows us to check for a specific condition and perform a task based on that condition. The expression used in the if/else statement, which either evaluates to true or false. If a conditional test evaluates to true, statements inside the if statement get executed, but when it evaluates to false, statements in the else part get executed. Example: car = 'bmw' car == 'bmw'

Whitespace

Any nonprinting character that shows up as a blank space on the screen, such as a space, tab, or new line. tab \t new line \n Example: print("Languages:\nEnglish\nSpanish") Languages: English Spanish

Underscores

Can be used in Python to separate big numbers since the interpreter will just skip over them.

Hardware components

Central processing unit (CPU) Primary storage/RAM Secondary storage Input devices Output devices

And keyword

Checks multiple conditions; all conditional tests must pass to return True Example: age_0 = 22 age_1 = 18 age_0 >= 21 and age_1 >= 21

F-string

Combines strings together by replacing the value of the variable in braces. Example: first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" print(full_name.title()) Ada Lovelace

Input/output (I/O) devices

Devices that both accept and present data. Examples include headsets or touch-screens.

Output devices

Devices that display data from the computer to the outside world. Examples include screens, printers, or speakers.

Input devices

Devices that send data into the computer from the outside world. Examples include keyboards, scanners, or cameras.

Elements in a list

Elements can be numbers or strings. Each element in a list has a position and an index. Its index is its position - 1 since the first element in a list has index 0. Elements can also be accessed backwards (an index of -1 is the last element, -2 the second to last, etc). Example: cars[0] --> 'element' print(cars[0]) --> element

For loop

For loops run through entire lists without having to go through each elements one by one and performs repetitive tasks. Anything indented in the loop is repeated once for each item in the list, while any lines of code after the for loop that are not indented are executed in the usual way without repetition. Example: magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician)

If statements

If the conditional test evaluates to True, Python executes the code following the if statement, but if the test evaluates to False, Python ignores the code following the if statement. Format: if (conditional_test): do something Example: age = 19 if age >= 18: print("You are old enough to vote!")

Python's interactive mode

In this mode, you can enter commands via keyboard and immediately get the output. The shell.

Python's script mode

In this mode, you can save commands or a program in a script file and then later execute it. The new file.

Pseudocode

Informal language or method used to outline and write algorithms that can later be translated into actual code in order to run programs.

Copying a list

Make a slice of the entire list and assign this to the list you are trying to copy it into. new_list = old_list[ : ]

IPO chart

No code goes in an IPO chart. You are writing in English words what the input and output are and describing in the process what you will be doing in your program (assigning values to variables, combining strings, printing variables, etc)

Or keyword

Only one conditional test must be true to return true Example: age_0 = 22 age_1 = 18 if(age_0 >= 18) or (age_1 >= 18): print ('both can drive!')

Method/Function

Performs an operation/action on a piece of data

Compilers and assemblers

Programs that translate high-level languages to machine languages that the computer can understand.

Styling your code

Python Enhancement Proposal (PEP) has a set of guidelines for how to style and structure your code. An example is separating distinct tasks using blank lines.

Multiple Assignment

Python allows a programmer to assign values to several variables at once. Example: x, y, z = 0, 0, 0

Indentation

Python uses indentation to determine when one line of code is connected to the line above it. Indentation errors occur with improper indentation, such as forgetting to indent in a for loop or indenting unnecessarily. Example: magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("Thank you everyone, that was a great magic show!") This will print the "thank you everyone statement" three times instead of just once. This is a logical error, rather than a syntax error.

Reassigning an element in a list

Reassignment Example: animals = ['dog', 'cat'] animals[1] = 'bird' print(animals) ['bird', 'cat']

Assembly Language

Resides between machine language and higher-level languages. It assigns letter codes to each machine language instruction.

Programmer's Toolbox

The 6 essential tools in every programming language. 1. Variables 2. Arithmetic expressions 3. Input and Output 4. Conditional statements 5. Repetition statements 6. Functions

Syntax highlighting

The Python interpreter displays code in different colors depending on the type of code (variables, functions, etc). This improves the readability of the code and makes it easier to spot mistakes.

Data/value

The actual value stored in the variable. Example: The value in age = 20 is 20.

Central Processing Unit (CPU)

The brain of the computer that is made up of the ALU and Control Unit. It performs the fetch, decode, execute cycle in order to process instructions and perform operations.

Von Neumann Machine

The first ever computer that allowed for input, output, processing, and memory.

Changing case methods

The following are methods/functions that go after a variable and a dot. 1. title() --> puts value of variable in title case 2. upper() --> puts value of variable in upper case 3. lower() --> puts value of variable in lower case Example: name = "ada lovelace" print(name.title()) Ada Lovelace

Machine language

The language made up of binary-coded instructions that a computer can understand.

Name/identifier

The name of the variable. We can access the data stored in memory under this name/location. Example: The variable name in age = 20 is age.

Control Unit (CU)

The part of the CPU that fetches and decodes instructions and tells the other hardware devices what to do based on the instructions.

Arithmetic Logic Unit (ALU)

The part of the CPU that performs operations and tasks.

Software

The programs that run on a computer, either the operating system or the application software.

Range function

The range() function makes it easy to generate a series of numbers. Example: This will generate a list of numbers from 1 to 5 since the range function goes until but excludes the second value. for value in range(1, 6): print(value) The range function can also be given a third value, which Python will read as a step size. Syntax: list(range(starting number, ending number, step size)) Example: even_numbers= list(range(2, 11, 2)) print(even_numbers)

Syntax

The set of rules that defines the combinations of symbols that are considered to be correct for a particular programming language.

Computer science

The study of computers and computational systems. It is the theory, experimentation, and engineering that enables the use of algorithms to process, store, and communicate digital information.

Secondary/non-volatile memory

This memory stores information permanently and holds data when the computer is off. One might store photos and documents on this type of memory. Examples include flash drives, SD cards, or hard drives.

Slices of lists

To make a slice, you specify the index of the first and last element you want to work with, but it stops one item before the second index you specify. If you omit the first index in a slice, Python automatically starts your slice at the beginning of the list. If you omit the second index in a slice, Python automatically starts your slice at the specified index and ends at the end of the list. Example: computer_scientists = ['Alan Turing', 'Donald Knuth', 'Grace Hopper'] print(computer_scientists[1 : ])

Methods on individual values of a list

Upper, title, lower cases, tabs, stripping, operations if numbers Syntax: listname[indexofelement].function() Example: print(animals[-4].title( ))

Styling if statements

Use a single space around comparison operators, such as == , >= , <= . Example: if age < 4

If-elif-else chains

Use this when you will need to test and evaluate more than two possible situations. Python runs each conditional test in order until one passes, such that it executes only one block in the chain. You can use as many elif blocks as needed, and the else block may be omitted. Example: if age <4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.")

If statements with for loops

You can combine if statements with for loops to check conditions for elements in a list. Example: requested_toppings = ['mushrooms', 'green peppers', onions'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Sorry, we are out of green peppers.") else: print(f"Adding{requested_topping} .")

List function

You can convert the results of range() directly into a list using the list() function. Example: numbers = list(range(1, 6)) print(numbers)

Statistics with numerical lists

You can find the minimum and maximum values of a list of numbers as well as the sum of all of the values in the list. Example: digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] min(digits) max(digits) sum(digits)

Looping through a slice

You can use a slice in a for loop if you want to loop through a subset of the elements in a list. Example: computer_scientists = ['Alan Turing', 'Donald Knuth', 'Grace Hopper'] for scientist in computer_scientists[1: ]: print(scientist)

If-else statements

You can use an if-else statement if you want to take one action when a conditional test passes and a different action in all other cases. The else statement allows you to define an action or set of actions that are executed when the conditional test fails. Example: age = 19 if age >= 18: print("You are old enough to vote!") else: print("Sorry, you are too young to vote.")

Number operations

add (+) subtract (-) divide (/) --> creates floats multiply (*) raise to a power (**) Python follows PEMDAS when we combine the operations and specify what we want done first using parentheses. Example: (4 + 2) * 6 = 36

Conditional test operators

equality: == inequality: != greater than: > greater than or equal to: >= less than: < less than or equal to: <=

Length of a list

tells you the number of elements in a list len(listname)


Conjuntos de estudio relacionados

Mattock's Document 2nd Semester Final

View Set

Chapter 6 Analyzing the auidence

View Set