0% found this document useful (0 votes)
17 views49 pages

Programming ZyBooks1

The document outlines the structure and functionality of participation activities (PAs) and challenge activities (CAs) within zyBooks, emphasizing their role in engaging students and assessing their understanding. PAs allow students to earn points through participation without penalties for incorrect answers, while CAs require students to demonstrate mastery of the material. Additionally, it discusses the importance of feedback and tracking completion status for both students and instructors.

Uploaded by

cadabradanny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views49 pages

Programming ZyBooks1

The document outlines the structure and functionality of participation activities (PAs) and challenge activities (CAs) within zyBooks, emphasizing their role in engaging students and assessing their understanding. PAs allow students to earn points through participation without penalties for incorrect answers, while CAs require students to demonstrate mastery of the material. Additionally, it discusses the importance of feedback and tracking completion status for both students and instructors.

Uploaded by

cadabradanny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

3) When a participation activity's question


is answered, an explanation appears.
1.1 Basics Such explanations can usually be
skipped.
True
Participation activities
False
©zyBooks
In a zyBook, a participation activity (PA) is an activity used in the initial learning02/27/24 20:03
of a topic. 1927475
A PA is a ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes 4) Answering a question, even incorrectly, Daniel Reyes
more engaging way of reading. As one student put it, "It's like the material is working with me,
CS119-2402A-06-2402A rather CS119-2402A-06-2402A
counts as completing the question.
than talking to me." Anyone can get all PA points just by participating (hence the name).
True
PA's are labeled and numbered as: "Participation Activity 1.1.1". A zyBook records student completion of
each PA. An instructor may provide course points for completing PA's. Completing means: False

5) Animations can be completed by


Learning questions: Eventually entering a correct answer.
clicking on each step, but not
Animations: Watching all steps in their entirety.
necessarily watching each step entirely.
Tools: Interacting with the tool; some tools require reaching "done".
True
Learning questions have no penalty if a student answers wrong the first time (or multiple times) or if a
False
student shows themselves the answer.

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

PA completion can be viewed by the filled-in icons next to each activity.


1) A small point deduction applies if a
participation activity's question is not
answered correctly the first time. Figure 1.1.1: PA completion icons filling in as learning questions are
True correctly answered.
False

2) Clicking "Show answer" means no


points can later be gained for this
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
question. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
True
False

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 1/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 2/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

If you are completing zyBook activities in another browser tab, you may have to reload the Home/TOC
page to see updated activity completion.

Figure 1.1.3: Checking section activity completion on a zyBook's


Home/TOC page.
©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.1.2: PA completion icon filling in as an animation's steps are


watched entirely.

PARTICIPATION
ACTIVITY
1.1.2: PA completion.

1) A student's section-level activity


completion data can be found by _____ .
clicking on the zyBook's name at
the top to go to the zyBook's
"Home"
clicking on the student's name

2) If the activity completion does not


appear updated, then _____ .
"refreshing" the page may help
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes send email to Daniel Reyes
CS119-2402A-06-2402A [email protected] CS119-2402A-06-2402A

Viewing PA completion for entire sections

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 3/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 4/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

1) If a student returns to a section and


notices all previous answers are
missing, then _____ .
the zyBook system must be
broken
waiting long enough should
cause the answers to appear
PARTICIPATION
this is normal ACTIVITY 1.1.4: zyBook activity feedback.

1) Our team requests that you make


Feedback
extensive use of the _____ link to tell
Use the "Feedback" links throughout the material to let us know what was helpful and what could be us what you liked and what could be
improved. The feedback links appear throughout the material; if one doesn't exist for an item you'd like improved.
to report on, just find the closest one and explain what item you're referring to. Our authoring team
reviews such feedback a couple times each year, which helps guide updates/improvements to the
material. ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Check Show answer Daniel Reyes
Errors: While all material goes through a review process, if you find an error,CS119-2402A-06-2402A
please let us know by CS119-2402A-06-2402A

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 5/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 6/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

2) Selecting "My feedback describes a


possible content or technical _____"
within the feedback form causes the
support team to be immediately
notified.

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Check Show answer Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A

3) Describing an actual bug like "A


small insect" or even "An error in a
program", and then selecting "My
comments describe a bug", is a
funny joke. (Answer true or false).

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.

Figure 1.2.2: Progression challenge activities: Incorrect answers.

1.2 Progression challenge activities


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.

Different types of CAs exist. A particular zyBook may have one type of CA, different types of CAs, or no
CAs at all.

Progression challenge activities

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 7/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 8/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

1 2 3 4 5 6 7

Check Next

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Daniel Reyes
CS119-2402A-06-2402A 1.3 Programming challenge activities
Daniel Reyes
CS119-2402A-06-2402A

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

2) A user may only attempt a question at


Figure 1.3.1: Sample C++ programming challenge homework activity:
each level once. Replace comment with your code.
True
False

CHALLENGE 1.2.1: Sample progression challenge activity: Simplify ©zyBooks


using the 02/27/24
laws of 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
ACTIVITY
exponents. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A

550678.3854950.qx3zqy7

Start

Ex: 2
x7 x3 = x

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 9/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 10/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

©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 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.

©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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 11/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 12/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

Figure 1.3.5: Programming challenge activity completion.

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.

Figure 1.3.6: Failing test cases due to using a literal.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 13/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 14/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

©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

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

2) If a user's program passed an activity's


©zyBooks 02/27/24 20:03 1927475 sample test case, the program is ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes deemed correct. Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
True
False

When running a program, a user may see this error message:

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 15/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 16/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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) The message "Program end never


reached" means that the user's program
generated output that didn't match the
expected output.
True
False
©zyBooks 02/27/24 20:03 1927475 2) If a student runs a program ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A successfully in a separate environment, CS119-2402A-06-2402A
but the program fails in the zyBook, the
most common reason is a problem in
the zyBook system.
True
False

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 17/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 18/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

