cs22a midterm

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

flow of execution

-The order in which statements are executed during a program run.

Algorithm characteristics

-Unambiguous - algorithm should be clear; steps, inputs/outputs should be clear, precise, and must lead to only one meaning -Input - algorithm should have 0 or more well defined inputs to operate on -Output - algorithm should have 1 or more well defined outputs -Finiteness - algorithms must terminate after a finite number of steps -Independence - algorithm should have step-by-step directions, which should be independent of any programming language

Logical operators

-can be used to create complex Boolean expressions ○ [and] operator and [or] operator: binary operators, connect two Boolean expressions into a compound Boolean expression ○ [not] operator: unary operator, reverses the truth of its Boolean operand ● Logical operators can be used to simplify nested conditional statements

return statement

-ends a function and sends value(s) from a called function back to the calling function

Data types: Boolean Expression (bool)

-expression that stores two or more values (i.e True or False ONLY) ■ Ex.x=9 ● print(x == 9): → true ● print(x >= 9): → true ● print(x == 10) → FALSE ■ a=200//b=33 ● If b>a: ○ print("b is greater than a") Else:print("b is not greater than a")

while loop

-tests a condition, if true, keeps executing an instruction block -pretest loops: loop condition is tested FIRST BEFORE the loop body is executed -Flow of execution: 1.Evaluate the Boolean expression to determine whether the condition is true or false. 2.If condition is false, exit the while statement and continue execution at the next statement. 3. If the condition is true, run the body and then go back to step 1.

Arguments vs. Parameters

-variables passed into a function that are needed for processing -provided when the method or function is called -local to function it's defined in if not passed -example: def F1 (x, y): #function definition with 2 parameters """Takes 2 parameters, add them and prints result""" A= x + y print (A) def main(): F1(3, 7) #Function call using 2 arguments print ("Statement prints when execution returns from function") main()

Nested Decision Structures

To test more than one condition, a decision structure can be nested inside another decision structure.

Interactive Loops

a loop that allows part of a program to repeat according to the wishes of the user

for statement

iterate through a sequence of values

Nested Loops

occur when a loop structure exists within another loop structure

Data types: float

represents numbers with fractional parts (decimals)

Data types: Str

represents text (sequences of characters called strings)

Data types: int

represents whole numbers

Boolean Variables

● A Boolean variable is a location in memory that can contain either True or False ● Boolean variable references one of two values, [True] or [False] ○ Represented by [bool] data type ● Commonly used as flags: ○ Flag: variable that signals when some condition exists in a program Flag set to false > condition does not exist Flag set to true > condition exists ● EX:○ If sales >= 50000.0: ■ Sales_quota_met = true ○ Else: ■ Sales_quota_met = false

Slicing string for substring access

● A substring (segment of a string) is a slice ● To slice a continuous section of a string a colon operator is used inside square brackets: [begin : end] ○ Begin index is inclusive, end index is exclusive ○ If the end index is beyond the end of the string, it stops at the end

Abstraction

● Abstraction is detail removal and generalization: -A tool for reducing complexity ● Abstraction is intentionally hiding information that is unnecessary for others to know behind a more convenient interface

The if Statement (Single Selection)

● Actions are conditionally executed: -Action performed when a condition is true -If the condition doesn't exist, the action isn't performed ● Provides only one alternative path of execution - If condition is false, exit the structure -ONLY the TRUE condition takes a different path ● Used for asking Yes/No or True/False questions in a program ● SYNTAX: ○ The if clause: includes the keyword if followed by condition (Boolean expression), ends with colon: ○ Body follows and must be indented ○ Condition can be true or false ○ When the if statement executes, the condition is tested

Boolean Expressions and how to use them as conditions:

● An expression tested by if statement to determine if it is true or false ● The Boolean expression following if is the condition ○ If the condition is true, the indented statement runs. ○ If not, nothing happens ● A condition is a Boolean expression that ○ Compares things and ○ Tells us if the criteria set by comparison is true/false ● To create Boolean expression, we use operator: ○ Relational: <, <=, >, >=, ==, != ○ Logical: and, or, not

Understand how Python evaluates an Assignment Statement:

● Assignment statements create new variables and give them values to refer to/store ● The equal sign (=) is used to assign a value to a variable ○ EX: myLuckyNumber = 7 ● The "=" is the ASSIGNMENT OPERATOR, not the equality operator

String operations and methods

