Introduction to Computer Programming (Exam 1)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

The input function

1. Always returns a string 2. Only takes one argument 3. Is returned when the user hits 'enter'

Numeric data types

1. Whole numbers that do not contain decimal point 2. Abbreviated as int

Repetition structures/loops

1. Write the code for the operation one time 2. Place the code into a special structure that causes Python to repeat it as many times as necessary 3. There is more than one kind of repetition structure/loop in Python

Augmented assignment operators

1. a short-hand self-referential assignment c+=5 means c=c+5 c-=5 means c=c-5 c+=5 means c=c*5 c/=5 means c=c/5 c%=5 means c=c%5

The Format Function: Formatting Numbers

1. generate a printable string version of a float or integer number 2. format() takes two arguments-a number and a formatting pattern (expressed as a string) 3. returns a string, which can only be treated like any other string variable (can be printed immediately, stored, etc.) e.g. a=10000/6 e=format(a,">20,.2f") # output: 1,666.67

The Format Function: String Formatting

1. generate a string that contains known number of characters 2. it can be left (<) or right (>) justified 3. takes two arguments a string and a formatting pattern (expressed as a string) e.g. x=format("craig",">20s") # output: craig

Two-way if statement

1. if condition is true the block of execution under it is executed 2. if condition is false then move on to a second if statement positioned at the same level of indentation below the previous if statement 3. the second if statement should have the opposite condition so that it the program will continue to run in all conditions

Infinite loop

1. occurs when the boolean expression will never evaluate to false 2. you can interrupt IDLE to end the while loop by pressing CTRL-C

Sentinels

1. pre-defined value that the user can type in to indicate that they are finished entering in data (i.e. "type 'finish' when you are finished") 2. useful when user has many items to enter into a program; you do not have to keep asking them after each iteration if they want to continue nor do you require them to know exactly how many items they are entering 3. must be distinctive enough that they will not be mistaken for regular data

Repetition structures/loops: advantages

1. program is shorter 2. takes less time 3. more efficient (if there is a mistake it does not have to be fixed many times; if you need to change something you only have to change it once)

String comparison

1. reduce strings to their zeros and ones and then compare them numerically 2. look at the standard ASCII Table (note: null="" and has lowest value and alphabet increases in value as it is read forward)

Accumulator variables

1. set up accumulator variable outside of the loop, generally right before you enter a repetition structure 2. decide value at which you would like to start accumulator variable; 0 or 0.0 is best for when you are adding values up from nothing 3. use a self-referential assignment statement when incrementing an accumulator variable (i.e. counter=counter+1; you reset your variable to depend on its previous value plus another value so that through each iteration its current value is maintained and then added to)

String literals