3) If the compiler reports an error on a line


of code the user cannot edit, the 1.4 zyLab basics
compiler must be broken.
True
Intro to program auto-graders
False
In the "old days", students self-tested their weekly programming assignment, then submitted it for
©zyBooks 02/27/24 20:03 1927475 ©zyBooks
grading. Instructors, TAs, or readers would grade the programs, running 02/27/24on
each program 20:03
the 1927475
CHALLENGE Daniel Reyes Daniel Reyes
ACTIVITY
1.3.1: Sample programming challenge activity. CS119-2402A-06-2402A instructor's test cases. Perhaps a week later (or more), students would receive a grade for that program,
CS119-2402A-06-2402A
sometimes (but not always) with feedback explaining point deductions and suggested improvements.
Modify the program so the output is: Unfortunately, getting grades/feedback a week later was not ideal for learning, as students had moved
on to the next assignment and often ignored feedback (or such feedback was received too late, after the
Annual pay is 40000
next assignment was already submitted). Plus, students were often frustrated due to unexpectedly low
To solve this sample, replace /* Your solution goes here */ with: scores. Furthermore, much of a teacher's time was spent with such grading, meaning less time to
interact with students.
cout << "Annual pay is "; In fact, that situation is not really the "old days" -- it is probably still the most common situation in
programming classes today.
then click "Run".
Instead, your instructor has chosen to use a state-of-the-art program auto-grader, called zyLabs. An
Learn how our autograder works auto-grader automatically runs a student's program on an instructor's test cases, and immediately
provides a score to the student. In response, a student can immediately determine and fix mistakes, and
550678.3854950.qx3zqy7 resubmit. The learning is better because feedback is immediate (true, human feedback may be better,
1 #include <iostream> but not when received a week or more later), and scores are no longer an upsetting surprise.
2 using namespace std;
3 Any auto-grader has potential issues as well. This section aims to help students become comfortable
4 int main() { with the zyLab auto-grader, so students can enjoy auto-grading's benefits, with minimal issues.
5 int wage = 20;
6 zyLab assignments are created and/or controlled by instructors, not by zyBooks. Students having
7 /* Your solution goes here */
issues should usually first consult with their class' help resources. (Of course, if the zyLabs platform
8
9 cout << wage * 40 * 50; seems to be having issues (rare), please contact zyBooks support by clicking on the "Feedback" link at
10 cout << endl; the bottom of every zyLab assignment).
11
12 return 0; One last note: Learning to program is hard. It is perfectly normal to struggle with converting an
13 } instructor's specification into an actual program, to experience bugs, etc. Even experienced
programmers struggle. But the reward of a working program can be quite great. The zyLabs auto-grader
is often the bearer of the bad news that "Your program isn't correct", but we hope you find that getting
that news immediately so you can fix your program is better than getting that news two weeks later.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Run Daniel Reyes PARTICIPATION Daniel Reyes
CS119-2402A-06-2402A ACTIVITY 1.4.1: Auto-graders. CS119-2402A-06-2402A
View your last submission keyboard_arrow_down

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 19/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 20/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

3) zyLab test cases are created and


controlled by zyBooks staff.
True
False

4) Clicking on the "Feedback" link at the


bottom of a zyLab assignment sends
an email to your instructor.
True
False

5) A student should expect to fail plenty of


test cases as they learn to program.
True
False

zyLabs with programming window: Develop mode


PARTICIPATION
To ease a student's programming learning curve, an instructor can configure a zyLab assignment such ACTIVITY 1.4.2: zyLabs with programming window: Develop mode.
that students program directly in a programming window in the zyLab assignment itself. As such,
students need not use an external development tool (known as an IDE). Such simplicity can be 1) Any zyLab assignment can be
especially helpful in the first weeks of a class; in fact, some intro classes use the zyLab programming programmed directly in a zyLab
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
window the entire term, teaching an IDE in a second class. Daniel Reyes programming window. Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
If configured as such, a student writes a program directly in the assignment's programming window. True
The student can test their program by pressing the "Develop mode" tab and then clicking "Run program".
False
If the program requires input values, the student can pre-enter those values in the input box. The
program's output (or error messages) appear in the output box.

A student can run their program as many times as desired while in develop mode, testing the program
on different input values.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 21/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 22/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

2) An instructor can limit the number of


times a student can run a program in
develop mode.
True
False

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

1) When a zyLab assignment is configured


zyLabs with program file upload by an instructor for program files to be
uploaded, the student develops their
An instructor can configure an assignment to require students to upload one or more program files. The program in another environment.
student can drag the file onto the corresponding box, or click to find the file on the student's drive.
True
False
Figure 1.4.2: Multiple file submission.
2) The uploaded filename must match the
expected filename exactly.
True
False

3) In the figure above, the second file has


been successfully uploaded.
True
False

4) Above, uploading CustomerInfo.cpp


would result in a successful upload.
True
False

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A
Submitting a program for grading CS119-2402A-06-2402A
A file's name and extension must match exactly, or the zyLab platform will not recognize the file.
Common errors include misspelled file names, use of uppercase instead of lowercase letters or vice- If an assignment is configured with a programming window, the student can select "Submit mode" to
versa, and wrong file extensions (such as .doc rather than .cpp). get ready to submit their program for grading. That mode does NOT actually submit yet. Rather, a
"Submit for grading" button appears.

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 23/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 24/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

1) Upon submitting a program for grading,


the student's program is run using the
Noting the failed test cases can help the student understand how to correct their program. Above, the instructor's test cases.
student realizes more numbers must be output, and proceeds to fix the program.
True
False
Figure 1.4.5: Submitted and graded lab: All test cases passed.
2) Each passed test case earns some
points.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes True Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
False

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 25/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 26/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

3) An instructor can limit the number of


Figure 1.4.7: Control character placeholder for invalid characters.
submissions, or the rate of
submissions.
True
False

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

