Chapter 2 Flashcards
What are the 5 phases of the program development cycle?
- Design the Program: Creating a design of the program before writing any code
- Write the Code: writing the code in a high-level language
- Correct Syntax Errors: compiler or interpreter will display error message to be fixed
- Test the Program: Once code is in executable form, it is tested for logic errors (mistake that compiles but produces incorrect results (ex mathematics are off)
- Correct Logic Errors: Programmer debugs the logic errors. If program must be redesigned, the process starts over again
What two steps summarize the process of designing a program?
- Understand the task that the program is to perform
- It is important to interview or discuss with the customer what it is that the program is supposed to do.
- Programmer creates a list of software requirements (tasks the program must perform) based on this gathered info - Determine the steps that must be taken to perform the task
- Programmer breaks down the task into an algorithm (list of logical steps that must be completed in order)
- Programmers use pseudocode and flowcharts to help organize these algorithms/steps
What is pseudocode?
- An informal language that has no syntax rules and is not meant to be compiled or executed.
- Pseudocode is used to create models, or “mock-ups,” of programs.
- Allows programmers to not have to worry about syntax errors during mockup
What is a flowchart?
- A diagram that graphically depicts the steps that take place in a program.
- There are three different symbols:
- Ovals: top and bottom of flowchart (start/end)
- Parallelograms: Input and output symbols
- Rectangles: processing symbols, like mathematical calculations
Computer programs typically perform the three-step process:
- Input is received. (any data that the program receives while it is running)
- Some process is performed on the input. (ex mathematical calculation)
- Output is produced. (this is the result of the program that is outputted)
What is a function? What are some function examples in python?
- A piece of prewritten code that performs an operation.
- Ex: print(‘hello world’) function displays the output onto the screen
What does calling a function mean?
When programmers execute a function, they refer to it as calling a function
What is an argument?
Data that you want to be displayed on the screen (items in the parenthesis)
What is a string?
A sequence of characters that is used as data in a program
-Ex: ‘Name’
‘address’
‘profession’
What is a string literal?
When a string appears in the actual code of a program
-String literals are contained in single quotation marks
How do you use apostraphes or quotes with the print function?
- Use double quotation marks
- Ex: print(“I’m Jake”)
How do you display “ in the display?
-Use triple quotations to display “
-Ex: print(“"”I said “Hello”. “””)
-Triple quotes can also be used to surround multiline strings, something for which single and double quotes cannot be used
-Ex:
print(“"”One
Two
Three”””)
What are comments? How is it displayed in Python?
- Comments are short notes placed in different parts of a program, explaining how those parts of the program work
- Comments are displayed with # character
- Ex: # This is a comment
What is an end-line comment?
-A comment that appears at the end of a line of code
-Ex:
1 print(‘Kate Austen’) # Display the name.
What is a variable?
- A name that represents a value in the computer’s memory.
- Use an assignment statement to create a variable and make it reference a piece of data.
- Ex: age=25
- Variable is the name of a variable and expression is a value, or any piece of code that results in a value.
- When passing a variable into a print function, do not use quotation marks
What is an input function?
-Reads input that the user inputs from the keyboard
-Ex: variable=input(prompt)
name = input(‘What is your name?’)
1 # Get the user’s first name.
2 first_name = input(‘Enter your first name: ‘)
3
4 # Get the user’s last name.
5 last_name = input(‘Enter your last name: ‘)
6
7 # Print a greeting to the user.
How would you print the first_name and last_name inputs?
print(‘Hello’, first_name, last_name)
The input function always returns the user’s input as a string, even if the user enters numeric data. What function can you use to convert a string to a numeric type?
-int(item) : You pass an argument to the int() function and it returns the argument’s value converted to an int.
-float(item): You pass an argument to the float() function and it returns the argument’s value converted to a float.
-Best line of code for this:
hours = int(input(‘How many hours did you work? ‘))
What is an exception?
- An unexpected error that occurs while a program is running, causing the program to halt if the error is not properly dealt with.
- Ex; int and float function does not contain a valid numeric value
What are math operators and give some examples of them in Python?
Tools for performing mathematical calculations
-Ex: Addition +, Subtraction -, Multiplication *, Division /, Exponents **, Integer division //
What is an operand?
Values to the left and the right of operators
-Ex: 12+2 (12 and 2 are operands)
How to enter a percent value in Python?
Multiply by the decimal version
-Ex: 20% discount is 0.2 times the original price of the item. Then doing the original price-discount amount=New price of item
Give an example of the use of / operator vs // operator:
5/2=2.5
5//2=2 (whole integer)
-When the result is positive, it is truncated, which means that its fractional part is thrown away.
-When the result is negative, it is rounded away from zero to the nearest integer.
(-5)//2=-3
What does % do?
Remainder operator: Instead of returning the quotient, it returns the remainder
- leftover = 17 % 3=2
- When an operation is performed on two ___ values, the result will be an int.
- When an operation is performed on two _____ values, the result will be a float.
- When an operation is performed on an int and a float, the ____ value will be temporarily converted to a ____ and the result of the operation will be a float. (An expression that uses operands of different data types is called a mixed-type expression.)
- int
- float
- int, float
Explain how an int value gets converted to a float with this expressoin:
my_number = 5 * 2.0
When this statement executes, the value 5 will be converted to a float (5.0) then multiplied by 2.0. The result, 10.0, will be assigned to my_number.
fvalue = −2.9
ivalue = int(fvalue)
What is the value of ivalue?
-2
ivalue = 2
fvalue = float(ivalue)
What is the value of fvalue?
2.0
What is the line continuation character and how is it used?
- Allows you to break a statement into multiple lines
-Use a backslash () to do this
Ex:
result = var1 * 2 + var2 * 3 + \
var3 * 4 + var4 * 5
What is a concantenation?
To append one string to the end of another string.
-In Python, this is done with + operator
Ex:
»_space;> message = ‘Hello ‘ + ‘world’ [Enter]
»_space;> print(message) [Enter]
Hello world
»_space;>
> > > my_str = ‘one’ ‘two’ ‘three’
print(my_str)
-What will this code print?
onetwothree
What does argument end=’ ‘ do?
Used for when you do not want the print function to start a new line of output when it finishes displaying its output
p
print(‘One’, end=’ ‘)
print(‘Two’, end=’ ‘)
print(‘Three’)
What does this code do?
OneTwoThree
What does sep=’ ‘ do?
Eliminates space between items Ex: >>> print('One', 'Two', 'Three', sep='') [Enter] OneTwoThree >>>
> > > print(‘One’, ‘Two’, ‘Three’, sep=’*’) [Enter]What does this output?
OneTwoThree
What is an escape character?
-A special character that is preceded with a backslash (\), appearing inside a string literal Ex: print('One\nTwo\nThree') Result: One Two Three
What do the following do? /n /t /' /" //
/n: Output advanced to next line /t: Output skips over to next horizontal tab position /': Single quote mark printed /": double quote mark printed //: backslash character printed
Note: / and // can be used as quotation marks when using print function
/ can be used to print a backslash
What is a formatted string literal-
-An f-string is a string literal that is enclosed in quotation marks and prefixed with the letter f.
-Ex:
»> print(f’Hello world’) [Enter]
Hello world
-Can be used to contain placeholders for variables and other expressions
-Ex:
»> name = ‘Johnny’ [Enter]
»_space;> print(f’Hello {name}.’) [Enter]
Hello Johnny.
-Note: You can concatenate multiple f strings together with +
What is the output of the following program:
|»_space;> print(f’The value is {10 + 2}.’) [Enter]
The value is 12.
What is a format specifier?
-Can be included inside of a placeholder in an f-string to format the placeholder.
-Ex: Rounding a value to a specific decimal places
-Written as follows:
{placeholder:format-specifier}
Provide an example of a format specifier:
{monthly_payment:.2f}
-The .2f is a precision designator that indicates the number should be rounded to two decimal places. The letter f is a type designator, and it indicates that the value should be displayed with a fixed number of digits after the decimal point.
-
What do the following format specifiers do? \:2f \:, \:% \:e \:d \:10 (or any number) \:< \:> \:^
:2f Rounds to the nearest amount of decimal places
:, Adds commas to numbers such as 1,300,200
:% Formats floating point number as percentage
:e Displays number in scientific notation
:d indicates value should be displayed as a decimal integer
:10 displays minimum number of spaces to display the value
:< Left-aligns the value
:> Right-aligns the value
:^ Center-aligns the value
What order should you write format specifiers in?
[alignment][width][,][.precision][type]
print(f’{number:^10,.2f}’)
What is a magic number?
An unexplained value that appears in the program’s code
What is a named constant?
-a name that represents a special value
Ex: INTEREST_RATE = 0.069
-Makes program easier to understand and makes modifying program easier
What is the first step to using Python’s turtle?
import turtle
What does this do?
»> import turtle
»_space;> turtle.showturtle()
Imports turtle and makes it visible
What does this do? >>> import turtle >>> turtle.forward(200) >>> turtle.right(90) >>> turtle.forward(200) >>>
- Moves turtle forward 200 pixels
- Turns turtle right 90 degrees
- Moves turtle forward 200 pixels
What does this do?
turtle.setheading(angle)
Sets the turtle’s heading to a specific angle
What does this do?
turtle.heading()
Displays turtle’s current heading
What does the turtle.penup() and turtle.pendown() commands do?
Raises and lowers turtle pen so you can move him without drawing a line
What does this do?
turtle.circle(radius)
Draws a circle of a certain radius
turtle.dot()
Turtle draws a simple dot
turtle.pensize(width)
Changes the turtle’s pensize
turtle.pencolor(color)
Changes turtle’s pen colors
turtle.reset()
all drawings that currently appear in the graphics window, resets the drawing color to black, and resets the turtle to its original position in the center of the screen.
turtle.clear()
erases all drawings that currently appear in the graphics window. It does not change the turtle’s position, the drawing color, or the graphics window’s background color.
turtle.clearscreen()
erases all drawings that currently appear in the graphics window, resets the drawing color to black, reset the graphics window’s background color to white, and resets the turtle to its original position in the center of the graphics window.
turtle.setup(width, height)
Specifies size of graphics window
turtle.goto(x, y)
Makes turtle go to certain point on coordinate pane, almost like a unit circle plane.
turtle.pos()
Displays turtle’s current position
turtle.speed(speed)
Sets turtles speed from range of 0-10
turtle. hideturtle()
turtle. showturtle()
Hides or shows turtle graphic but still draws what you prompted it to
turtle.write(text)
Displays text in graphics window
turtle. begin_fill()
turtle. end_fill()
- Turtle fills a shape with a color
- When turtle end fill is executed, the shape fills with the color
- Note: If you fill a shape that is not enclosed, the shape will be filled as if you had drawn a line connecting the starting point with the ending point.
turtle.numinput
- get numeric input from the user and assign it to a variable
- displays a small graphical window known as a dialog box. The dialog box provides an area for the user to type input, as well as an OK button and a Cancel button.
- variable = turtle.numinput(title, prompt)
- Title is whatever the user will see (such as “enter a radius”, then prompt is the value the user enters and is stored as a variable
variable = turtle.numinput(title, prompt, default=x, minval=y, maxval=z)
-Give an example of how this might be used
num = turtle.numinput(‘Input Needed’, ‘Enter a value in the range 1-10’, default=5, minval=1, maxval=10)
turtle.textinput
-Gets string input from a user
variable = turtle.textinput(title, prompt)
turtle.done()
If graphics window disappears after turtle is done drawing, add this command to ensure it doesn’t disappear
-If using IDLE, this is not necessary