1. strings that you define inside of your program 2. hard-coded values 3. must be delimited using a special character (" or ' or """ or ''') so that Python knows the characters you typed should be treated as text/string and not a function call

Generating a random integer

1. use the randint() function/must import this module 2. takes two parameters (a starting integer and an ending integer) 3. returns a random integer in the range of your two parameters

The Format Function

1. used to format a number/string/variable before you print it to user 2. takes two arguments-a number/string and a formatting pattern (expressed as a string) 3. returns a string which can be treated like any other string (i.e. you can print it out, store its value in a variable, etc.) 4. first argument passed to the format function is the item that you wish to format 5. second argument is the formatting "pattern" you wish to apply to this item 6. you must specify the data type which you wish to format 7. the formatting pattern is applied and returns the number with pattern as a string

String length

1. you can ask Python to count the number of characters contained in a string 2. msut use the len() function e.g. myname="ellie" print(len(myname)) # output: 5

Comparison/relational operators (there are six)

== != >= <= > <

Python's reserved words

False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield

IDLE

Integrated DeveLopment Environment; has two modes

Math Operations

Operation:Operator Addition:+ Subtraction:- Multiplication:* Division (floating point):/ Division (integer):// Remainder operator (modulo):% Exponents:** Square root:**(1/2) 1. Expressions: use operators along with numeric data to create "math expressions" that Python can "evaluate" on our behalf 2. Numeric data can be numeric literals or variables that are numeric 3. An operand is the numeric value that on which the operator works 4. Python supports standard order of operations (PEMDAS)

Output

Some kind of tangible/visible/readable product is constructed (screen display, printout, 3D fabrication)

Sources of input

User (keyboard, mouse, etc.), hardware (scanner, camera, etc.), data (file, the Internet, etc.)

String Concatenation

You cannot add strings together, but you can concatenate them e.g. a = input("First Name ") b = input("Last Name ") c = b + "," + a print (c) # output: Last Name, First Name

IDLE: Script mode

allows programmer to write a program (saved as a "Text file" on your computer) and then your commands can be processed whenever you like

IDLE: Interactive mode

commands are immediately processed as they are received

Logical oeprators

used to create complex Boolean expressions that evaluate more than one condition at the same time; there are three main logical operators: 1. not, evaluated first, boolean expression must be false for it to evaluate to true 2. and, evaluated second, both boolean expressions must be true to evaluate to true 3. or, evaluated third, only one boolean expression must be true for it to evaluate to true

Arithmetic operators

we have already seen these: + - * / // % ** ( )

Conditional statements: one way if statements

1. "if" keyword + condition +: 2. the condition is assumed to be boolean 3. block of execution (what Python reads if the condition statement is true and will skip over if the condition statement is false) 4. continues to the next line of code that is not indented (or an elif else statement) after it either reads or skips over the block of execution

Separating print() function arguments

1. By default Python places a space in between arguments that you use in print() function calls 2. to override this use the 'sep' argument at the end of the line, MUST be at the end e.g. print("one","two",sep="*") # output: one*two

Strings

1. Data that is textual in nature 2. Can contain 0 or more printed characters

Line Continuation

1. Expressions and print () function calls can get to be very long 2. You can use the "\" symbol to indicate to Python that you'd like to continue the expression or print function call onto another line

Three components of variables

1. Identifier (i.e. the variable name) 2. Value (i.e. the item being stored) 3. Data type (i.e. what kind of data is being stored)

Floating point numbers

1. Numbers that contain a decimal point 2. Abbreviated as "float" in Python

Mixed Type Expressions

1. Python allows you to mix ints and floats when performing calculations 2. The result of a mixed-type expression will evaluate based on the operands used in the expression 3. int + int = int float + float = float float + int = float

Line endings

1. Python automatically places a newline character at the end of each line 2. to override this use the 'end' argument at the end of the line, MUST be at the end e.g. print("one",end="") print("two",end="") # output: onetwo

Commenting

1. Python supports multi line comments through the use of the triple quote delimiter 2. Use # to comment your pseudocode 3. Commenting also allows you to turn off parts of your code, which can be useful in isolating an issue in the logic or syntax of your program during debugging

Three types of data

1. Strings 2. Numbers (numeric) 3. Logical Values (True/False)

Error types

1. Syntax errors: the code does not follow the rules of the language; for example, a single quote is used where a double quotes is needed; a colon is missing; a keyword is used as a variable name. 2. Runtime errors: In this case, your code is fine but the program does not run as expected (it "crashes"). For example, if your program is meant to divide two numbers, but does not test for a zero divisor, a run-time error would occur when the program attempts to divide by zero. Another example: when you store a variable as the integer or float of an input, and the user enters a value that is not numeric (like "apple") 3. Logic errors: these can be the hardest to find. In this case, the program is correct from a syntax perspective; and it runs; but the result is unanticipated or outright wrong. For example, if your program prints "2+2=5" the answer is clearly wrong.

Nesting data type conversions

1. Using a single line to convert a user's input into a value other than string 2. float() and int() are data type conversion functions; they each take one argument and convert that argument into the specified data type

Escape characters: conjunctions

1. \n forces a line break 2. \t forces a tab e.g. print('line 1\nline 2\nline 3\n') # output: line 1 line 2 line 3 x=5 y=4 print('X','\t','Y','\t','X*Y') print(x,'\t','y','\t',x*y) # output: X Y X*Y 5 4 20

Function

1. a pre-written piece of computer code that will perform a specific action or set of actions. 2. Python comes with many built-in functions and you can also write your own. 3. Functions always begin with a keyword followed by a series of PARENTHESIS 4. You can pass one or more arguments into a function by placing data inside the parenthesis. Different functions expect different numbers of arguments and different argument types 5. "Calling" a function means that you ask Python to run a function

Condition controlled loops

1. a programming structure that causes a statement or set of statements to repeat as long as the condition under which they are nested evaluates to True 2. can implement a condition controlled loop by writing a "while" loop in Python 3. useful when the task requires an unknown number of iterations

Nested if statements/nested decision structures

1. allows you to evaluate additional conditions within your statement if that conditional statement was met (i.e. allows you to ask follow up questions if one of your statements is true) 2. INDENTATION IS KEY

Escape characters

1. allows you to perform special actions inside of the confines of a delimiter 2. In Python the escape character is "\" 3. it causes Python to treat the next character as "special", which in most cases means you ignore the next character to prevent it from taking on its regular meaning which in some cases will mess up your program/delimiter e.g. print('Hi, it\'s Ellie') # output: Hi, it's Ellie

Optional statements

1. cannot stand on their own; they are "married" to the if or the elif statements directly above them, ONLY married to the one conditional statement directly above it 2. elif is a "follow-up question" 3. else is the final question and is the "catch all" category, there is no new condition, rather it is anything that did not satisfy previous conditions, i.e. one of the blocks of execution is GUARANTEED to be read

While loop

1. evaluate a boolean expression 2. if false, the program skips the block of statements associated with the while loop and continue with the following program (indented at the same level as the condition) 3. if true: a)executes the series of statements (marked via INDENTATION) under the condition b)at the end of the statement block re-evaluates the condition c)if it is still true it repeats the block of statements d)if it is false it skips the block of statements associated with the while loop and continues the following program (indented at the same level as the condition) 4. iteration=one process of going through the entire loop (evaluation of boolean expression all the way through execution of the statement block and back again to re-evaluate the boolean condition) 5. it is a "pre-test" loop, which means that it only iterates upon the successful evaluation of a condition; must evaluate the condition FIRST and then execute the block if it is true 6. the above means that you have to set up the loop prior to Python being able to work with it (like setting up a control variable)

Boolean data

1. is binary and reduces to true or false 2. Boolean expressions utilize three kinds of operators: arithmetic operators, comparison operators, and logical operators

Basic string manipulation (lower and upper)

1. lower: converts the characters in a string to all lowercase 2. upper: converts the characters in a string to all uppercase 3. they are not written directly into Python library and exist inside string module; as such they must be referred to using "dot syntax" e.g. string_lc=str.lower("Ellie Dempsey") string_lc = ellie dempsey string_uc=str.upper("Ellie Dempsey") string_uc = ELLIE DEMPSEY

Selection Statement

1. perform an action if certain conditions are met 2. if not met then the action is not performed 3. like yes or no questions

Random module

1. random.randint(1,10): will generate a random number between 1 and 10, including 10 2. random.random: return the next random floating point number in the range [0.0, 1.0); includes 0, but does not include 1! 3. random.seed: allows you to change the way the computer generates random numbers (the default is to generate based on computer time so it is not truly random); the seed (i.e. number that you input) is what is fed to the process that generates the first random number; if you want a different set of numbers every time you must have a different seed value every time; useful if you want to reproduce results; in the form: random.seed(a=None, version=2) Initialize the random number generator. 4. random.uniform: return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a; similar to random.random except that you can set the range within which you wish your floating point to lie e.g. import random print("The seed is based on the computer's time:") x=random.random() print(x) y=random.randint(1,10) print(y) a=random.uniform(1,10) print(a) print() print("Now we define the seed:") random.seed(a=17890) z=random.randint(1,100) print(z) b=random.uniform(1,100) print(b) # output 1: The seed is based on the computer's time: 0.977253666645795 10 7.27955872973289 Now we define the seed: 72 18.147387384227255 # output 2: The seed is based on the computer's time: 0.6810337671737534 6 6.396692582785202 Now we define the seed: 72 18.147387384227255 # output 3: The seed is based on the computer's time: 0.7625323849936642 8 7.069848612300595 Now we define the seed: 72 18.147387384227255

The break command

1. special Python command that can be used to immediately end a loop 2. it ends the current repetition structure, but does not end the program which picks up at the line directly after the end of your loop 3. it IMMEDIATELY terminates the current loop, which means statements in the block that appear after the break command will not be run on the iteration that the loop breaks

Variables

1. store information in your computer's memory 2. the '=' symbol used when creating variables is called the 'assignment operator' and causes Python to store the data on the right side of the statement into the variable name printed on the left side 3. cannot use one of Python's reserved words as a variable name 4. variables cannot contain spaces, use underscore instead, also cannot contain special characters 5. first character of a variable name has to be either a letter (upper or lower case) or the underscore character, after that the characters can be underscore, letter, OR number 6. Python is case sensitive 7. It's possible to set the value of multiple variables on the same line. For example: x, y, z = 'a', 'b', 'c' 8. You can also assign the same value to multiple variables at the same time by doing the following: # a, b and c will all contain the integer 100 a = b = c = 100

Pocessing

A series of mathematical or logical processes that are applied to the input

Algorithms

A series of well-defined, logical steps that must be taken in order to perform a task. They serve as a necessary intermediate step between understanding the task at hand and translating it into computer code.

String repetition

Multiply a string by an integer value to produce a larger string (will not be separated by spaces leave a space at the end of the string literal before the last delimiter)

The Format Function: Formatting Percentages

e.g. a = 0.52 print (format(a, '%')) print (format(a, '.2%')) print (format(a, '.0%')) 52.000000% 52.00% 52%

The Format Function: Formatting Integers

e.g. a=20000 print(format(a,">20,d")) # output: 20,000

Time module

time.time: returns back time in seconds since the "epoch" as a floating point number, takes no parameters; i.e. time.time(); it will increase with each running of the program unless your computer's clock is set backward for some reason


Set pelajaran terkait

Anatomy Chapter 13 Surface Anatomy

View Set

MKT Exam 4, mktg ch 15, Chapter 2, MKT321_CH20, MKT 350 Test 4, Mktg 351 Test 3 Ch 20, MKTG 3, Marketing Segmentation, Chap 19 Practice Questions, MKT 350 quiz 4, Ch. 12 marketing, MKTG 330: Chapter 14 Quiz, marketing test 3 ch 16, chapter 11marketin...

View Set

History - Chapter 13 Checkup and Continent Study 3 - For Cumulative Test 12 (5th Grade)

View Set

AWS Solutions Architect Associate

View Set

Orion Series 65 - Exam 3 Quick Quizzes

View Set

Ch 5: NJ laws, rules, regulations

View Set

RE Course Section 4: Agency in Michigan

View Set

MFT Clinical questions to review

View Set