Compare output test PARTICIPATION


1.4.5: Compare output tests.
ACTIVITY

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

2) If a student repeatedly fails test cases


because of whitespace issues even
though the program's logic is correct,
the student can reasonably conclude
that the zyBooks platform is too picky.
True
False

3) If a program runs fine on an IDE but


fails when submitted for grading in
An instructor can configure any compare output test case to ignore whitespace. Some instructors zyLabs, the zyLabs platform probably
believe precise output formatting is important (teaching precision), others don't wish to have students has a bug.
worrying about whitespace details. True
Numerous other configuration options exist, such as only requiring the start of 02/27/24
©zyBooks the output to match,
20:03 or
1927475 False ©zyBooks 02/27/24 20:03 1927475
only the end of the output to match. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
No perfect algorithm exists for determining and showing differences between student output and
expected output. For certain situations, the highlighting may be somewhat confusing. But hopefully the
immediate feedback still helps the student determine what is wrong.

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).

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 27/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 28/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

1) A student's program should output all


the text shown in an instructor's
example of the program running.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
True Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
False

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 29/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 30/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

1.5 Programming using Python PARTICIPATION


ACTIVITY
1.5.2: Match the Python terms with their definitions.

If unable to drag and drop, refresh the page.


Python interpreter

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

>>> wage = 20 Python interpreter Executing a Python program


>>> hours = 40
Name Value
>>> weeks = 50 wage 20 The Python interactive interpreter is useful for simple operations or programs consisting of only a few
>>> salary = wage * hours * weeks hours 35 lines. However, entering code line-by-line into the interpreter quickly becomes unwieldy for any program
>>> print(salary) weeks 50 spanning more than a few lines.
40000 salary 35000
>>> hours = 35 Instead, a programmer can write Python code in a file, and then provide that file to the interpreter. The
>>> salary = wage * hours * weeks interpreter begins by executing the first line of code at the top of the file, and continues until the end is
>>> print(salary) reached.
35000
>>> | A statement is a program instruction. A program mostly consists of a series of statements, and
each statement usually appears on its own line.
Expressions are code that return a value when evaluated; for example, the code
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes wage * hours * weeks is an expression that computes a number. The symbol
Daniel * is used for
Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
multiplication. The names wage, hours, weeks, and salary are variables, which are named
references to values stored by the interpreter.
Animation captions:
A new variable is created by performing an assignment using the = symbol, such as
1. After each press of the enter key, the python interpreter executes the line of code. salary = wage * hours * weeks, which creates a new variable called salary.
2. The python interpreter can be used as a calculator and can perform a variety of calculations. The print() function displays variables or expression values.
3. Users can change values and execute calculations again. '#' characters denote comments, which are optional but can be used to explain portions of code to
a human reader.
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 31/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 32/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

©zyBooks 02/27/24 20:03 1927475


4) Comments are required in a program. ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
file.py Python interpreter True
CS119-2402A-06-2402A CS119-2402A-06-2402A
wage = 20 False
>>>
hours = 40
weeks = 50 Name Value
salary = wage * hours * weeks
wage 20
print('Salary is:', salary) hours 35
weeks
salary
50
35000
zyDE 1.5.1: A first program.
hours = 35
salary = wage * hours * weeks
print('New salary is:', salary) The below program simulates a race between two cars, displaying the
position of each car at the end of the race. Make sure the output box
Salary is: 40000
below the code is visible, then click "run."
New salary is: 35000
The car1_top_speed and car1_acceleration variables control the
maximum velocity and acceleration of car 1. Modify these variables, and
run the program again. Can you make the second car win?
Animation captions:
You do not need to understand how the code works right now. Instead,
1. The python interpreter reads a file line by line. Variables wage, hours, and weeks are named just modify the speed and acceleration variables and observe how the
references that refer to values stored by the interpreter. output changes.
2. 20 * 40 * 50 is computed, and then the variable salary is assigned with the value.
3. The print statement prints 'Salary is:' to the screen and displays the value of the variable salary.
4. Values can be overwritten if the same variable name is used.

PARTICIPATION
ACTIVITY 1.5.4: Python basics.

1) What is the purpose of variables?


Store values for later use.
Instruct the processor to execute
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
an action. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Automatically color text in the
editor.

2) The code 20 * 40 is an expression.


True
False

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 33/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 34/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

Load default template...


# Each print statement starts on a new
line Hello there.
1 # Welcome to the Python 500 race! Click the run button to print('Hello there.') My name
2 print('My name is....') is....
3 # Configurable values. print('Carl?') Carl?
4 # Try changing car speeds, accelerations, and the simulati
5 car1_top_speed = 60
6 car2_top_speed = 50
7 ©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
8 car1_acceleration = 11
CS119-2402A-06-2402A CS119-2402A-06-2402A
9 car2_acceleration = 10
PARTICIPATION
10
ACTIVITY
1.6.1: Basic text output.
11 car1 = [' ______\n',
12 ' |__1_|_\\\n',
13 ' O----O\n'] 1) Select the statement that prints the
14
following: Welcome!
15
16 car2 = [' ___\n', print(Welcome!)
17 ' /__2_\\__\n',
print('Welcome!")
Run
print('Welcome!')

PARTICIPATION
ACTIVITY
1.6.2: Basic text output.

1) Type a statement that prints the


following: Hello

1.6 Basic output


Check Show answer

Basic text output


CHALLENGE
ACTIVITY 1.6.1: Output simple text.
Printing output to a screen is a common programming task. This section describes basic output; later
sections have more details.
Write the simplest statement that prints the following:
The primary way to print output is to use the built-in function print(). Ex: print('hello world').
Text enclosed in quotes is known as a string literal. Text in string literals may have letters, numbers, 3 2 1 Go!
spaces, or symbols like @ or #. Each use of print() starts on a new line.
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes
Note: Whitespace (blank spaces / blank lines) matters; make sure your whitespace exactly
Daniel Reyes
A string literal can be surrounded by matching single or double quotes: 'Python rocks!' or matches the expected output.
CS119-2402A-06-2402A CS119-2402A-06-2402A
"Python rocks!". Good practice is to use single quotes for shorter strings and double quotes for
more complicated text or text that contains single quotes, likeprint("Don't eat that!").

Learn how our autograder works


Figure 1.6.1: Printing text. 550678.3854950.qx3zqy7

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

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Daniel Reyes View your last submission keyboard_arrow_down Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A

Keeping output on the same line

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=' ')