● CONCATENATING STRINGS: literally just adding two strings together ○ Str1 = hello / str2 = world ○ print('str1 + str2 =', str 1 + str 2 ○ Displays hello world ● MULTIPLYING/REPEATING STRINGS: ○ Multiplying a string by an integer repeated the string the specified number of times ○ EXAMPLE: letter x multiplied by the number 10 Print ('x' * 10) Output: xxxxxxxxxx ○ A string can not be multiplied by another string ○ String multiplication can be used for text alignment

How text is encoded (ASCII table)

● Computers store and manipulate characters as numbers (binary 0's and 1's)

Function Definition

● Functions are self-contained block of code used to define a specific task ● A function is a group of related statements that perform a specific task -The def keyword is used to define a function -The def keyword is followed by the function name -Open and close parentheses must follow the function name -Parameters, if any, are included inside the parentheses -The parentheses is followed by a colon -The colon is followed by docstring (description the function does include triple quotes) -Body of function (statement block) follows the colon and must be indented 4 spaces

Boolean functions

● Functions can return Booleans, which is often convenient for hiding complicated tests inside functions ● It's common to give Boolean functions names that sound like yes/no questions ● Boolean functions are often used in conditional statements: ○ Ex: if is_divisible(x, y): ■ print('x is divisible by y') ○ Is_divisible returns either True or False to indicate whether x is divisible by y

Decomposition using Functions - Why use Functions?

● Functions help decompose programs into smaller and modular chunks. ● Functions are procedural abstraction ● Allows programmers to create REUSABLE code

Defining and Calling a Void Function

● Functions that do not return a value are called void functions ● Void functions might display something on the screen or have some other effect, but they don't have a return value ● If you assign the result of a void function to a variable, or print it, you get a special value called None.

The if-elif-else Statement (Multiple Selection)

● If-elif-else statement is a special version of a decision structure ● Can include multiple elif statements ○ If, elif, an else clauses are all aligned ○ Even if more than one condition is true, only the first true branch runs ● Better option over nested if-else > logic is easier to follow

Write program that uses the input() function to capture keyboard input from the user:

● Input function reads a line of text from standard input ● Has an optional parameter, which is the prompt string ● SYNTAX: ○ name = input("What's your name?") ○ print = ("Your name is," name)

Express an algorithm in flowchart - know what the symbols in a flow chart represent:

● Oval: indicates beginning and end of an algorithm ● Parallelogram: indicated the input or output of information ● Rectangle: indicates a computation, with the results of the computation assigned to a variable ● Diamond: indicates a point where a decision is made ● Hexagon: indicates the beginning of the repetition structure ● Double lined rectangle: used at a point where a subprogram is used ● Arrow: indicates the direction of flow of the algorithm. ○ Circles with arrow: connects flowchart between pages.

Negative Indexing

● Python allows positive and negative indexing for its sequences ● The index of -1 refers to the last item, and so on

Accessing characters within a string

● Python strings are indexed sequences ● We can access individual characters in a string using an index specified in square brackets notation [ ] ● The index value must be an integer and starts at zero ● Using float or other types will result into TypeError ● Trying to access a character out of index range will raise an IndexError

understand the different types of decision structures and what their applications are:

● Single: if statement ● Double: if-else statement ● Multiple (cascading/chained) if statements ● Nested if statements

How strings are stored in memory

● Strings are stored in consecutive bytes in memory ● The string "hello" would be stored in 5 memory locations next to each other ○ Each byte holds the binary code corresponding to a character

Creating strings

● Strings can be created by enclosing characters (text) in quotes (' or ") ● Even triple quotes can be used in Python but generally used to represent multi-line strings and docstrings

Describe what makes up the syntax of a programming language such as Python:

● Syntax: structure/form of code that makes up Python -Keep everything in def main(): ??? -ALWAYS end with main() -KEEP EVERYTHING INSIDE MAIN (unless custom functions are created, then call INSIDE MAIN) -Indentation: indent if you want to keep something inside that code ● Case sensitive - DO NOT FORGET PARENTHESES OR QUOTATIONS!! It will lead to a syntax error, which is an error that pops up in your code ● Iterative if 5 > 2: print("Five is greater than two!") ● Comments - use # ● Multi-line strings - multi line comments made with triple quotes (""") or (''')

Range function

● The range() function is used to create a list of numbers between (x,y) and is used to indicate how many times the loop will repeat ● The sequence of numbers the range() built-in function generates, start with 0 ○ Ex: range(10) will generate numbers from 0-9 ● range() takes three parameters: start, stop, and step size ○ Start defaults to 0 ○ Step size defaults to 1 if not provided ● We can use the list() function to see the numbers range iterator creates ● list() is a built-in Python function that turns the sequence into a list

The if-else Statement (Double Selection)

● Two possible paths of execution ○ One is taken if the condition is true ○ The other if the condition is false ● Two outcomes for a condition: True or False ● Both the TRUE condition and the FALSE each have different paths ● Double selection ○ Executes a block of statements when a condition is true, ○ Otherwise executes another block of statements if condition is false ● Used for either-or situations ● SYNTAX: ○ If (temperature < 40): print('A little cold, isn't it?') ○ Else: print('Nice weather we're having.')

Variable Naming Rules

● Variable names can be a combo of letters, numbers, and underscore (_) ○ Can NOT use special symbols like !, @, etc. > generates invalid syntax ○ MUST start with a letter○ No spaces or keywords allowed ● Variable names are case sensitive

Define and use variables in a program:

● Variable: a name, an abstract symbol, that represents a value -Used to store values -Given unique names -Not permanently tied to a value - variables value can change

Variable Reassignment:

● Variable: storing values that can be used and/or changed in the program ○ Holds user inputs, can be referred to with a certain name given (ex. x = 9; x is storing the value of 9 into program) ● Basically overwriting the original variable with another desired value ○ Example: x=9 x = 1004 ● New value of x → 1004 since we want the program to update and store this new value

String Traversal

● We can traverse a string using: ○ A while statement ○ An iteration variable ■ MyString [beginning index : ] prints the string from beginning index to end ■ MyString [ : ending index ] prints the string from start to ending index - not inclusive ■ MyString [ : ] prints the string from start to end ○ And the len() function ● The indefinite or conditional loop (while) keeps iterating until certain condition is met ● We can construct a loop to look at each of the letters in a string individually ● [for] statement can be used to iterate through a sequence of values ● For loops are definite loops - they execute a definite number of times ● In a definite loop the number of iterations is determined when the loop starts ● Unlike while loops, for each loops need to know ahead of time the maximum number of times to execute the loop body


Ensembles d'études connexes

EST Essentials - Chapter 1 Concepts

View Set

Chapter 1: The Nurse's Role in a Changing Maternal-Child Health Care Environment

View Set

Acct Quiz 2 Ch 17 CPA Exam Questions

View Set

Anatomy - Palmaris longus muscle

View Set

Chap. 6 Socioemtional Development in early childhood

View Set