Murach's: Python
Murach's: Python
murach’s
Python
programming
2nd Edition
(Chapter 2)
Thanks for downloading this chapter from Murach’s Python Programming (2nd
Edition). We hope it will show you how easy it is to learn from any Murach book, with
its paired-pages presentation, its “how-to” headings, its practical coding examples, and
its clear, concise style.
To view the full table of contents for this book, you can go to our website. From there,
you can read more about this book, you can find out about any additional downloads that
are available, and you can review our other books on related topics.
Thanks for your interest in our books!
“This is not only a book to learn Python but also a guide to refer to whenever
I face a Python problem. What I really like is that it is very well-organized
and easy to follow, and it does not make you bored by providing unnecessary
details.”
Posted at an online bookseller
“The material in the book itself is worth 6 stars [out of 5]. It’s second to none
in its quality.”
Posted at an online bookseller
“This is now my third text book for Python, and it is the ONLY one that
has made me feel comfortable solving problems and reading code. The
paired-pages approach is fantastic, and it makes learning the syntax, rules,
and conventions understandable for me.”
Posted at an online bookseller
“[Look at the contents] and see where they put testing/debug: Chapter 5. I
love the placement! Folks going through the book get Python installed, receive
positive returns with some basic code, and then take a breather with testing/
debugging before more complex things come their way.”
Jeremy Johnson, DreamInCode.net
“Murach’s Rocks: Murach’s usual excellent coverage with examples that are
actually practical.”
Posted at an online bookseller
2
How to write your first
programs
The quickest and best way to learn Python programming is to do Python
programming. That’s why this chapter shows you how to write complete Python
programs that get input, process it, and display output. When you finish this
chapter, you’ll have the skills for writing comparable programs of your own.
counter = 0
score_total = 0
test_score = 0
An indentation error
print("Total Score: " + str(score_total))
print("Average Score: " + str(average_score))
Explicit continuation
print("Total Score: " + str(score_total) \
+ "\nAverage Score: " + str(average_score))
Coding rules
•• Python relies on proper indentation. Incorrect indentation causes an error.
•• The standard indentation is four spaces whenever it is required.
•• With implicit continuation, you can divide statements after parentheses, brackets,
and braces, and before or after operators like plus or minus signs.
•• With explicit continuation, you can use the \ character to divide statements
anywhere on a line.
Description
•• A statement performs a task. Each statement must be indented properly.
•• A program typically starts with a shebang line that begins with a hash (#) symbol
followed by a bang (!) symbol. This line identifies the interpreter to use when
running the program.
•• If you’re using IDLE to run your programs, you don’t need a shebang line.
However, it’s generally considered a good practice to include one.
# get scores
while test_score != 999: Inline comments
test_score = int(input("Enter test score: "))
if test_score >= 0 and test_score <= 100:
score_total += test_score # add score to total
counter += 1 # add 1 to counter
Description
• Comments start with the # sign, and they are ignored by the compiler. Block
comments are coded on their own lines. Inline comments are coded after statements
to describe what they do.
• Comments are used to document what a program or portion of code does. This can
be helpful not only to the programmer who creates the program, but also to those
who maintain the program later on.
• Comments can also be used to comment out statements so they aren’t executed
when the program is tested. Later, the statements can be uncommented so the
statements will be executed when the program is tested. This can be helpful when
debugging.
• When you’re using IDLE, you can use the Format menu to comment out and to
uncomment the statements that you’ve selected.
Goodbye!
Description
•• A function is a reusable unit of code that performs a specific task.
•• Python provides many built-in functions that do common tasks like getting input
data from the user and printing output data to the console.
•• When you call a function, you code the name of the function followed by a pair
of parentheses. Within the parentheses, you code any arguments that the function
requires, and you separate multiple arguments with commas.
•• In a syntax summary like the one at the top of this page, brackets [ ] mark the
portions of code that are optional. And the italicized portions of the summary are
the ones that you have to supply.
•• In this chapter, you’ll learn to use the print() function plus five other functions.
Description
•• A variable can change, or vary, as code executes.
•• A data type defines the type of data for a value.
•• An assignment statement uses the equals sign (=) to assign a value to a variable. The
value can be a literal value, another variable, or an expression like the arithmetic
expressions in the next figure.
•• To initialize a variable, you assign an initial value to it. Then, you can assign
different values later in the program.
•• You can assign a value of any data type to a variable, even if that variable has
previously been assigned a value of a different data type.
•• Because variable names are case-sensitive, you must be sure to use the correct case
when coding the names of variables.
Python keywords
and except lambda while
as False None with
assert finally nonlocal yield
break for not
class from or
continue global pass
def if raise
del import return
elif in True
else is try
Description
•• When naming variables, you must follow the rules shown above. Otherwise, you’ll
get errors when you try to run your code.
•• It’s also a best practice to follow the naming recommendations shown above. This
makes your code easier to read, maintain, and debug.
•• With underscore notation, all letters are lowercase with words separated by
underscores. This can also be referred to as snake case.
•• With camel case, the first word is lowercase and subsequent words start with a
capital letter.
Description
•• An arithmetic expression consists of one or more operands that are operated upon
by arithmetic operators.
•• You don’t have to code spaces before and after the arithmetic operators.
•• When an expression mixes integer and floating-point numbers, Python converts the
integers to floating-point numbers.
•• If you use multiple operators in one expression, you can use parentheses to clarify
the sequence of operations. Otherwise, Python applies its order of precedence.
Description
•• Besides the assignment operator (=), Python provides for compound assignment
operators. These operators are a shorthand way to code common assignment
operations.
•• Besides the compound operators in the table, Python offers /=, //=, %=, and **=.
•• When working with floating-point numbers, be aware that they are approximations,
not exact values. This can cause inaccurate results.
Description
•• The Python interactive shell that you learned about in chapter 1 is an excellent tool
for learning more about the way numeric operations work. For example, you can
use it to test assigning numeric literals and arithmetic expressions to variables.
•• To see how numeric statements work, just enter a statement or series of statements
and see what the results are.
•• This type of testing will give you a better idea of what’s involved as you work with
integer and floating-point numbers. It will also show your errors when you enter a
statement incorrectly so you will learn the proper syntax as you experiment.
Figure 2-8 How to use the interactive shell for testing numeric operations
44 Section 1 Essential concepts and skills
With an f-string
name = f"{last_name}, {first_name}" # name is "Smith, Bob"
With an f-string
message = f"{name} is {age} years old." # str() function not needed
With an f-string
print(f"Name: {name}\n"
f"Age: {age}")
Description
•• A string can consist of one or more characters, including letters, numbers, and
special characters like *, &, and #.
•• To specify the value of a string, you can enclose the text in either double or single
quotation marks. This is known as a string literal.
•• To assign an empty string to a variable, you code a set of quotation marks with
nothing between them. This means that the string doesn’t contain any characters.
•• To join strings, you can use the + operator or an f-string. To use an f-string, you
code an f before a string literal. Then, you use braces ({}) to identify the variables
to insert into the string literal.
Figure 2-9 How to assign strings to variables and how to join strings
46 Section 1 Essential concepts and skills
Description
•• Within a string, you can use escape sequences to include certain types of special
characters such as new lines and tabs. You can also use escape characters to include
special characters such as quotation marks and backslashes.
•• Another way to include quotation marks in a string is to code single quotes within a
string that’s in double quotes, or vice versa.
Description
•• The Python interactive shell that you learned about in chapter 1 is an excellent
tool for learning more about the way string operations work. For example, you can
use it to test assigning strings to variables, joining strings, and including special
characters in strings.
•• To see how string statements work, just enter a statement or series of statements
and see what the results are. This will also show your errors when you enter a
statement incorrectly so you will learn the proper syntax as you experiment.
Figure 2-11 How to use the interactive shell for testing string operations
50 Section 1 Essential concepts and skills
Description
•• The print() function can accept one or more data arguments.
•• If you pass a series of arguments to the print() function, numbers don’t have to be
converted to strings.
•• If you pass just one string as the argument for a print() function, numbers have to
be converted to strings within the string argument.
•• In a syntax summary, an argument that begins with a name and an equals sign (=) is
a named argument. To pass a named argument to a function, you code the name of
the argument, an equals sign (=), and the value of the argument.
•• The print() function provides a sep argument that can change the character that’s
used for separating the strings from one space to something else.
•• The print() function also provides an end argument that can change the ending
character for a print() function from a new line character (\n) to something else.
The console
Enter your first name: Mike
Hello, Mike!
The console
What is your first name?
Mike
Hello, Mike!
Description
•• You can use the input() function to get user input from the console. Typically, you
assign the string that’s returned by this function to a variable.
•• The input() function always returns string data, even if the user enters a number.
Description
•• If you try to perform an arithmetic operation on a string, an exception occurs. To fix
that, you can use the int() and float() functions.
•• When you chain functions, you code one function as the argument of another
function. This is a common coding practice.
Figure 2-14 How to use the int(), float(), and round() functions
56 Section 1 Essential concepts and skills
The console
The Miles Per Gallon program
Bye!
The code
#!/usr/bin/env python3
# display a title
print("The Miles Per Gallon program")
print()
Description
•• This program uses many of the features presented in this chapter.
•• The input() function is chained with the float() function to convert the user entries
from str values to float values.
•• This round() function rounds the result of the calculation to 2 decimal places.
•• If the user enters a non-numeric value such as “sixty”, this program will crash
and display an exception to the console. That’s because the input entry can’t be
converted to a float value. You’ll learn how to fix an exception like that in chapter 8.
The console
The Test Scores program
Bye!
The code
#!/usr/bin/env python3
# display a title
print("The Test Scores program")
print()
print("Enter 3 test scores")
print("======================")
Description
•• This program shows how you can use a variable named total_score to accumulate
the total for a series of entries. In this case, the program doesn’t store the individual
scores in variables. Instead, it just adds them to the total_score variable.
•• If the user doesn’t enter a valid integer for each test score, this program will crash
and display an exception on the console. You’ll learn how to fix that in chapter 8.
Perspective
The goal of this chapter has been to get you started with Python
programming and to get you started fast. Now, if you understand the Miles Per
Gallon and Test Scores programs, you’ve come a long way. You should also be
able to write comparable programs of your own.
Keep in mind, though, that this chapter is just an introduction to Python
programming. So in the next chapter, you’ll learn how to code the control
statements that drive the logic of your programs. This will take your programs
to another level.
Terms
statement string literal
implied continuation numeric literal
explicit continuation multiple assignment
shebang line case-sensitive
comment keyword
block comment underscore notation
inline comment snake case
comment out camel case
uncomment arithmetic expression
built-in function operand
function arithmetic operator
call a function modulo operator
argument remainder operator
data type exponentiation operator
string order of precedence
str data type compound assignment operator
integer empty string
int data type concatenate
floating-point number join
float data type f-string
variable escape sequence
assignment statement named argument
assignment operator prompt
initialize a variable chain functions
literal
Chapter 2 How to write your first programs 61
Summary
•• A Python statement has a simple syntax that relies on indentation. A
statement can be continued by using implicit continuation.
•• Python comments can be block or inline. Comments can also be used to
comment out portions of code so they won’t be executed. Later, the code can
be uncommented and executed.
•• Python provides many built-in functions that you can call in your programs.
When you call a function, you can include any arguments that are used by
the function.
•• Python variables are used to store data that changes as a program runs, and
you use assignment statements to assign values to variables. Variable names
are case-sensitive, and they are usually coded with underscore notation, also
called snake case, or camel case.
•• You can use multiple assignment to assign values to more than one variable
using a single statement.
•• The str, int, and float data types store values for strings, integers, and
floating-point numbers.
•• When you assign a value to a numeric variable, you can use arithmetic
expressions that include arithmetic operators, variable names, and numeric
literals.
•• When you assign a value to a string variable, you can use the + operator or
an f-string to join variables and string literals. Within a string literal, you can
use escape sequences to provide special characters.
•• The print() function prints output to the console, and the input() function
gets input from the console. The str(), int(), and float() functions convert data
from one data type to another. And the round() function rounds a number to
the specified number of decimal places.
•• To chain functions, you code one function as the argument of another
function. This is a common coding practice.
62 Section 1 Essential concepts and skills
If you have any problems when you test your changes, please refer to figure 1-9
of the last chapter, which shows how to fix syntax and runtime errors.
1. Start IDLE and open the mpg.py file that should be in this folder:
python/exercises/ch02
2. Press F5 to compile and run the program. Then, enter valid values for miles
driven and gallons used. This should display the miles per gallon in the
interactive shell.
3. Test the program with invalid entries like spaces or letters. This should cause
the program to crash and display error messages for the exceptions that occur.
4. Modify this program so the result is rounded to just one decimal place. Then,
test this change.
5. Modify this program so the argument of the round() function is the arithmetic
expression in the previous statement. Then, test this change.
6. Modify this program so it gets the cost of a gallon of gas as an entry from the
user. Then, calculate the total gas cost and the cost per mile, and display the
results on the console as shown above.
Chapter 2 How to write your first programs 63
If you have any problems when you test your changes, please refer to figure 1-9
of the last chapter, which shows how to fix syntax and runtime errors.
1. Start IDLE and open the test_scores.py file that should be in this folder:
python/exercises/ch02
2. Press F5 to compile and run the program. Then, enter valid values for the
three scores. This should display the results in the interactive shell.
3. Modify this program so it saves the three scores that are entered in variables
named score1, score2, and score3. Then, add these scores to the total_score
variable, instead of adding the entries to the total_score variable without ever
saving them.
4. Display the scores that have been entered before the other results, as shown
above.
64 Section 1 Essential concepts and skills
Area = 250
Perimeter = 70
Bye!
1. Start IDLE and open the mpg_model.py file that is in this folder:
python/exercises/ch02
Then, before you do anything else use the FileSave As command to save the
file as rectangle.py.
2. Modify the code for this program so it works for the new program. Remember
that the area of a rectangle is just length times width, and the perimeter is 2
times length plus 2 times width.
100% Guarantee
When you buy directly from us, you must be
satisfied. Try our books for 30 days or our eBooks
for 14 days. They must outperform any competing
book or course you’ve ever tried, or return your
purchase for a prompt refund.…no questions asked.