Outputting a variable's value

The value of a variable can be printed out via: print(variable_name)(without quotes).

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 37/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 38/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

Figure 1.6.3: Printing the value of a variable. wage = 20

print('Wage:', wage) # Comma separates multiple Wage: 20


items Goodbye.
wage = 20 print('Goodbye.')

print('Wage is', end=' ') Wage is


print(wage) # print variable's 20
Goodbye.
©zyBooks 02/27/24 20:03 1927475
value ©zyBooks 02/27/24 20:03 1927475
print('Goodbye.') Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
A common error is to forget the comma between items, as in print('Name' user_name).

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

1) Write a statement that prints the


value of the variable num_people.

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.

Figure 1.6.4: Printing multiple items using a single print statement.


Any space, tab, or newline is called whitespace.

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.

print('Enter name of best friend:', end=' ')


Assume variable age = 22, pet = "dog", and pet_name = "Gerald". best_friend = input()
Marty McFly best_friend
print('My best friend is', best_friend)
1) What is the output of
Input
print('You are', age,
Marty McFly
'years old.') Output
Enter name of best friend: Marty McFly

My best friend is Marty McFly

Check Show answer

2) What is the output of


print(pet_name, 'the',
pet, 'is', age) Animation captions:
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel
1. The input() statement gets an input value from the keyboard and puts that Reyes
value into the
CS119-2402A-06-2402A CS119-2402A-06-2402A
best_friend variable.
Check Show answer 2. best_friend's value can then be used in subsequent processing and outputs.

PARTICIPATION
ACTIVITY 1.7.2: Reading user input.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 41/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 42/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

1) Which statement reads a user-entered


string into variable num_cars? Figure 1.7.2: Converting user input to integers.
num_cars = input
input() = num_cars print('Enter wage:', end='
')
num_cars = input() wage = int(input()) Enter wage:
8
©zyBooks 02/27/24 20:03 1927475 new_wage = wage + 10 ©zyBooks
New wage: 18 02/27/24 20:03 1927475
Daniel Reyes print('New wage:', Daniel Reyes
PARTICIPATION new_wage)
1.7.3: Reading user input. CS119-2402A-06-2402A CS119-2402A-06-2402A
ACTIVITY

1) Complete a statement that reads a


user-entered string into variable
my_var. PARTICIPATION
ACTIVITY
1.7.4: Converting user input to integers.

1) Type a statement that converts the


Check Show answer
string '15' to an integer and assigns
my_var with the result.

Converting input types

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

Figure 1.7.1: Using int() to convert strings to integers.


Input prompt
my_string = '123'
my_int = Adding a string inside the parentheses of input() displays a prompt to the user before waiting for input
int('123') 123 ©zyBooks 02/27/24 20:03 1927475 and is a useful shortcut to adding an additional print statement line. ©zyBooks 02/27/24 20:03 1927475
123 Daniel Reyes Daniel Reyes
print(my_string) CS119-2402A-06-2402A CS119-2402A-06-2402A
print(my_int)
Figure 1.7.3: Basic input example.

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

finish the code.


hours = 40 Enter hourly wage:
weeks = 50 12
num1 = int(input())
hourly_wage = int(input('Enter hourly wage:
'))
Salary is 24000 num2 = ?
....
Enter hourly wage: print(num1 + ?)
print('Salary is', hourly_wage * hours * 20
weeks) Salary is 40000

©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

View your last submission keyboard_arrow_down

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

Learn how our autograder works


Read two numbers from user input. Then, print the sum of those numbers.
Hint -- Copy/paste the following code, then just type code where the questions marks are to 550678.3854950.qx3zqy7

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

print('Current salary is', end='


')
print(45000) File "<main.py>", line 7
print(new_sal)
print('Enter new salary:', end=' print(user_num)
') ^
new_sal = int(input()) SyntaxError: invalid syntax
print(new_sal) print(user_num)
©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

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

1.8 Errors No Error

2) print("Dogs: " num_dogs)

Syntax errors Error


No Error
As soon as a person begins trying to program, that person will make mistakes. One kind of mistake,
known as a syntax error, is to violate a programming language's rules on how symbols can be 3) print('Woof!")
combined to create a program. An example is putting multiple prints on the same line.
Error
The interpreter will generate a message when encountering a syntax error. The error message will
report the number of the offending line, in this case 7, allowing the programmer to go back and fix the No Error
problem. Sometimes error messages can be confusing, or not particularly helpful. Below, the message
4) print(Woof!)
"invalid syntax" is not very precise, but is the best information that the interpreter is able to report. With
enough practice a programmer becomes familiar with common errors and is able to avoid them, Error
avoiding headaches later. No Error
Note that syntax errors are found before the program is ever run by the interpreter. In the example
below, none of the prints prior to the error is in the output. 5) print("Hello + friend!")
©zyBooks 02/27/24 20:03 1927475 Error ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A No Error CS119-2402A-06-2402A
Figure 1.8.1: A program with a syntax error.

PARTICIPATION
ACTIVITY
1.8.2: Common syntax errors.

Find and click on the 3 syntax errors.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 47/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 48/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
stmt4
stmt5 stmt4
stmt5
stmt6 stmt6
1) triangle_base = 0 # Triangle base (cm) stmt7 stmt7
triangle_height = 0 # Triangle height (cm)
triangle_area = 0
# Triangle area (cm) Run code Run code
Run code
Run code
print('Enter triangle base (cm): ')
triangle_base = int(input()
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
print('Enter triangle height (cm): ') CS119-2402A-06-2402A CS119-2402A-06-2402A
triangle_height = int(input())
Animation captions:

1. Writing many lines of code without compiling is bad practice.


# Calculate triangle area 2. New programmers should compile their program after every couple of lines.

triangle_area = (triangle_base * triangle_height) / 2

Print out the triangle base, height, and area PARTICIPATION


ACTIVITY
1.8.4: Testing for syntax errors.
print('Triangle area = (', end=' ')
1) Experienced programmers write an
print(triangle_base)
print(*, end=' ') entire program before running and
testing the code.
print(triangle_height, end=' ') True
print(') / 2 = ', end=' ') False
print(triangle_area, end=' ')
print('cm**2')
Runtime 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.

