Programming ZyBooks1
Programming ZyBooks1
Some answers involve typing text like x + 1 or a number like 20. The tool that checks correctness uses
Extremely fast clicking through activities, always clicking "Show answer" before answering, or first
text matching (rather than expression evaluation) to enable convenient use on various platforms with
typing bogus answers, are easily detectable. Most students really try the activities, which are designed
varying Internet access. Supporting all possible (non-standard) answers isn't usually practical. Following
to help. Feedback is excellent, and research shows students learn from such activities (research
instructions carefully helps. If a student thinks an answer is correct but isn't being accepted, the student
summaries). About 90% of students earnestly attempt the PA's, realizing PA's are effective and respect
can just click "Show answer".
student time (SIGCSE 2017 paper).
PARTICIPATION
ACTIVITY
1.1.1: Participation activities. Viewing PA completion in a section
If you are completing zyBook activities in another browser tab, you may have to reload the Home/TOC
page to see updated activity completion.
PARTICIPATION
ACTIVITY
1.1.2: PA completion.
Students can also check section-level activity completion status at a zyBook's "Home/TOC", which is
accessed from within a zyBook by clicking the zyBook's name at the top.
3) Within a section, a student can quickly Figure 1.1.4: Feedback buttons appear throughout the material.
detect if an activity is not fully
completed by _____ .
looking for unfilled icons next to
each activity
contacting support
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Returning to a section: Previous answers intentionally aren't shown
When a student leaves and then returns to a section, the system intentionally does not show previous
answers to learning questions. That way, students can redo a section to help better learn the material.
Research shows that approach is better for learning (one article discussing such research).
The completion icons on the side remain filled in, though, so students can know what PA's have already
been completed.
PARTICIPATION
ACTIVITY
1.1.3: zyBook question answers.
selecting "My feedback describes a possible content or technical error" when submitting feedback. Your
feedback then goes straight to our support team as a "support ticket". The team typically responds
within a day (usually in less than an hour, especially during California working hours), and often fixes
issues in the live zyBook right away.
If answered incorrectly, the correct answer and possibly an explanation are shown. Clicking "Next"
generates a new question of the same difficulty for that level. Students may attempt questions at each
Check Show answer level as many times as needed.
Different types of CAs exist. A particular zyBook may have one type of CA, different types of CAs, or no
CAs at all.
Some zyBooks include progression challenge activities that consist of a series of auto-generated
questions, each progressively more difficult. Students must correctly ©zyBooks
answer a 02/27/24
question20:03
at each level
1927475 ©zyBooks 02/27/24 20:03 1927475
Danielappears,
before proceeding to the next higher level. If answered correctly, a green checkmark Reyes usually Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Completion of progression challenge activities can be viewed by filled-in levels, as well as the filled-in
along with an explanation. Clicking "Next" proceeds to the next higher level.
icons next to the activity. If a student leaves the page and returns, the completed levels remain filled.
Such an incremental approach represents a "structured adaptivity" approach used in zyBooks, teaching
specific concepts in an incremental manner to help students progress.
Figure 1.2.3: Activity completed shown by filled-in level and icons next to
the activity.
Figure 1.2.1: Progression challenge activities: Proceeding to next level.
1 2 3 4 5 6 7
Check Next
In a zyBook, a participation activity (PA) is an activity used in the initial learning of a topic. Anyone can
get all PA points just by participating (hence the name). In contrast, a Challenge activity (CA) is the
zyBook version of a homework problem. A CA allows students to apply and practice what they've
learned. Students must eventually get a CA right on their own to get points, and thus CAs serve as a
lightweight assessment for instructors as well.
Students may click on any previously-completed level to do more problems for extra practice. Such Different types of CAs exist. A particular zyBook may have one type of CA, different types of CAs, or no
practice is useful to build confidence, study for an exam, etc. For students, clicking on a level beyond the CAs at all.
next uncompleted level yields an error message (instructors may jump to any level, however); each level
typically builds on earlier levels, so earlier levels must be completed first. Programming challenge activities
PARTICIPATION
1.2.1: Progression challenge activities. Some zyBooks (C, C++, Java, Python, etc.) may include programming "challenge activities" that ask a
ACTIVITY
student to type a code portion of a program into a text box. Such activities are auto-graded, by
compiling and running the program with various test cases.
1) If a user has previously completed
questions for level 1, 2, and 3, the user Replace /* Your solution goes here */ (or '''Your solution goes here''') with
may jump to question level 4. your code.
True The surrounding sample program's code is NOT editable.
False
550678.3854950.qx3zqy7
Start
Ex: 2
x7 x3 = x
A programming challenge activity appears at this section's end. The activity uses C++, but the lesson
applies to C, C++, Java, Python, etc.
After clicking "Run", the program is automatically tested with various values that may differ from what
appears in the sample program, to ensure the student's code properly solved the problem.
The result of each test case is shown below the "Run" button. If all test cases are passed, a green
If any of the test cases did not pass, the expected output (or value) is shown along with the actual
checkmark appears with the message "All tests passed".
output produced by your code.
If the program's output differs from the expected output in the whitespace characters, such as tabs and
Figure 1.3.2: Sample C++ programming challenge activity: Passed all test newlines, the differences will be highlighted in yellow.
cases.
Figure 1.3.3: Sample C++ challenge homework activity: Failed test cases.
Like other zyBook activities, programming challenge activities are primarily for learning and not testing.
However, programming challenge activities do not reveal answers to students, to challenge the student.
Students (and some instructors) sometimes ask that our system provide solutions to students, but
many instructors ask us not to provide such solutions, because much learning occurs in a student's
attempts to solve the problem. Of course, sometimes students just get stuck, in which case students are
encouraged to utilize their class' help resources, whatever those may be: discussion board, office hours,
classmates (if allowed), email to instructors, etc.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
Note that our system may introduce minor version changes to such activities. Version differences are
CS119-2402A-06-2402A CS119-2402A-06-2402A
quite hard for a student to notice, but analysis can easily detect that an answer was copied from a
different version.
Programming challenge activities are scored as 2 points. (Note: The MATLAB programming challenge
activities differ slightly and are explained in the MATLAB zyBook). One point is awarded for passing the
first test case. The second point is awarded for passing all the remaining test cases. The number of test
cases may differ for each programming challenge activity. Completion of programming challenge
activities can be viewed by the filled-in icons next to each activity.
Certain whitespace characters, such as a newline or tab, that are in the student's output but are not in
the expected output, will be shown using special arrow symbols.
Figure 1.3.4: Newlines and tabs are shown using special arrow symbols.
Beginning students sometimes don't understand that the system may change values to test the
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes student's code. Below, the student was supposed to output the variable wage, but instead
Daniel Reyesoutput 20.
CS119-2402A-06-2402A The first test case passes, because wage happened to be 20. But then the CS119-2402A-06-2402A
system, behind the scenes,
changes wage = 20 to wage = 30 in the program, and then reruns the program a second time. Because
the student "hardcoded" 20 rather than outputting wage as instructed, the student's program produces
incorrect output.
PARTICIPATION
ACTIVITY 1.3.1: Programming challenge activities.
Figure 1.3.7: Passing test cases by correctly outputting a variable.
1) Only type the program portion to
replace the /* Your solution goes here */
portion.
True
False
Program end never reached (commonly due to an infinite loop or infinite recursion).
The user's code may be run with various test cases. If one of those test cases causes the program to
exit, the above message is printed. For example, a user may write an infinite loop, such as
while (x = 1) ... (the user used = instead of ==, a common error in C, C++, and Java). In such a
case, the system will stop running the program after a few seconds. Or, the user may access an invalid
array/vector index, as in myArray[i] = 99 , where i is 10 but myArray ©zyBooks 02/27/24
is size 20:03
10 so only 1927475
has valid ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
indices 0..9 (another common error). In such a case, the program may terminate immediately.
CS119-2402A-06-2402A CS119-2402A-06-2402A
The way the programming challenge activities currently work, the test case that causes the program to
fail does not get printed. For some activities where such errors are common, the activity's instructions
may indicate the test cases. Whether such test cases are provided or not, the user should carefully
examine the code for possible errors.
Students will sometimes submit feedback indicating that the user's program ran fine in a separate
environment but fails in the zyBook's environment. "Running fine" depends on what test cases are used.
Often, the problem lies in the program not correctly executing for a particular set of test cases.
Students sometimes complain that the activity is reporting a compiler error on a line number the
student cannot edit. Students should note that the actual error often exists before the reported line
number; the compiler may not notice the error until reaching a later line, such as when a semicolon is
missing.
Figure 1.3.8: Error appears on line 7, but the compiler reports the error on
line 9.
PARTICIPATION
ACTIVITY 1.3.2: Program end never reached.
1) An auto-grader runs a program on an The student MUST pre-enter any required input. Otherwise, the program will run but may produce no
instructor's test cases, thus providing output, or produce erroneous output.
immediate feedback as to the
correctness of a program.
Figure 1.4.1: zyLab with programming window.
True
False
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
2) zyLab assignments are created and Daniel Reyes Daniel Reyes
controlled by zyBooks staff. CS119-2402A-06-2402A CS119-2402A-06-2402A
True
False
A student can run their program as many times as desired while in develop mode, testing the program
on different input values.
3) If the student does not pre-enter input ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
values but a program expects input, Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
strange behavior may occur.
True PARTICIPATION
ACTIVITY
1.4.3: Uploading program files.
False
Figure 1.4.3: Filenames must match exactly. If an assignment is configured to upload program files, once all files have been uploaded correctly, the
"Submit for grading" button highlights.
In either case, pressing the "Submit for grading" button compiles and runs the program on the
instructor's test cases. The test cases are listed, with an indication of which cases passed, and points
are awarded for each passed test case (as determined by the instructor).
When an instructor runs a grade report, the student's highest grade in the specified time window is
reported. Thus, if a student submitted five times with scores of 3, 5, 9, 7, 7, the student's score is 9.
Thus, students need not worry about receiving a lower score by trying to improve their program; their
highest score in the time window is reported to the instructor. ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Figure 1.4.4: Submitted and graded lab: No test cases passed.
Instructors can configure a lab to allow a maximum number of submissions, or to accept the next
submission only after some number of minutes, to help students think carefully about their program
before submitting (thus not turning programming into a guessing game -- "Let's see if making this
change gets me more points.").
Instructors can choose to hide the details of a test case from students, so that students think carefully
about why a program might not be correct (thus not over-relying on the auto-grader to do all the thinking
for them).
PARTICIPATION
ACTIVITY
1.4.4: Submitting for grading.
4) An instructor can hide details of a test ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
case from students. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
True
False
A "Compare output" test compares the student program's output vs. the expected output as specified by
1) If a test case requires output to exactly
an instructor. If differences cause the test case to not be passed, differences are highlighted. Tab and
newline characters (normally invisible) are shown using arrow symbols. match "Hello there", then the output
"Hello there!" will match.
True
Figure 1.4.6: Whitespace characters are shown as control characters.
False
If a program outputs an invalid character (typically due to a nasty bug), a "control character" is shown,
such as a diamond symbol with a question mark (but other control characters may appear).
4) If a student's program outputs a compares the function's return value against the expected value.
diamond with a question mark inside,
but the student didn't write such an
output statement, then the zyLabs Figure 1.4.9: Unit tests: One passed and one failed unit test.
platform probably has a bug.
True
False ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Students sometimes get confused when a program's example text has interleaved output and input.
Students sometimes try to output the input values, to match the example text. Students should note
that ONLY the output values should be output by the student's program.
Instructors may wish to limit the amount of "prompting" to reduce this common source of confusion,
which exists for any auto-grading system.
Figure 1.4.8: Student programs should only output the output, and not also
output the input to match example text.
Miscellaneous
zyLabs doesn't close submissions based on time or date, instead allowing students to continue to
practice and improve their code. However, an instructor is able to view submissions recorded before a
specified due date and time. Therefore, later attempts may not be counted if beyond the specified due
date.
You can view up to 5 of your previous lab submissions. Each previous submission details the number of
points received and which tests passed and failed. Previously submitted code can also be downloaded.
PARTICIPATION
Figure 1.4.10: Previous submissions.
ACTIVITY 1.4.6: Compare output tests and interleaved input / output.
Unit test
For programs with functions (called "methods" in Java), a unit test may be used to verify that the
function returns the correct value. A unit test calls a function, independent of the main code, and
The Python interpreter is a computer program that executes code written in the Python programming Prompt Code Line Interpreter
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
language. An interactive interpreter is a program that allows the user to executeDaniel
one line of code at a
Reyes Daniel Reyes
time. CS119-2402A-06-2402A CS119-2402A-06-2402A
Code is a common word for the textual representation of a program (and hence programming is also A program that executes computer
called coding). A line is a row of text. code.
The interactive interpreter displays a prompt (">>>") that indicates the interpreter is ready to accept The text that represents a computer
code. The user types a line of Python code and presses the enter key to instruct the interpreter to program.
execute the code. Initially you may think of the interactive interpreter as a powerful calculator. The
example program below calculates a salary based on a given hourly wage, the number of hours worked Informs the programmer that the
per week, and the number of weeks per year. The specifics of the code are described elsewhere in the interpreter is ready to accept
chapter. commands.
PARTICIPATION
1.5.1: The Python interpreter. A row of text.
ACTIVITY
Reset
Many code editors color certain words, as in the below program, to assist a human reader in 3) How are most Python programs
understanding various words' roles. developed?
Writing code in the interactive
PARTICIPATION
ACTIVITY
1.5.3: Executing a simple Python program. interpreter.
Writing code in files.
PARTICIPATION
ACTIVITY 1.5.4: Python basics.
PARTICIPATION
ACTIVITY
1.6.2: Basic text output.
1
2 ''' Your solution goes here '''
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 35/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 36/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
g
3
Run
Each call to print() outputs on a new line. However, sometimes a programmer may want to keep
Run output on the same line. A programmer can add end=' ' inside of print() to keep the output of a
subsequent print statement on the same line separated by a single space. Ex:
View your last submission keyboard_arrow_down print('Hello', end=' ').
CHALLENGE
ACTIVITY 1.6.2: Output an eight with asterisks. Figure 1.6.2: Printing text on the same row.
Output the following figure with asterisks. Do not add spaces after the last character in each # Including end=' ' keeps output on same
line. line
print('Hello there.', end=' ') Hello there. My name is....
print('My name is....', end=' ') Carl?
***** print('Carl?')
* *
*****
* *
*****
PARTICIPATION
Note: Whitespace (blank spaces / blank lines) matters; make sure your whitespace exactly ACTIVITY
1.6.3: Printing text on the same row.
matches the expected output.
1) Which pair of statements print output
on the same line?
Learn how our autograder works print('Halt!')
550678.3854950.qx3zqy7
print('No access!')
1 ©zyBooks 02/27/24 20:03 1927475 print('Halt!', end=' ') ©zyBooks 02/27/24 20:03 1927475
2 ''' Your solution goes here ''' Daniel Reyes print('No access!') Daniel Reyes
3 CS119-2402A-06-2402A CS119-2402A-06-2402A
print(Halt!, end=' ')
print(No Access!, end=' ')
Newline characters
PARTICIPATION
ACTIVITY
1.6.4: Basic variable output. Output can be moved to the next line by printing "\n", known as a newline character. Ex:
print('1\n2\n3') prints "1" on the first line, "2" on the second line, and "3" on the third line of output.
1) Given the variable num_cars = 9, which "\n" consists of two characters, \ and n, but together are considered by the Python interpreter as a
statement prints 9? single character.
print(num_cars)
print("num_cars") Figure 1.6.5: Printing using newline characters.
PARTICIPATION 1
ACTIVITY 1.6.5: Basic variable output. print('1\n2\n3') 2
3
print() always adds a newline character after the output automatically to move the next output to the
Check Show answer next row, unless end=' ' is provided to replace the newline character with a space (or some other
character). An empty print() can be used to print only a newline.
Outputting multiple items with one statement Figure 1.6.6: printing without text.
Programmers commonly try to use a single print statement for each line of output by combining the
printing of text, variable values, and new lines. A programmer can simply separate the items with print('123') 123
©zyBooks 02/27/24 20:03 variables,
1927475 print() ©zyBooks 02/27/24 20:03 1927475
commas, and each item in the output will be separated by a space. Combining string literals, print('abc')
Daniel Reyes abc Daniel Reyes
and new lines can improve program readability, because the program's code corresponds more
CS119-2402A-06-2402A
closely
CS119-2402A-06-2402A
to the program's printed output.
NOTE: In a normal programming environment, program input is provided interactively and completed by
pressing the enter key. The enter key press would insert a newline. Since zyBooks input is pre-entered,
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 39/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 40/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
no enter key press can be inferred. Thus, activities that require pre-entered input may need extra newline
characters or blank print statements in zyBooks, compared to other environments. 1.7 Basic input
PARTICIPATION
1.6.6: Output simulator.
ACTIVITY
Basic input
The tool below allows for experimenting with print statements. The variables Many useful programs allow a user to enter values, such as typing a number, a name, etc.
country_population = 1344130000 and country_name =©zyBooks 'China' 02/27/24 20:03 1927475
have been ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Reading input is achieved using the input() function. The statement best_friend input() will
Daniel=Reyes
defined and can be used in the simulator. CS119-2402A-06-2402A CS119-2402A-06-2402A
read text entered by the user and the best_friend variable is assigned with the entered text. The function
Try printing the following output: input() causes the interpreter to wait until the user has entered some text and has pushed the return
The population of China was 1344130000 in 2011.
key.
The input obtained by input() is any text that a user typed, including numbers, letters, or special
characters like # or @. Such text in a computer program is called a string.
print(
A string simply represents a sequence of characters. For example, the string 'Hello' consists of the
'Change this string!' ) characters 'H', 'e', 'l', 'l', and 'o'. Similarly, the string '123' consists of the characters '1', '2', and '3'.
PARTICIPATION
Change this string! 1.7.1: A program can get an input value from the keyboard.
ACTIVITY
PARTICIPATION
ACTIVITY
1.6.7: Single print statement.
PARTICIPATION
ACTIVITY 1.7.2: Reading user input.
The string '123' (with quotes) is fundamentally different from the integer 123 (without quotes). The '123' Check Show answer
string is a sequence of the characters '1', '2', and '3' arranged in a certain order, whereas 123 represents
the integer value one-hundred twenty-three. Strings and integers are each an example of a type; a type 2) Complete the code so that new_var
determines how a value can behave. For example, integers can be divided by 2, but not strings (what is equal to the entered number plus
sense would "Hello" / 2 make?). Types are discussed in detail later on. 5.
Reading from input always results in a string type. However, often a programmer wants to read in an my_var = int(input())
new_var =
integer, and then use that number in a calculation. If a string contains only numbers, like '123', then the
int() function can be used to convert that string to the integer 123.
Check Show answer
A programmer can combine input() and int() to read in a string from the user and then convert that
string to an integer for use in a calculation.
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 43/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 44/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
©zyBooks 02/27/24 20:03 1927475 Note: Our system automatically runs your program several times, trying different
©zyBooks input20:03
02/27/24 values
1927475
Daniel Reyes each time to ensure your program works for any values. Notes on how to solve Daniel
this.Reyes
See How
CS119-2402A-06-2402A CS119-2402A-06-2402A
to Use zyBooks for info on how our automated program grader works.
NOTE: The below tool requires input to be pre-entered. This is a current limitation of the web-based tool
and atypical of conventional Python environments, where users enter input as the program runs. For Learn how our autograder works
conventional behavior, you may copy-paste the program into a local environment, such as IDLE. 550678.3854950.qx3zqy7
1
2 ''' Your solution goes here '''
zyDE 1.7.1: Basic input. 3
Run the program and observe the output. Change the input box value
from 3 to another number, and run again.
3
Load default template...
1 dog_years = int(input('Enter
2 print() Run
3
4 human_years = 7 * dog_years
5
6 print(dog_years, 'dog years i
7 print (human_years, 'human ye
8
Run
CHALLENGE
ACTIVITY
1.7.2: Read user input and print to output.
Read three integers from user input without a prompt. Then, print the product of those
©zyBooks 02/27/24 20:03 1927475 integers. Ex: If input is 2 3 5, output is 30. Note: Our system will run ©zyBooks
your program several
02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A
times, automatically providing different input values each time, to ensureCS119-2402A-06-2402A
your program works
CHALLENGE
1.7.1: Read user input numbers and perform a calculation. for any input values.
ACTIVITY
1
2 ''' Your solution goes here '''
3
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 45/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 46/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
PARTICIPATION
Run ACTIVITY 1.8.1: Syntax errors.
View your last submission keyboard_arrow_down Find the syntax errors. Assume variable num_dogs exists.
1) print(num_dogs).
Error
PARTICIPATION
ACTIVITY
1.8.2: Common syntax errors.
The Python interpreter is able to detect syntax errors when the program is initially loaded, prior to
Good coding practice actually executing any of the statements in the code. However, just because the program loads and
executes does not mean that the program is correct. The program may have another kind of error called
New programmers will commonly write programs with many syntax errors, leading to many frustrating a runtime error, wherein a program's syntax is correct but the program attempts an impossible
error messages. To avoid continually encountering error messages, a good practice is to execute the operation, such as dividing by zero or multiplying strings together (like 'Hello' * 'ABC').
code frequently, writing perhaps a few (3–5) lines of code and then fixing errors, then writing a few more A runtime error halts the execution of the program. Abrupt and unintended termination of a program is
lines and running again and fixing errors, and so on. Experienced programmers may write more lines of often called a crash of the program.
code each time, but typically still run and test syntax frequently.
©zyBooks 02/27/24 20:03 1927475 Consider the below program that begins executing, prints the salary, and then waits
©zyBooks for the
02/27/24 user
20:03 to enter
1927475
Daniel Reyes Daniel Reyes
PARTICIPATION CS119-2402A-06-2402A
an integer value. The int() statement expects a number to be entered, but gets the text 'Henry'
CS119-2402A-06-2402A
instead.
ACTIVITY 1.8.3: Run code frequently to avoid many errors.
stmt1 stmt1
The program crashes because the user enters 'Henry' instead of an integer value.
stmt2 stmt2
stmt3 stmt3
day_of_the_week = Friday
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A print('Today is Monday") CS119-2402A-06-2402A
Runtime errors are categorized into types that describe the sort of error that has occurred. Above, a
ValueError occurred, indicating that the wrong sort of value was passed into the int() function. Other Reset
examples include a NameError and a TypeError, both described in the table below.
Some errors may be subtle enough to silently misbehave, instead of causing a runtime error and a
Table 1.8.1: Common error types. crash. An example might be if a programmer accidentally typed "2 * 4" rather than "2 * 40" – the
program would load correctly, but would not behave as intended. Such an error is known as a logic
error, because the program is logically flawed. A logic error is often called a bug.
Error type Description
SyntaxError The program contains invalid code that cannot be understood. Figure 1.8.3: The programmer made a mistake that happens to be correct
syntax, but has a different meaning.
IndentationError The lines of the program are not properly indented.
ValueError An invalid value is used – can occur if giving letters to int(). The below program attempts to calculate a 5% raise for an employee's salary. The
programmer made a mistake by assigning raise_percentage with 5, instead of 0.05, thus
NameError The program tries to use a variable that does not exist.
giving a happy employee a 500% raise.
An operation uses incorrect types – can occur if adding an integer to a
TypeError current_salary = int(input('Enter current salary:'))
string.
raise_percentage = 5 # Logic error gives a 500% raise Enter current salary:
instead of 5%. 10000
new_salary = current_salary + (current_salary * New salary: 60000
raise_percentage)
print('New salary:', new_salary)
PARTICIPATION
ACTIVITY
1.8.5: Match the lines of code with the error type that they produce.
zyDE 1.8.1: Fix the bug. Retype the statements, correcting the syntax error in each print statement.
Click run to execute the program and note the incorrect program output. print('Predictions are hard.")
Fix the bug in the program. print(Especially about the future.)
user_num = 5
Load default template... Run print('user_num is:' user_num)
CHALLENGE Code development is usually done with an integrated development environment, or IDE. There are
1.8.1: Basic syntax errors.
ACTIVITY various IDEs that can be found online; some of the most popular are listed below.
IDLE is the official Python IDE that is distributed with the installation of Python from 2) Python code can be written in a simple
https://python.org. IDLE provides a basic environment for editing and running programs. text editor, such as Notepad (Windows).
PyDev (http://pydev.org) is a plugin for the popular Eclipse program. PyDev includes extra features True
such as code completion, spell checking, and a debugger that can be useful tools while
programming. False
For learning purposes, web-based tools like CodePad (http://www.codepad.org) or Repl
(http://www.repl.it) are useful.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
There are many other editors available—some of which are free, while others
Daniel Reyes
require a fee or
CS119-2402A-06-2402A 1.10 Python example: Salary calculation
Daniel Reyes
CS119-2402A-06-2402A
subscription. Finding the right IDE is sometimes like finding a pair of jeans that fits just right—try a
Google search for "Python IDE" and explore the options. This section contains a very basic example for starters; the examples increase in size and complexity in
later sections.
1 hourly_wage = 20
2
3 print('Annual salary is: ')
4 print(hourly_wage * 40 * 50)
5 print()
6
7 print('Monthly salary is: ')
8 print(((hourly_wage * 40 * 5
9 print()
10
11 # FIXME: The above is wrong.
12 # the 1 so that the s
13 # outputs monthly sal
14
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
15
PARTICIPATION
Daniel Reyes Daniel Reyes
1.9.1: Development environment basics. 16
ACTIVITY CS119-2402A-06-2402A CS119-2402A-06-2402A
In the late 1980s, Guido van Rossum began creating a scripting language called Python and an False
accompanying interpreter. He derived Python from an existing language called ABC. The name Python
came from Guido being a fan of the TV show Monty Python. The goals for the language included
simplicity and readability, while providing as much power and flexibility as other scripting languages like
Perl. 1.12 Why whitespace matters
Python 1.0 was released in 1994 with support for some functional programming constructs derived
from Lisp. Python 2.0 was released in 2000 and introduced automatic memory management (garbage
Whitespace and precise formatting
collection, described elsewhere) and features from Haskell and other languages. Python 3.0 was
released in 2008 to rectify various language design issues. However, Python 2.7 is the most widely used For program output, whitespace is any blank space or newline. Most coding activities strictly require a
version, due largely to third-party libraries supporting only Python 2.7. Python 2.7 programs cannot run student program's output to exactly match the expected output, including whitespace. Students learning
on Python 3.0 or later interpreters, i.e., Python 3.0 is not backwards compatible. However, Python 3.x programming often complain:
versions are becoming more widely used as new projects adopt the version. In fact, many libraries now
support Python 3.x since Python 2.7 has an "End Of Life" date (no more bug fixes) set for 2020 (Source: "My program is correct, but the system is complaining about output whitespace. "
Python.org). Python is an open-source language, meaning the community of users participate in
defining the language and creating new interpreters, and is supported by a large community of
However, correctness often includes output being formatted correctly.
programmers.
A December 2015 survey that measured the popularity of various programming languages found that PARTICIPATION
ACTIVITY 1.12.1: Precisely formatting a meeting invite.
Python (4.4%) is the second most popular language, just behind C++ (5.9%) (source: www.tiobe.com). A
review of open-source project contributions from 2004 to 2013 shows that the ratio of contributions
that are Python more than doubled, while C/C++ contributions fell 5–10% and Java contributions
remained the same (source: www.ohloh.net).
To provide some randomness to In programming, every little detail counts. Programmers must get in a mindset of paying extreme
the output attention to detail.
2) The programmer on the right did not Thus, another reason for caring about whitespace in program output is to help new programmers get
end the first sentence with a newline. into a "precision" mindset when programming. Paying careful attention to details like whitespace
What effect did that omission have? instructions, carefully examining feedback regarding whitespace differences, and then modifying a
program to exactly match expected whitespace is an exercise in strengthening attention to detail. Such
"Join meeting" appears on the
attention can lead programmers to make fewer mistakes when creating programs, thus spending less
same line
time debugging, and instead creating programs that work correctly.
No effect
PARTICIPATION
3) The programmer on the left neatly ACTIVITY
1.12.3: Thinking precisely, and attention to detail.
formatted the link, the "Phone:" text, and ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
phone numbers. What did the
CS119-2402A-06-2402A Programmers benefit from having a mindset of thinking precisely and paying attention to
CS119-2402A-06-2402A
programmer on the right do?
details. The following questions emphasize attention to detail. See if you can get all of the
Also neatly formatted those questions correct on the first try.
items
Output those items without
neatly formatting
1) How many times is the letter F (any 5) A password must start with a letter,
case) in the following? be at least 6 characters long, include
If Fred is from a part of France, then a number, and include a special
of course Fred's French is good. symbol. How many of the following
passwords are valid?
hello goodbye Maker1 dog!three
Oops_again 1augh#3
Check Show answer ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
2) How many differences are in these
Check Show answer
two lines?
Printing A linE is done using printIn
Printing A linE is done using print1n
PARTICIPATION
Check Show answer
ACTIVITY 1.13.1: People on bus.
Start
num_people: 5 5. In algebra, an equation means "the item on the left always equals the item on the right." So for x
+ y = 5 and x * y = 6, one can determine x = 2 and y = 3.
1 2 3 4 5 6. Assignment statements look similar but have VERY different meaning. The left side MUST be
one variable.
Check Next 7. The = isn't "equals," but is an action that PUTS a value into the variable. Assignment statements
only make sense when executed in sequence.
©zyBooks
By the way, the real riddle's ending question is actually, "What is the bus driver's02/27/24 20:03subject
name?" The 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
usually says, "How should I know?" The riddler then says, "I started with YOU are driving a bus."
CS119-2402A-06-2402A CS119-2402A-06-2402A
aside-elaboration
The box above serves the same purpose as a variable in a program, introduced below.
An assignment statement assigns a variable with a value, such as x = 5. That statement means x is
assigned with 5, and x keeps that value during subsequent statements, until x is assigned again.
An assignment statement's left side must be a variable. The right side can be an expression, so a
statement may be x = 5, y = x, or z = x + 2. The 5, x, and x + 2 are each an expression that evaluates to a PARTICIPATION
ACTIVITY 1.13.3: Valid assignment statements.
value.
x=5 x+y=5 2) x = y
53 x x*y=6 Valid
y=x
5 y
z=x+2 x=2 y=3 Invalid
7 z
x=3
3) x = y + 2
Valid
Animation captions: Invalid
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
1. In programming, a variable is a place to hold a value. Here, variables x, y,Daniel
and zReyes
are depicted 4) x + 1 = 3 Daniel Reyes
graphically as boxes. CS119-2402A-06-2402A CS119-2402A-06-2402A
2. An assignment statement assigns the left-side variable with the right-side expression's value. x Valid
= 5 assigns x with 5. Invalid
3. y = x assigns y with x's value, which presently is 5. z = x + 2 assigns z with x's present value plus
2, so 5 + 2 or 7.
4. A subsequent x = 3 statement assigns x with 3. x's former value of 5 is overwritten and thus
lost. Note that the values held in y and z are unaffected, remaining as 5 and 7.
5) x + y = y + x int z = 1;
x = 7; x is
y = 0;
Valid z = 9; 7 6 9
x = 6;
Invalid
y is
1 6 0
PARTICIPATION
1.13.4: Variables and assignment statements. z is
ACTIVITY ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
1 9 6
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Given variables x, y, and z.
1 2 3 4
1) x = 9
y=x+1
Check Next
What is y?
CHALLENGE
Check Show answer
ACTIVITY
1.13.1: Enter the output of the variable assignments.
2) x = 9 550678.3854950.qx3zqy7
y=x+1 Start
What is x?
Type the program's output
Because in programming = means assignment, a variable may appear on both the left and right as in x
PARTICIPATION ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
ACTIVITY 1.13.5: Trace the variable value. Daniel Reyes = x + 1. If x was originally 6, x is assigned with 6 + 1, or 7. The statement overwrites the
Daniel original 6 in x.
Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Increasing a variable's value by 1, as in x = x + 1, is common and known as incrementing the variable.
Select the correct value for x, y, and z after the following statements execute.
PARTICIPATION 1.13.6: A variable may appear on the left and right of an assignment
Start ACTIVITY
statement.
int x = 9;
int y = 6;
3) y = 30
x=y+2
x=1 1 20 400 x
x=x+1
x = x * 20
x = x * 20
A person with measles may cause 400
Put "A person with measles may cause " to output people to be infected in two weeks.
Put x to output
Check Show answer
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Put newline to output
Daniel Reyes Daniel Reyes
Put "people to be infected in two weeks." to output CS119-2402A-06-2402A 4) Complete this statement to CS119-2402A-06-2402A
increment y:
y = _____
Animation captions:
PARTICIPATION
ACTIVITY 1.13.7: Variable on both sides. Write a statement that assigns total_coins with the sum of nickel_count and dime_count.
Sample output for 100 nickels and 200 dimes is:
1) x = 5
x=x+7
Learn how our autograder works
550678.3854950.qx3zqy7
Check Show answer
1 total_coins = 0
2
3 nickel_count = int(input())
2) x = 2
4 dime_count = int(input())
y=3 5
6 ''' Your solution goes here '''
7
x=x*y
8 print(total_coins)
x=x*y
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Check Show answer
Run
sequence of letters (a-z, A-Z), underscores (_), and digits (0–9), and must start with a letter or an
View your last submission keyboard_arrow_down underscore.
Python is case sensitive, meaning upper- and lowercase letters differ. Ex: "Cat" and "cat" are different.
CHALLENGE
ACTIVITY
1.13.3: Multiplying the current value of a variable. The following are valid names: c, cat, Cat, n1m1, short1, and _hello. The following are invalid names: 42c
(doesn't start with a letter), hi there (has a space), and cat$ (has a symbol other than a letter or digit).
Write a statement that assigns cell_count with cell_count multiplied by 10. * performs Names that start and end with double underscores (for example, __init__) are allowed but should be
multiplication. If the input is 10, the output should be: ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
avoided because Python has special usages for double underscore names, explained elsewhere. A good
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A variable name should describe the purpose of the variable, such as "temperature" or "age," rather than
CS119-2402A-06-2402A
100
just "t" or "A."
Certain words like "and" or "True" cannot be used as names. Reserved words, or keywords, are words
that are part of the language, and thus, cannot be used as a programmer-defined name. Many language
Learn how our autograder works editors will automatically color a program's reserved words. A list of reserved words appears at the end
550678.3854950.qx3zqy7 of this section.
1 cell_count = int(input())
PARTICIPATION
2 1.14.1: Valid names.
ACTIVITY
3 ''' Your solution goes here '''
4
5 print(cell_count) Which of the following are valid names?
1) numCars
Valid
Invalid
2) num_cars1
Valid
Invalid
Run 3) _num_cars
Valid
View your last submission keyboard_arrow_down
Invalid
4) ___numcars2
Valid
1.14 Identifiers ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Invalid
©zyBooks 02/27/24 20:03 1927475
Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
5) num cars
Rules for identifiers
Valid
A programmer gives names to various items, such as variables (and also functions, described later). For Invalid
example, x = 5 uses the name "x" to refer to the value 5. An identifier, also called a name, is a
6) 3rd_place
Valid Less meaningful
Purpose More meaningful names
names
Invalid
ucla
7) third_place_ The number of students attending UCLA num num_students_UCLA
Valid nu
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Invalid Daniel Reyes The size of a television set measured as its sz_tv Daniel Reyes
CS119-2402A-06-2402A diagonal_tv_size_inches
CS119-2402A-06-2402A
diagonal length size
8) third_place!
The word for the ratio of a circle's
Valid p pi
circumference/diameter
Invalid
guess
The number of jelly beans in a jar, as num_guessed_jelly_beans
9) output num
guessed by a user user_guess_jelly_beans
njb
Valid
Invalid
10) print_copy
A list of reserved keywords in the language are shown below:
Valid
Invalid
Table 1.14.2: Python 3 reserved keywords.
PARTICIPATION PARTICIPATION
ACTIVITY 1.14.2: Python 3 name validator. ACTIVITY
1.15.1: Scientific notation.
Use the tool below to test valid and invalid names. 1) Type 1.0e-4 as a floating-point literal
but not using scientific notation,
with a single digit before and four
Enter an identifier: Validate digits after the decimal point.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
A floating-point number is a real number, like 98.6, 0.0001, or -666.667. The term "floating-point" refers
to the decimal point being able to appear anywhere ("float") in the number. Thus, float is a data type for
floating-point numbers. Check Show answer
A floating-point literal is written with the fractional part even if that fraction is 0, as in 1.0, 0.0, or 99.0.
3) Type 540,000,000 as a floating-point
literal using scientific notation with a
Figure 1.15.1: A program using float-type variables. single digit before and after the
decimal point.
The below program reads in a floating-point value from a user and calculates the time to drive
and fly the distance. Note the use of the built-in function float() when reading the input to
convert the input string into a float. Check Show answer
Scientific notation is useful for representing floating-point numbers that are much greater than or much
less than 0, such as 6.02x1023. A floating-point literal using scientific notation is written using an e
preceding the power-of-10 exponent, as in 6.02e23 to represent 6.02x1023. The e stands for exponent.
Likewise, 0.001 is 1x10-3, so it can be written as 1.0e-3.
Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers (Ex:
3.14159265359….) and repeating decimals (Ex: 4.33333333….) have an infinite number of digits after the
decimal. By default, most programming languages output at least 5 digits after the decimal point. But
for many simple programs, this level of detail is not necessary. A common approach is to output
floating-point numbers with a specific number of digits after the decimal to reduce complexity or
produce a certain numerical type (Ex: Representing currency with two digits after the decimal). The
syntax for outputting the float myFloat with two digits after the decimal point is
©zyBooks 02/27/24 20:03 1927475 print('{:.2f}'.format(myFloat)) ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A When outputting a certain number of digits after the decimal using print(), CS119-2402A-06-2402A
Python rounds the last output
digit, but the floating-point value remains the same. Manipulating how numbers are output is discussed
in detail elsewhere.
PARTICIPATION
ACTIVITY 1.15.2: Reducing the output of Pi.
3) What is output by
import math
print('{:.3f}'.format(9.1357))?
print('Default output of Pi:', math.pi)
print('Pi reduced to 4 digits after the decimal:', end=' ') 9.136
print('{:.4f}'.format(math.pi))
9.135
9.14
Default output of Pi: 3.141592653589793
©zyBooks 02/27/24 20:03 1927475
Pi reduced to 4 digits after the decimal: 3.1416 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
2) What is output by ©zyBooks 02/27/24 20:03 1927475 ** The exponent operator is **, as in x ** y (x to the power of
©zyBooks y).
02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
print('{:.1f}'.format(0.125))? CS119-2402A-06-2402A CS119-2402A-06-2402A
0
0.1
PARTICIPATION
0.13 ACTIVITY 1.16.1: Expressions.
1) x + 1 2) 6 times num_items:
Valid
6 x num_items
Not valid
Yes
2) 2 * (x - y) No
Valid 3) total_days divided by 12:
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Not valid Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
total_days / 12
3) x
Yes
Valid
No
Not valid
4) 5 times t:
4) 2
5t
Valid
Yes
Not valid
No
5) 2x 5) The negative of user_val:
Valid
-user_val
Not valid
Yes
6) 2 + (xy)
No
Valid
6) n factorial
Not valid
n!
7) y = x + 1
Yes
Valid
No
Not valid
Evaluation of expressions
PARTICIPATION
1.16.2: Capturing behavior with an expression.
ACTIVITY An expression evaluates to a value, which replaces the expression. Ex: If x is 5, then x + 1 evaluates to 6,
©zyBooks 02/27/24 20:03 1927475 and y = x + 1 assigns y with 6. ©zyBooks 02/27/24 20:03 1927475
Does the expression correctly capture the intended behavior? Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A An expression is evaluated using the order of standard mathematics, and such order is known in
CS119-2402A-06-2402A
1) 6 plus num_items: programming as precedence rules, listed below.
6 + num_items
Table 1.16.2: Precedence rules for arithmetic operators.
Yes
No
Operator/Convention Description Explanation
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 79/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 80/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
In x**y * 3, x to the power of y is 1. An expression like 3 * (x + 10 / w) evaluates to a value, using precedence rules. Items within
exponent ** ** used for exponent is next. computed first, with the results parentheses come first, and / comes before +, yielding 3 * (x + 5).
then multiplied by 3. 2. Evaluation finishes inside the parentheses: 3 * (x + 5) becomes 3 * 9.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes
3. Thus, the original expression evaluates to 3 * 9 or 27. That value replaces the expression. So y =
Daniel Reyes
In 2 * -x, the CS119-2402A-06-2402A
-x is computed first, 3 * (x + 10 / w) becomes y = 27, so y is assigned with 27. CS119-2402A-06-2402A
- used for negation (unary minus)
unary - with the result then multiplied by 4. Many programmers prefer to use parentheses to make order of evaluation more clear when
is next.
2. such order is not obvious.
3) x * y * z
(x * y) * z
PARTICIPATION
1.16.3: Evaluating expressions.
ACTIVITY x * (y * z)
4) x + 1 * y/2
((x + 1) * y) / 2
x=4
©zyBooks 02/27/24 20:03 1927475 x + ((1 * y) / 2) ©zyBooks 02/27/24 20:03 1927475
w=2 Preferred
Daniel Reyes Daniel Reyes
y = 3 * (x + 10 / w) y = 3CS119-2402A-06-2402A
* (x + (10 / w)) x + ( 1 * (y / 2)) CS119-2402A-06-2402A
10 / 2
5 5) x / 2 + y / 2
3 * (x + 5) ((x / 2) + y) / 2
4+5
9 (x / 2) + (y / 2)
3*9
y = 27
6) What is total_count after executing the If unable to drag and drop, refresh the page.
following?
num_items = 5 — [] Spaces in variable names ×
total_count = 1 + (2 * num_items) *
4
44
Replaced by ( )
41
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A Underscores CS119-2402A-06-2402A
aside-elaboration
-
550678.3854950.qx3zqy7
Start
Example: Calorie expenditure
A website lists the calories expended by men and women during exercise as follows (source): Type the program's output
Men: Calories = [(Age × 0.2017) + (Weight × 0.09036) + (Heart Rate × 0.6309) — 55.0969] × Time / x = 11
y = x + 4
15
4.184
print(y)
Women: Calories = [(Age × 0.074) — (Weight × 0.05741) + (Heart Rate × 0.4472) — 20.4022] × Time /
4.184 1 2
Below are those expressions written using programming notation: Check Next
""" Computes the total cost of leasing a car given the down
Addition assignment age += 1 age = age + 1
payment,
monthly rate, and number of months """
Enter down payment: 500 Subtraction assignment age -= 1 age = age - 1
down_payment = int(input('Enter down payment: ')) Enter monthly payment:
300
payment_per_month = int(input('Enter monthly payment: '))
Enter number of months:
Multiplication assignment age *= 1 age = age * 1
num_months = int(input('Enter number of months: '))
60
total_cost = down_payment + (payment_per_month * num_months) Total cost: 18500 Division assignment age /= 1 age = age / 1
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
print ('Total cost:', total_cost) Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A
Modulo (operator further discussed CS119-2402A-06-2402A
age %= 1 age = age % 1
elsewhere) assignment
PARTICIPATION
ACTIVITY
1.17.1: Simple program with an arithmetic expression.
PARTICIPATION
ACTIVITY
1.17.2: Compound operators.
Consider the example above.
Yes
No Check Show answer
No
3) Rewrite the statement using a
compound operator, or type: Not
Compound operators possible
car_count = car_count / 2
Special operators called compound operators provide a shorthand way to update
©zyBooks a variable,
02/27/24 20:03such as
1927475 ©zyBooks 02/27/24 20:03 1927475
age += 1 being shorthand for age = age + 1. Other compound operators includeDaniel
-=, *=,Reyes
/=, and %=. Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Check Show answer ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A Run CS119-2402A-06-2402A
Given sphere_radius and pi, compute the volume of a sphere and assign sphere_volume with
1) The following code correctly assigns the volume. Volume of sphere = (4.0 / 3.0) π r3
num_years with an integer value of 2
billion. Sample output with input: 1.0
num_years = 2,000,000,000
Sphere volume: 4.19
True
False
1 pi = 3.14159
Write a single statement that assigns avg_sales with the average of num_sales1, num_sales2, 2 sphere_volume = 0.0
3
and num_sales3.
4 sphere_radius = float(input())
5
Sample output with inputs: 3 4 8 6 ''' Your solution goes here '''
7
Average sales: 5.00 8 print('Sphere volume: {:.2f}'.format(sphere_volume))
Learn how our autograder works ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
550678.3854950.qx3zqy7
1 avg_sales = 0
2
3 num_sales1 = int(input())
4 num_sales2 = int(input())
Run
5 num_sales3 = int(input())
6
7 ''' Your solution goes here '''
View your last submission keyboard_arrow_down
8
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 87/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 88/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
1 userNum = int(input())
2 userNumSquared = userNum * userNum # Bug here; fix it when instructed
3
4 print(userNumSquared) # Output formatting issue here; fix it when instructed
1.18 zyLab Basics
While the zyLab platform can be used without training, a bit of training may help some students avoid
common issues. ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
The assignment is to get an integer from input, and output that integer squared, ending with newline.
CS119-2402A-06-2402A CS119-2402A-06-2402A
(Note: This assignment is configured to have students programming directly in the zyBook. Instructors
may instead require students to upload a file). Below is a program that's been nearly completed for you.
1. Click "Run program". The output is wrong. Sometimes a program lacking input will produce wrong
output (as in this case), or no output. Remember to always pre-enter needed input.
2. Type 2 in the input box, then click "Run program", and note the output is 4.
Run your program as often as you'd like, before submitting
3. Type 3 in the input box instead, run, and note the output is 6. Develop mode Submit mode
for grading. Below, type any needed input values in the first
When students are done developing their program, they can submit the program for automated grading. box, then click Run program and observe the program's
output in the second box.
1. Click the "Submit mode" tab
Enter program input (optional)
2. Click "Submit for grading".
3. The first test case failed (as did all test cases, but focus on the first test case first). The If your code requires input values, provide them here.
highlighted arrow symbol means an ending newline was expected but is missing from your
program's output.
Matching output exactly, even whitespace, is often required. Change the program to output an ending
trending_flat trending_flat
main.py
newline. Run program Input (from above)
(Your program)
Output
1. Click on "Develop mode", and change the output statement to output a newline:
Program output displayed here
print(userNumSquared). Type 2 in the input box and run.
2. Click on "Submit mode", click "Submit for grading", and observe that now the first test case passes
and 1 point was earned.
The last two test cases failed, due to a bug, yielding only 1 of 3 possible points. Fix that bug.
Coding trail of your work What is this?
1. Click on "Develop mode", change the program to use * rather than +, and try running with input 2
(output is 4) and 3 (output is now 9, not 6 as before). 2/10 S---0-1--3 min:7
2. Click on "Submit mode" again, and click "Submit for grading". Observe that all test cases are
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
passed, and you've earned 3 of 3 points. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
550678.3854950.qx3zqy7
LAB
1.19 LAB: Formatted output: Hello World!
ACTIVITY
1.18.1: zyLab Basics 3/3
Write a program that outputs "Hello World!" For ALL labs, end with newline (unless otherwise stated).
main.py Load default template...
550678.3854950.qx3zqy7
Output each floating-point value with two digits after the decimal point, which can be achieved as
follows:
print('Men: {:.2f} calories'.format(calories_man))
trending_flat trending_flat
550678.3854950.qx3zqy7
main.py
Run program Input (from above) Output
(Your program)
LAB
ACTIVITY
1.20.1: LAB: Expression for calories burned during workout 10 / 10
Program output displayed here
trending_flat trending_flat
main.py
Run program Input (from above) Output
(Your program)
Remember, you can always continue practicing to improve your score©zyBooks 02/27/24 20:03 1927475
on the assignments. ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
If you scroll up, you can look for incomplete activities. A check mark will appear to the right of
each activity that has been completed.
1.22 LAB: Input: Welcome message
View your 'My Activity' tab to see the assignment completion from a birds eye view. (Get there by
clicking on the course name at the top of this page --> My Activity on the bottom right)
info This section has been set as optional by your instructor.
To ensure your grades and scores sync with the VC gradebook, close out of this zyBook and click on
the next assignment link in Virtual Campus rather than clicking the next section in the zyBook now.
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 93/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 94/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
Write a program that takes a first name as the input, and outputs a welcome message to that name.
Coding trail of your work What is this?
Ex: If the input is Pat, the output is:
History of your effort will appear here once you begin working
Hello Pat and welcome to CS Online! on this zyLab.
550678.3854950.qx3zqy7
1 user_name = input() info This section has been set as optional by your instructor.
2
3 ''' Type your code here. '''
Driving is expensive. Write a program with a car's miles/gallon and gas dollars/gallon (both floats) as
input, and output the gas cost for 20 miles, 75 miles, and 500 miles.
Output each floating-point value with two digits after the decimal point, which can be achieved as
follows:
print('{:.2f} {:.2f} {:.2f}'.format(your_value1, your_value2, your_value3))
20.0
3.1599
trending_flat trending_flat
main.py
Daniel Reyes Daniel Reyes
Run program Input (from above)
CS119-2402A-06-2402A
Output
CS119-2402A-06-2402A
(Your program)
1 ''' Type your code here. '''
2
Program output displayed here
trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Output
History of your effort will appear here once you begin working
on this zyLab.
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 97/97