Python Turorail 4
Python Turorail 4
2
Program with three comments
1
# Display the menu options
2 print("Lunch Menu")
3 print("----------")
4 print("Burrito")
5 print("Enchilada")
6 print("Taco")
7 print("Salad")
8 print()
# End of menu
9
10
# Get the user's preferences
11 item1 = input("Item #1: ")
12 item2 = input("Item #2: ")
CONCEPTS IN PRACTICE
Simple comments
1. The main purpose of writing comments is to _____.
a. avoid writing syntax errors
b. explain what the code does
c. make the code run faster
2. Which symbol is used for comments in Python?
a. #
b. /*
c. //
3. Which comment is formatted correctly?
a. 0 spaces:
#Get the user input
b. 1 space:
# Get the user input
c. 2 spaces:
# Get the user input
Code quality
The example program above had two parts: (1) display the menu options, and (2) get the user's
preferences.
Together, the blank lines and comments show the overall structure of the program.
Programmers spend more time reading code than writing code. Therefore, making code easier
for others to
read and understand is important. Two ways to improve code quality include:
• Separate each part (lines that have a similar purpose) with a blank line.
28 1 • Statements
Access for free at openstax.org
• Write a comment before each part. Not every line needs a comment.
CHECKPOINT
Comments in a program
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
1-7-comments)
CONCEPTS IN PRACTICE
Code quality
4. Which comment is most useful for the following code?
print("You said:", adj1 + " " + noun1)
a.
# Append adj1 and noun1
b.
# Print out a bunch of stuff
c.
# Show the resulting phrase
5. Where should a blank line be inserted?
1 name = input("Whose birthday is today? ")
2 print("Happy birthday to", name)
3 print("Everyone cheer for", name)
a. After line 1
b. After line 2
c. After line 3
6. To temporarily prevent a line from being run, one might . . .
a. introduce a syntax error in the line.
b. remove the line from the program.
c. insert a # at the beginning of the line.
Documentation
Python programs may optionally begin with a string known as a docstring. A docstring is
documentation
written for others who will use the program but not necessarily read the source code. Most of
the official
documentation at docs.python.org (https://openstax.org/r/100docstrings) is generated from
docstrings.
Documentation can be long, so docstrings are generally written as multi-line strings (""").
Common
elements of a docstring include a one-line summary, a blank line, and a longer description.
CHECKPOINT
Vacations docstring
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
1-7-comments)
1.7 • Comments 29
CONCEPTS IN PRACTICE
Documentation
7. The main purpose of writing docstrings is to . . .
a. summarize the program's purpose or usage.
b. explain how each part of the code works.
c. maintain a list of ideas for new features.
8. Which of the following is NOT a docstring?
a. """Vacations Madlib."""
b. """Vacations Madlib. This program asks the user for two adjectives
and two
nouns, which are then used to print a funny story about a vacation.
"""
c.
# Vacations Madlib.
#
# This program asks the user for two adjectives
# and two nouns, which are then used to print
# a funny story about a vacation.
9. Which docstring is most useful for this program?
a. """Vacations Madlib."""
b. """Vacations Madlib. This program asks the user for two adjectives
and two
nouns, which are then used to print a funny story about a vacation.
"""
c. """Vacations Madlib. This program asks the user for two adjectives
and two
nouns, which are then used to print a funny story about a vacation.
The code
uses four variables to store the user input: two for the adjectives,
and two
for the nouns. The output is displayed on seven lines, beginning with
a blank
line after the input. """
TRY IT
Whose birthday
Add two comments to the following program: one for the input, and one for the output. Separate
the input
and output with a blank line. Then, compare your comments with the sample solution, and ask
yourself the
following questions:
• Are your comments longer or shorter? Why?
• Is the formatting of your comments correct?
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
1-7-comments)
TRY IT
Gravity calculation
Write a docstring for the following program. The first line of the docstring should explain, in one
short
30 1 • Statements
Access for free at openstax.org
sentence, what the program is. The second line of the docstring should be blank. The third and
subsequent
lines should include a longer explanation of what the program does. At the end of the docstring,
add a line
that says "Author: " followed by your name.
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
1-7-comments)
1.8 Why Python?
Learning objectives
By the end of this section you should be able to
• Name two historical facts about how Python was first created.
• Describe two ways Python is considered a popular language.
Historical background
Python has an interesting history. In 1982, Guido van Rossum
(https://openstax.org/r/100vanRossum), the
creator of Python, started working at CWI (https://openstax.org/r/100CWI), a Dutch national
research institute.
He joined a team that was designing a new programming language, named ABC, for teaching
and prototyping.
ABC's simplicity was ideal for beginners, but the language lacked features required to write
advanced
programs.
Several years later, van Rossum joined a different team at CWI working on an operating system.
The team
needed an easier way to write programs for monitoring computers and analyzing data.
Languages common in
the 1980's were (and still are) difficult to use for these kinds of programs. van Rossum
envisioned a new
language that would have a simple syntax, like ABC, but also provide advanced features that
professionals
would need.
At first, van Rossum started working on this new language as a hobby during his free time. He
named the
language Python because he was a fan of the British comedy group Monty Python
(https://openstax.org/r/
100MontyPython). Over the next year, he and his colleagues successfully used Python many
times for real
work. van Rossum eventually decided to share Python with the broader programming
community online. He
freely shared Python's entire source code so that anyone could write and run Python programs.
Python's first release, known as Version 0.9.0, appeared in 1991, about six years after C++ and
four years
before Java. van Rossum's decisions to make the language simple yet advanced, suitable for
everyday tasks,
and freely available online contributed to Python's long-term success.
CHECKPOINT
Key decisions
Access multimedia content
(https://openstax.org/books/introduction-python-programming/pages/1-8-why-
python)
CONCEPTS IN PRACTICE
Python history
1. The Python programming language was named after a _____.
1.8 • Why Python? 31
a. British comedy group
b. Dutch programmer
c. non-venomous snake
2. Which programming language came first?
a. Java
b. Python
3. Which sentence best describes the beginning of Python?
a. CWI hired Guido van Rossum to design a new programming language to compete with C++.
b. Python started out as a hobby and became open source after several years of development.
c. van Rossum posted Python's source code online after working on the language for one year.
EXPLORING FURTHER
For more details about Python's history, see "A brief history of Python
(https://openstax.org/r/100history)"
by Vasilisa Sheromova, and "History and Philosophy of Python
(https://openstax.org/r/100sheromova)" by
Bernd Klein.
Popularity of Python
Over the years, Python has become a nonprofit organization with a thriving community. Millions
of
programmers around the world use Python for all kinds of interesting projects. Hundreds of
thousands of
Python libraries have been released as open source software. The Python community is very
active and
supportive online, answering questions and sharing code.
One way to see Python's popularity is the TIOBE index (https://openstax.org/r/100TIOBE).
TIOBE is a Dutch
company that provides products and services for measuring software code quality. Since 2001,
TIOBE has
tracked the popularity of programming languages and posted the results online. Figure 1.2
shows the TIOBE
index over time for five of the most popular languages.
The TIOBE index is based on the number of search engine results for each language. The
percentage refers to
how many results belong to that language. Python has been among the top 10 languages every
year since
2004. In October 2021, Python became the #1 language on the TIOBE index. No other
language but C and Java
had been #1 for the previous 20 years.
Another way to see Python's popularity is to analyze how frequently Python is discussed online.
Stack Overflow
(https://openstax.org/r/100overflow) is a question-and-answer website for programmers. Figure
1.3 shows the
number of questions asked each month that were tagged with Python, JavaScript, and so forth.
In recent
years, Python has become the most asked about language in programming forums.
32 1 • Statements
Access for free at openstax.org
Figure 1.2 TIOBE programming community index. Source: www.tiobe.com
(https://www.tiobe.com/tiobe-index/)
Figure 1.3 Stack Overflow questions per month. Source: data.stackexchange.com
(https://data.stackexchange.com/)
CONCEPTS IN PRACTICE
Python popularity
4. According to the TIOBE Index, which two languages were most popular from 2001 to 2021?
1.8 • Why Python? 33
a. C and C++
b. Java and C
c. Python and JavaScript
5. In what year did Python become the most asked about language on Stack Overflow?
a. 2018
b. 2019
c. 2020
6. How long has TIOBE been tracking programming language popularity?
a. since 1991
b. since 2001
c. since 2015
1.9 Chapter summary
This chapter introduced the basics of programming in Python, including:
• print() and input().
• Variables and assignment.
• Strings, integers, and floats.
• Arithmetic, concatenation.
• Common error messages.
• Comments and docstrings.
At this point, you should be able to write programs that ask for input, perform simple
calculations, and output
the results. The programming practice below ties together most topics presented in the chapter.
Function Description
print(values) Outputs one or more values, each separated by a space, to the user.
input(prompt)
If present, prompt is output to the user. The function then reads a line of input from the
user.
len(string) Returns the length (the number of characters) of a string.
type(value) Returns the type (or class) of a value. Ex: type(123) is <class 'int'>.
Operator Description
=
(Assignment)
Assigns (or updates) the value of a variable. In Python, variables begin to exist when
assigned for the first time.
Table 1.6 Chapter 1 reference.
34 1 • Statements
Access for free at openstax.org
Function Description
+
(Concatenation) Appends the contents of two strings, resulting in a new string.
+
(Addition) Adds the values of two numbers.
-
(Subtraction) Subtracts the value of one number from another.
*
(Multiplication) Multiplies the values of two numbers.
/
(Division) Divides the value of one number by another.
**
(Exponentiation) Raises a number to a power. Ex: 3**2 is three squared.
Syntax Description
#
(Comment) All text is ignored from the # symbol to the end of the line.
' or "
(String)
Strings may be written using either kind of quote. Ex: 'A' and "A" represent the same
string. By convention, this book uses double quotes (") for most strings.
"""
(Docstring)
Used for documentation, often in multi-line strings, to summarize a program's purpose
or usage.
Table 1.6 Chapter 1 reference.
TRY IT
Fun facts
Write a program that assigns a variable named number to any integer of your choice. Ex:
number = 74.
Then, use this variable to calculate and outpu