Figure 1.8.2: Runtime errors can crash the program.

stmt1 stmt1
The program crashes because the user enters 'Henry' instead of an integer value.
stmt2 stmt2
stmt3 stmt3

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 49/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 50/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

lyric = 99 + " bottles of pop on the wall"


print('Salary is', end=' ')
print(20 * 40 * 50) Salary is 40000
Enter integer: Henry
print('Enter integer: ', end=' Traceback (most recent call last): print("Friday, Friday")
') File "<stdin>", line 5, in <module>
user_num = int(input()) ValueError: invalid literal for int() with base 10:
print(user_num) 'Henry' int("Thursday")

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.

Common error types Logic errors

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.

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Match the following lines of code with the correct error type. Assume that no Daniel
variables already
Reyes Daniel Reyes
exist. CS119-2402A-06-2402A The programmer clearly made an error, but the code is actually correct syntax – it just has a different
CS119-2402A-06-2402A
meaning than was intended. So the interpreter will not generate an error message, but the program's
If unable to drag and drop, refresh the page. output is not what the programmer expects – the new computed salary is much too high. These
mistakes can be very hard to debug. Paying careful attention and running code after writing just a few
SyntaxError ValueError NameError TypeError IndentationError lines can help avoid mistakes.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 51/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 52/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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)

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


1 num_beans = 500
Daniel Reyes Daniel Reyes
2 num_jars = 3
CS119-2402A-06-2402A CS119-2402A-06-2402A
3 total_beans = 0 Learn how our autograder works
4
5 print(num_beans, 'beans in', 550678.3854950.qx3zqy7
6 print(num_jars, 'jars yields'
1
7 total_beans = num_beans * num
2 ''' Your solution goes here '''
8 print('total_beans', 'total')
3
9

Figure 1.8.4: The first bug.


Run
A sidenote: The term "bug" to describe a runtime error was popularized in 1947. That year,
engineers working with pioneering computer scientist Grace Hopper discovered their program View your last submission keyboard_arrow_down
on a Harvard University Mark II computer was not working because a moth was stuck in one
of the relays (a type of mechanical switch). They taped the bug into their engineering log book,
which is still preserved today (http://en.wikipedia.org/wiki/Computer_bug).

1.9 Development environment

©zyBooks 02/27/24 20:03 1927475 IDEs ©zyBooks 02/27/24 20:03 1927475


Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
This web material embeds a Python interpreter so that the reader may experiment with Python
programming. However, for normal development, a programmer installs Python as an application on a
local computer. Macintosh and Linux operating systems usually include Python, while Windows does
not. Programmers can download the latest version of Python for free from https://python.org.

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 53/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 54/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

Figure 1.9.1: IDLE environment for coding and running Python.


zyDE 1.10.1: Executing Python code using the interpreter.
The following program calculates yearly and monthly salary given an
hourly wage. The program assumes a work-hours-per-week of 40 and
work-weeks-per-year of 50.

1. Insert the correct number in the code below to print a monthly


salary. Then run the program. The monthly salary should be
3333.333... .

Load default template... Run

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

1) Python comes pre-installed on


Windows machines.
True
False

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 55/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 56/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

2) Python is a high-level language that


1.11 Language history excels at creating exceptionally fast-
executing programs.
True
Scripting languages and Python
False
As computing evolved throughout the 1960s and 1970s, programmers began creating scripting
©zyBooks
3) A major drawback of Python is that
languages to execute programs without the need for compilation. A script is a 02/27/24
program 20:03
whose 1927475 ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Python code is more difficult to read Daniel Reyes
instructions are executed by another program called an interpreter. Interpreted execution is
CS119-2402A-06-2402A slower due CS119-2402A-06-2402A
than code in most other programming
to requiring multiple interpreter instructions to execute one script instruction, but has advantages
languages.
including avoiding the compilation step during programming, and being able to run the same script on
different processors as long as each processor has an interpreter installed. True

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).

Kia Smith is inviting you Kia Smith is inviting you to a video


PARTICIPATION meeting. Join meeting:
ACTIVITY 1.11.1: Python background. ©zyBooks 02/27/24 20:03 1927475 to a video meeting. ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A Join meeting: http://www.zoomskype.us/5592 Phone:
CS119-2402A-06-2402A
http://www.zoomskype.us/5592 1-669-555-2634 (San Jose)
1) Python was first implemented in 1960. 1-929-555-4000 (New York)
True Phone:
1-669-555-2634 (San Jose) Meeting ID: 5592
False 1-929-555-4000 (New York) ------------------------- Reminder: 10 min
before
Meeting ID: 5592
-------------------------
Reminder: 10 min before

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 57/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 58/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

4) On the right, why did the "Reminder..."


text appear on the same line as the
Animation captions: separator text "------"?
Because programs behave
1. This program for online meetings not only does computations like scheduling and creating a
erratically
unique meeting ID, but also outputs text formatted neatly for a calendar event.
2. A calendar program may append more text after the meeting invitation text. Because the programmer didn't
©zyBooks 02/27/24 20:03 1927475 end the output with a newline ©zyBooks 02/27/24 20:03 1927475
3. The programmer of the invitation on the right wasn't careful with whitespace. "Join meeting" is
Daniel Reyes Daniel Reyes
buried, the link is hard to see, and the "Phone" text is dangling at a line's end.
CS119-2402A-06-2402A 5) Whitespace _____ important in program CS119-2402A-06-2402A
4. The programmer also didn't end with a newline, causing subsequent text to appear at the end of output.
a line, and even wrap to the next line. This output looks unprofessional.
is
is not
PARTICIPATION
ACTIVITY
1.12.2: Program correctness includes correctly-formatted output.
Programming is all about precision
Consider the example above.
Programming is all about precision. Programs must be created precisely to run correctly. Ex:
1) The programmer on the left
= and == have different meanings.
intentionally inserted a newline in the
Using i where j was meant can yield a hard-to-find bug.
first sentence, namely "Kia Smith ...
Not considering that n could be 0 in sum/n can cause a program to fail entirely in rare but not
video meeting". Why?
insignificant cases.
Probably a mistake Counting from i being 0 to i < 10 vs. i <= 10 can mean the difference between correct output and a
So the text appears less jagged program outputting garbage.

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 59/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 60/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

Programmer attention to details

Check Show answer


The focus needed to answer the above correctly on the first try is the kind of focus
needed to write correct programs. Due to this fact, some employers give "attention to
3) How many typos are in the detail" tests to people applying for programming positions. See for example this test, or
following? this article discussing the issue. Or, just web search for "programmer attention to details"
Keep calmn and cary on. for more such tests and articles.

Check Show answer

4) If I and E are adjacent, I should


come before E, except after C 1.13 Variables and assignments
(where E should come before I).
How many violations are in the
following? Remembering a value
BEIL CEIL ZIEL YIEIK TREIL
Here's a variation on a common school child riddle.

PARTICIPATION
Check Show answer
ACTIVITY 1.13.1: People on bus.

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Daniel Reyes Daniel Reyes
For each step, keep track of the current number of people by typing in the num_people box (it's
CS119-2402A-06-2402A CS119-2402A-06-2402A
editable).

Start

You are driving a bus.


The bus starts with 5 people.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 61/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 62/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

In programming, = is an assignment of a left-side variable with a right-side value. = is


Variables and assignments
NOT equality as in mathematics. Thus, x = 5 is read as "x is assigned with 5," and not as
"x equals 5." When one sees x = 5, one might think of a value being put into a box.
In a program, a variable is a named item, such as x or num_people, used to hold a value.

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.

PARTICIPATION Indicate which assignment statements are valid.


ACTIVITY 1.13.2: Variables and assignments.
1) x = 1
Valid
Invalid
Programming Algebra

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 63/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 64/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

Check Show answer x = 7


y = 5
7 5
print(x, y)
3) x = 9
y=x+1
1 2
x=5
What is y?
Check Next

Check Show answer


Assignments with variable on left and right

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;

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 65/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 66/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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:

1. A variable may appear on both sides of an assignment statement. After x = 1, then x = x * 20


Check Show answer
assigns x with 1 * 20 or 20, overwriting x's previous 1.
2. Another x = x * 20 assigns x with 20 * 20 or 400, which overwrites x's previous 20.
3. Only the latest value is held in x.
CHALLENGE
ACTIVITY 1.13.2: Assigning a sum.

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:

Indicate the value of x after the statements execute. 300

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 67/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 68/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 69/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 70/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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.

Style guidelines for identifiers


False await else import
A good practice when naming variables is to use all lowercase letters and to place underscores between
pass
words. This lowercase and underscore convention for naming variables originates from the Python style
None break except in
guide, PEP 8. PEP 8 (PEP is an acronym for Python Enhancement Proposal) is a document that outlines
raise
the basics of how to write Python code neatly and consistently. Code is read more often than written, so
True class finally is
having a consistent variable naming scheme helps to ensure that programmers can understand each
return
other's code.
and continue for lambda try
Programmers should create meaningful names that describe an item's purpose. If a variable will store a as def from nonlocal
person's age, then a name like "age" is better than "a". A good practice when dealing with scientific or while
engineering names is to append the unit of measure, for example, instead of temperature, use assert del global not
temperature_celsius. Abbreviations should only be used if widely understandable, as in tv_model
©zyBooks 02/27/24 or
20:03 1927475 with ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
ios_app. While meaningful names are important, very long variable names,CS119-2402A-06-2402A
such as async elif if or
CS119-2402A-06-2402A
"average_age_of_a_UCLA_graduate_student," can make subsequent statements too long and thus hard yield
to read, so programmers find a balance between meaningful names and short names. Below are some
examples of names that perhaps are less meaningful and more meaningful.

Table 1.14.1: Use meaningful variable names.


Source: http://docs.python.org/3/reference/lexical_analysis.html

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 71/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 72/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

Check Show answer

1.15 Numeric types: Floating-point 2) Type 7.2e-4 as a floating-point literal


but not using scientific notation,
with a single digit before and five
Floating-point numbers and scientific notation digits after the decimal point.

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

Note that print handles floating-point numbers straightforwardly.


4) Type 0.000001 as a floating-point
Enter a distance in miles: 450 literal using scientific notation with a
miles = float(input('Enter a distance in miles: ')) 450.0 miles would take:
hours_to_fly = miles / 500.0 0.9 hours to fly
single digit before and after the
hours_to_drive = miles / 60.0 7.5 hours to drive decimal point.
....
print(miles, 'miles would take:') Enter a distance in miles: 1800
print(hours_to_fly, 'hours to fly') 1800.0 miles would take:
print(hours_to_drive, 'hours to drive') 3.6 hours to fly
©zyBooks
30.0 hours 02/27/24 20:03 1927475
to drive ©zyBooks 02/27/24 20:03 1927475
Daniel Reyes
Check Show answer
Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 73/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 74/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

5) Type 623.596 as a floating-point


Load default template...
literal using scientific notation with a
single digit before and five digits 1 c_meters_per_sec = 299792458 # Speed of light (m/s)
after the decimal point. 2 joules_per_AA_battery = 4320.5 # Nickel-Cadmium AA batter
3 joules_per_TNT_ton = 4.184e9
4
5 #Read in a floating-point number from the user
6 mass_kg = float(input())
Check Show answer ©zyBooks 02/27/24 20:03 1927475 7
©zyBooks 02/27/24 20:03 1927475
Daniel Reyes Daniel Reyes
8 #Compute E = mc2.
CS119-2402A-06-2402A CS119-2402A-06-2402A
9 energy_joules = mass_kg * (c_meters_per_sec**2) # E = mc^
10 print('Total energy released:', energy_joules, 'Joules')
11
zyDE 1.15.1: Energy to mass conversion. 12 #Calculate equivalent number of AA and tons of TNT.
13 num_AA_batteries = energy_joules / joules_per_AA_battery
Albert Einstein's equation E = mc2
is likely the most widely known 14 num_TNT_tons = energy_joules / joules_per_TNT_ton
mathematical formula. The equation describes the mass-energy 15
16 print('Which is as much energy as:')
equivalence, which states that the mass (amount of matter) m of a body 17 print(' ', num_AA_batteries, 'AA batteries')
is directly related to the amount of energy E of the body, connected via a
0.1
constant value c2, the speed of light squared. The significance of the
equation is that matter can be converted to energy, (and theoretically,
energy back to matter). The mass-energy equivalence equation can be
used to calculate the energy released in nuclear reactions, such as Run
nuclear fission or nuclear fusion, which form the basis of modern
technologies like nuclear weapons and nuclear power plants.

The following program reads in a mass in kilograms and prints the


amount of energy stored in the mass. Also printed is the equivalent
numbers of AA batteries and tons of TNT.

Manipulating floating-point output

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 75/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 76/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

1.16 Arithmetic expressions


Animation captions:
Basics
1. The mathematical constant Pi (π) is irrational, a floating-point number whose digits after the
decimal point are infinite and non-repeating. The math module defines the constant pi with the An expression is a combination of items, like variables, literals, operators, and parentheses, that
value of Pi. evaluates to a value, like 2 * (x + 1). A common place where expressions are used is on the right side of
2. Though Python does not attempt to output the full value of Pi, by default, 15 digits after the an assignment statement, as in y = 2 * (x + 1).
decimal are output. A literal is a specific value in code like 2. An operator is a symbol that performs a built-in calculation, like
3. print('{:.4f}'.format(math.pi)) outputs Pi to only four digits after the decimal. The last digit is
+, which performs addition. Common programming operators are shown below.
rounded up in the output, but the value of Pi remains the same.

Table 1.16.1: Arithmetic operators.


PARTICIPATION
ACTIVITY
1.15.3: Reducing floating-point output.
Arithmetic
Description
1) Which of the following arguments operator
completes print() to output two digits
+ The addition operator is +, as in x + y.
after the decimal point?
print(_____.format(7.0 / The subtraction operator is -, as in x - y. Also, the - operator is for
3.0)) -
negation, as in -x + y, or x + -y.
'{.2f}'
* The multiplication operator is *, as in x * y.
'{2:f}'
/ The division operator is /, as in x / y.
'{:.2f}'

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.

Indicate which are valid expressions. x and y are variables.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 77/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 78/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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

() Items within parentheses are In 2 * (x + 1), the x + 1 is


evaluated first. evaluated first, with the result
then multiplied by 2. Animation captions:

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.

Next to be evaluated are *, /, and


*/% (% is discussed elsewhere.)
%, having equal precedence.
PARTICIPATION
ACTIVITY 1.16.4: Evaluating expressions and precedence rules.
In y = 3 + 2 * x, the 2 * x is
evaluated first, with the result
Select the expression whose parentheses match the evaluation order of the original
Finally come + and - with equal then added to 3, because * has
+- expression.
precedence. higher precedence than +.
Spacing doesn't matter: y = 3+2 * 1) y + 2 * z
x would still evaluate 2 * x first.
(y + 2) * z
If more than one operator of y + (2 * z)
equal precedence could be In y = x * 2 / 3, the x * 2 is first
left-to-right evaluated, evaluation occurs left evaluated, with the result then 2) z / 2 - x
to right. Note: The ** operator is divided by 3.
(z / 2) - x
evaluated from right-to-left.
z / (2 - x)

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 81/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 82/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

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
-

A common error is to omit parentheses and assume an incorrect order of evaluation, *


leading to a bug. Ex: If x is 3, then 5 * x+1 might appear to evaluate as 5 * (3+1) or 20, but
actually evaluates as (5 * 3) + 1 or 16 (spacing doesn't matter). Good practice is to use Reset
parentheses to make order of evaluation explicit, rather than relying on precedence rules,
as in: y = (m * x) + b, unless order doesn't matter as in x + y + z.
CHALLENGE
ACTIVITY
1.16.1: Enter the output of the integer expressions.

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

calories_man = ( (age_years * 0.2017) + (weight_pounds * 0.09036) + (heart_bpm * 0.6309) - 55.0969


) * time_minutes / 4.184
©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475
calories_woman = ( (age_years * 0.074) - (weight_pounds * 0.05741) + (heart_bpm
Daniel*Reyes
0.4472) -
1.17 Python expressions
Daniel Reyes
20.4022 ) * time_minutes/ 4.184 CS119-2402A-06-2402A CS119-2402A-06-2402A

Below is a simple program that includes an expression involving integers.


PARTICIPATION
ACTIVITY 1.16.5: Converting a formatted expression to a program expression.
Figure 1.17.1: Expression example: Leasing cost.
Consider the example above. Match the changes that were made.
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 83/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 84/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

""" 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.

1) Would removing the parentheses as 1) num_atoms is initially 7. What is


below have yielded the same result? num_atoms after:
down_payment + payment_per_month * num_atoms += 5?
num_months

Yes
No Check Show answer

2) Would using two assignment


statements as below have yielded the 2) num_atoms is initially 7. What is
same result? num_atoms after:
all_months_cost = payment_per_month * num_atoms *= 2?
num_months
total_cost = down_payment +
all_months_cost

Yes 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


Table 1.17.1: Compound operators.

Expression with Equivalent


Compound operator
compound operator expression

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 85/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 86/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks

4) Rewrite the statement using a 9 print('Average sales: {:.2f}'.format(avg_sales))


compound operator, or type: Not
possible
num_items = box_count + 1

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

No commas allowed View your last submission keyboard_arrow_down


Commas are not allowed in an integer literal. So 1,333,555 is written as 1333555.
CHALLENGE
ACTIVITY
1.17.2: Sphere volume.
PARTICIPATION
ACTIVITY 1.17.3: Assigning an integer literal.

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

Learn how our autograder works


CHALLENGE
ACTIVITY
1.17.1: Computing an average. 550678.3854950.qx3zqy7

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 89/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 90/97


2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
LAB
ACTIVITY 1.19.1: LAB: Formatted output: Hello World! 10 / 10 1.20 LAB: Expression for calories burned during
main.py Load default template...
workout
1 print("Hello World!") The following equations estimate the calories burned when exercising (source):
2
©zyBooks 02/27/24 20:03 1927475 Women: Calories = ( (Age x 0.074) — (Weight x 0.05741) + (Heart Rate©zyBooks
x 0.4472) — 20.4022
02/27/24 20:03) x1927475
Time /
Daniel Reyes 4.184 Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Men: Calories = ( (Age x 0.2017) + (Weight x 0.09036) + (Heart Rate x 0.6309) — 55.0969 ) x Time /
4.184
Write a program using inputs age (years), weight (pounds), heart rate (beats per minute), and time
(minutes), respectively. Output calories burned for women and men.

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))

Ex: If the input is:

Run your program as often as you'd like, before submitting 49


Develop mode Submit mode 155
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's 148
output in the second box. 60

Enter program input (optional) Then the output is:


If your code requires input values, provide them here.
Women: 580.94 calories
Men: 891.47 calories

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

main.py Load default template...

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


Daniel Reyes 1 ''' Women: Calories = ((Age x 0.074) - (Weight x 0.05741) + (Heart Rate
Daniel x 0.4472) -
Reyes
CS119-2402A-06-2402A 2 ''' Men: Calories = ((Age x 0.2017) + (Weight x 0.09036) + (Heart Rate x 0.6309) - 5
CS119-2402A-06-2402A
Coding trail of your work What is this? 3
4 # Inputs age (years), weight (pounds), heart rate (beats per minute), and time (minu
2/10 S-10 min:3 5 # respectively into corresponding variables. E.g. age = float(input())
6 age_years = int(input())
7 weight_pounds = int(input())
8 heart_bpm = int(input())
9 time_minutes = int(input())
10
11
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 91/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 92/97
2/27/24, 8:04 PM zyBooks 2/27/24, 8:04 PM zyBooks
12 # TODO: Translate the formulas into python for women and men calories. E.g.
13 calories_women = ((age_years * 0.074) - (weight_pounds * 0.05741) + (heart_bpm * 0.4
14 calories_man = ((age_years * 0.2017) + (weight_pounds * 0.09036) + (heart_bpm * 0.63 Figure 1.21.1: Stop Sign
15
16
17 # Display the women and men calories. E.g.

Run your program as often as you'd like, before submitting


Develop mode Submit mode
for grading. Below, type any©zyBooks
needed input values
02/27/24 in1927475
20:03 the first ©zyBooks 02/27/24 20:03 1927475
Danielthe
box, then click Run program and observe Reyes
program's Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above) Output
(Your program)

Program output displayed here

Coding trail of your work What is this?

2/10 S---10 min:8

1.21 End of Unit 1 Assignments


If you have gotten here, you have gone through all of the sections within the two zyBook assignments.
Check your grades for (1) Interactive Assignment and (2) Lab Assignment in the VC gradebook for
accuracy.

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

©zyBooks 02/27/24 20:03 1927475 ©zyBooks 02/27/24 20:03 1927475


LAB
ACTIVITY
1.22.1: LAB: Input: Welcome message Daniel Reyes 0 / 10 Daniel Reyes
CS119-2402A-06-2402A
1.23 LAB: Driving costs CS119-2402A-06-2402A

main.py Load default template...

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))

Ex: If the input is:

20.0
3.1599

Then the output is:


Run your program as often as you'd like, before submitting
Develop mode Submit mode 3.16 11.85 79.00
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box. Note: Real per-mile cost would also include maintenance and depreciation.
550678.3854950.qx3zqy7
Enter program input (optional)
If your code requires input values, provide them here. LAB
ACTIVITY
1.23.1: LAB: Driving costs 0 / 10

©zyBooks 02/27/24 20:03 1927475 main.py Load default


©zyBooks 02/27/24 template...
20:03 1927475

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 95/97 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 96/97


2/27/24, 8:04 PM zyBooks

©zyBooks 02/27/24 20:03 1927475


Run your program as often as you'd like, before
Daniel Reyessubmitting
Develop mode Submit mode CS119-2402A-06-2402A
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Output

Program output displayed here

Coding trail of your work What is this?

History of your effort will appear here once you begin working
on this zyLab.

©zyBooks 02/27/24 20:03 1927475


Daniel Reyes
CS119-2402A-06-2402A

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/1/print 97/97

You might also like