Text stringlengths 1 9.41k |
|---|
That is, they accept some
argument or arguments, and return a result, behaving like a black box
with no interaction with anything outside the box. |
Example:
```
def successor(n):
return n + 1
```
In this case, there’s an argument, a simple calculation, and the result
is returned. |
This is pure, in that there’s nothing changed outside the
function and there’s no observable behavior of the function other than
returning the result. |
This is just like the mathematical function
𝑠(𝑛) = 𝑛+ 1.
###### Impure functions
Sometimes it’s useful to implement an impure function. An impure function is one that has side effects. |
For example, we might want to write a
function that prompts the user for an input and then returns the result.
```
def get_price():
while True:
price = float(input("Enter the asking price "
"for the item you wish "
"to sell: $"))
if price > 1.00:
break
... |
That is, we can
observe behavior in this function other than its return value. |
It does
return a value, but it exposes other behaviors as well.
###### Keep side effects to a minimum
Always, always consider what side effects your functions have, and
whether such side effects are correct and desirable.
As a rule, it’s best to keep side effects to a minimum (eliminating
them entirely if possible). |
But sometimes it is appropriate to rely on side
effects. Just make sure that if you are relying on side effects, that it is
correct and by design, and not due to a defect in programming. |
That is,
if you write a function with side effects, it should be because you choose
_to do so and you understand how side effects may or may not change the_
_state of your program. |
It should always be a conscious choice and never_
inadvertent, otherwise you may introduce bugs into your program. |
For
example, if you inadvertently mutate a mutable object, you may change
the state of your program in ways you have not anticipated, and your
program may exhibit unexpected and undesirable behaviors.
We will take this topic up again, when we get to mutable data types
like list and dict in Chapters 10 and 16.
###### C... |
Write an impure function which produces a side effect, but returns
```
None.
```
2. |
Write a pure function which performs a simple calculation and
returns the result.
###### 5.6 The math module
We’ve seen that Python provides us with quite a few conveniences “right
out of the box.” Among these are built-in functions, that we as programmers can use—and reuse—in our code with little effort. |
For example,
```
print(), and there are many others.
```
We’ve also learned about how to define constants in Python. |
For example, Newton’s gravitational constant:
```
G = 6.67 * 10 ** -11 # N m^2 / kg^2
```
Here we’ll learn a little about Python’s math module. |
The Python math
module is a collection of constants and functions that you can use in your
own programs—and these are very, very convenient. |
For example, why
-----
write your own function to find the principal square root of a number
when Python can do it for you?[10]
Unlike built-in functions, in order to use functions (and constants)
provided by the Python math module, we must first import the module
(or portions thereof).[11] You can think of this as... |
It provides many functions
including
function calculation
`sqrt(x)` √𝑥
`exp(x)` 𝑒[𝑥]
`log(x)` ln 𝑥
`log2(x)` log
2 𝑥
`sin(x)` sin 𝑥
`cos(x)` cos 𝑥
and many others.
###### Using the math module
To import a module, we use the import keyword. |
Imports should appear
in your code immediately after the starting docstring, and you only need
to import a module once. |
If the import is successful, then the imported
module becomes available.
```
>>> import math
```
Now what? Say we’d like to use the sqrt() function provided by the
```
math module. |
How do we access it?
```
If we want to access functions (or constants) within the math module
we use the . operator.
```
>>> import math
>>> math.sqrt(25)
5.0
```
Let’s unpack this. |
Within the math module, there’s a function named
```
sqrt(). Writing math.sqrt() is accessing the sqrt() function within the
math module. |
This uses what is called dot notation in Python (and many
```
other languages use this as well).
Let’s try another function in the math module, sin(), which calculates
the sine of an angle. |
You may remember from pre-calculus or trigonometry course that sin 0 = 0, sin [𝜋]2 [= 1][, sin][ 𝜋= 0][, sin][ 3𝜋]2 [= −1][, and sin][ 2𝜋= 0][.]
Let’s try this out.
10The only reasonable answer to this question is “for pedagogical purposes”, and
in fact, later on, we’ll do just that—write our own function to fin... |
But let’s set that aside for now.
11We’re going to ignore the possibility of importing portions of a module for now.
-----
```
>>> import math
>>> PI = 3.14159
>>> math.sin(0)
0.0
```
So far, so good.
```
>>> math.sin(PI / 2)
0.999999998926914
```
That’s close, but not quite right. |
What went wrong? (Hint: Representation error is not the problem.) Our approximation of 𝜋 (defined as
```
PI = 3.14159, above) isn’t of sufficient precision. |
Fortunately, the math
```
module includes high-precision constants for 𝜋 and 𝑒.
```
>>> math.sin(math.pi / 2)
1.0
```
Much better.
It is left to the reader to test other arguments to the sin() function.
```
math module documentation
```
As noted, the math module has many ready-made functions you can use.
For m... |
We’ve seen when defining a function that the body of the function must be indented (we’ll see other uses of indentation soon).
An exception of type `IndentationError is raised if Python dis-`
agrees with your use of indentation—typically if indentation is expected
and your code isn’t, or if a portion of your code is ov... |
return n * n
File "<stdin>", line 2
return n * n
^
IndentationError: expected an indented block after function
definition on line 1
```
-----
```
>>> def square(n):
... |
return n * n # now it's correctly indented!
...
>>> square(4)
16
ValueError
```
A ValueError is raised when the type of an argument or operand is valid,
but the value is somehow unsuitable. |
We’ve seen how to import the math
module and how to use math.sqrt() to calculate the square root of some
number. |
However, math.sqrt() does not accept negative operands (it
doesn’t know about complex numbers), and so, if you supply a negative
operand to math.sqrt() a ValueError is raised.
Example:
```
>>> import math
>>> math.sqrt(4) # this is A-OK
2.0
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<stdin>... |
Identify
the problem and suggest a fix.
a. Function to cube any real number.
```
def cube:
return x ** 3
```
b. Function to print someone’s name.
```
def say_hello():
print(name)
```
c. |
Function to calculate 𝑥[2] + 3𝑥−1 for any real valued 𝑥.
```
def poly(x):
return x ** 2 + 3 * x - 1
```
d. |
Function which takes some number, 𝑥, subtracts 1, and returns the
result.
```
def subtract_one(x):
y = x - 1
```
**Exercise 03**
Write a function which takes any arbitrary string as an argument and
prints the string to the console.
-----
**Exercise 04**
Write a function which takes two numeric arguments (f... |
Write a function which take an integer as an argument and returns 0
if the integer is even and 1 if the integer is odd. |
Hint: The remainder
(modulo) operator, %, calculates the remainder when performing
integer division. For example, 17 % 5 yields 2, because 5 goes into
17 three times, leaving a remainder of two.
b. |
What did you name your function and why?
**Exercise 06**
Write a function which takes two numeric arguments, one named
```
subtotal and the other named tax_rate, and calculates and returns the
```
total including tax. |
For example, if the arguments supplied were 114.0
for subtotal and 0.05 for tax_rate, your function should return the value
```
119.7. |
If the arguments were 328.0 and 0.045, your function should re
```
turn the value 342.76.
This function should produce no side effects.
-----
#### Chapter 6
### Style
Programs must be written for people to read, and only
incidentally for machines to execute.
–Abelson, Sussman, and Sussman
Learn the rules so you ... |
We’ll further our understanding of
constants, learn about the benefits of using comments, and how/when
to use them effectively.
**Learning objectives**
- You will learn about the importance of good Python style and the
PEP 8 style guide.
- You will learn conventions for naming constants.
- You will learn abou... |
Using
97
-----
good style:
- helps you read your code more quickly and accurately.
- makes it easier to identify syntax errors and common bugs.
- helps clarify your reasoning about your code.
Most workplaces and open-source projects require conformance to a
coding standard. |
For example, Google’s style guide for Python.[1]
When we’re solving problems we don’t want reading code or making
decisions about formatting our code to consume more than their share
of valuable cognitive load. |
So start off on the right foot and use good
style from the beginning. |
That way, you can free your brain to solve
problems—that’s the fun part.
Every language has its conventions, and you should stick to them.
This is part of writing readable, idiomatic code.
###### 6.2 PEP 8
Fortunately, there is a long-standing, comprehensive style guide for
Python called PEP 8.[2] The entire style gu... |
Noted Python developer Kenneth_
[Reitz has made a somewhat prettified version at https://pep8.org/. You](https://pep8.org/)
should consult these resources for a complete guide to good style for
Python. |
Many projects in industry and in the open source world enforce
the use of this standard.
Don’t think in terms of saving keystrokes—follow the style guide, and
you’ll find this helps you (and others!) read and understand what you
write.
###### 6.3 Whitespace
Yes! |
Whitespace is important! |
Using whitespace correctly can make your
code much more readable.
Use whitespace between operators and after commas.[4] Example:
```
# Don't do this
x=3.4*y+9-17/2
joules=(kg*m**2)/(sec**2)
amount=priceperitem*items
```
Instead, do this:
[1https://google.github.io/styleguide/pyguide.html](https://google.githu... |
You should avoid unnecessary whitespace before closing
and after opening braces, brackets or parentheses.
```
# Don't do this
picas = inches_to_picas ( inches )
# Better
picas = inches_to_picas(inches)
```
Do not put whitespace after names of functions.
```
# Don't do this
def inches_to_points (in):
re... |
Exceptions to this are
function declarations which should be preceded by two blank lines, and
function bodies which should be followed by two blank lines.
-----
###### 6.4 Names (identifiers)
Choosing good names is crucial in producing readable code. |
Use meaningful names when defining variables, constants, and functions. |
This makes
your code easier to read and easier to debug!
Examples of good variable names:
- velocity
- average_score
- watts
Examples of bad variable names:
- q
- m7
- rsolln
Compare these with the good names (above). |
With a good name, you
know what the variable represents. With these bad names, who knows
what they mean? |
(Seriously, what the heck is rsolln?)
There are some particularly bad names that should be avoided no
matter what. |
Never use the letter ”O” (upper or lower case) or ”l” (lowercase ”L”) or ”I” (upper case ”i”) as a variable name. “O” and “o” look
too much like “0”. |
“l” and “I” look too much like “1”.
While single letter variable names are, in general, to be avoided, it’s
OK sometimes (depending on context). For example, it’s common practice to use i, j, etc. |
for loop indices (we’ll get to loops later) and x, y, z
for spatial coordinates, but only use such short names when it is 100%
clear from context what these represent.
Similar rules apply to functions. |
Examples of bad function names:
- i2m()
- sd()
Examples of good function names:
- inches_to_meters()
- standard_deviation()
###### ALL_CAPS, lowercase, snake_case, camelCase, WordCaps
In Python, the convention for naming variables and function is that they
should use lowercase or so-called snake case, in whi... |
Not
so with Python. camelCase should be avoided (always). |
WordCaps are
appropriate for class names (a feature of object-oriented programming—
something that’s not presented in this text).
- Good: price_per_item
- Bad: Priceperitem or pricePerItem
As noted earlier, ALL_CAPS is reserved for constants.
-----
###### 6.5 Line length
PEP 8 suggests that lines should not e... |
This is well documented.
If your eye has to scan too great a distance to find the beginning
of the next line, readability suffers.
Throughout this text, you may notice some techniques used to keep
line length in code samples within these bounds.
###### 6.6 Constants
In most programming languages there’s a convention... |
Python is no different—and the convention is quite similar to
many other languages.
In Python, we use ALL_CAPS for constant names, with underscores
to separate words if necessary. |
Here are some examples:
```
# Physical constants
C = 299792458 # speed of light: meters / second ** -1
MASS_ELECTRON = 9.1093837015 * 10 ** -31 # mass in kg
# Mathematical constants
PI = 3.1415926535 # pi
PHI = 1.6180339887 # phi (golden ratio)
# Unit conversions
FEET_PER_METER = 3.280839895
KM_PER_NA... |
In Python, nothing.
All the more reason to make it immediately clear—visually—that we’re
dealing with a constant.
So the rule in Python is to use ALL_CAPS for constants and nothing else. |
Then it’s up to you, the programmer, to ensure these remain
unchanged.
-----
###### 6.7 Comments in code
Virtually all programming languages allow programmers to add com_ments to their code, and Python is no different. |
Comments are text_
within your code which is ignored by the Python interpreter.
Comments have many uses:
- explanations as to why a portion of code was written the way it
was,
- reminders to the programmer, and
- guideposts for others who might read your code.
Comments are an essential part of your code. |
In fact, it’s helpful to
think of your comments as you do your code. |
By that, I mean that the
_comments you supply should be of value to the reader—even if that reader_
is you.
Some folks say that code should explain how, and comments should
explain why. |
This is not always the case, but it’s a very good rule in
general. But beware: good comments cannot make up for opaque or
poorly-written code.
Python also has what are called docstrings. |
While these are not ignored by the Python interpreter, it’s OK for the purposes of this textbook
to think of them that way.
Docstrings are used for:
- providing identifying information,
- indicating the purpose and correct use of your code, and
- providing detailed information about the inputs to and output fr... |
Python uses
the # (call it what you will—pound sign, hash sign, number sign, or
octothorpe) to start a comment. Everything following the # on the same
line will be ignored by the Python interpreter. |
Here are some examples:
```
# This is a single-line comment
foo = 'bar' # This is an inline comment
###### Docstrings
```
_Docstring is short for documentation string. |
These are somewhat different_
from comments. |
According to PEP 257
A docstring is a string literal that occurs as the first statement
in a module, function, class, or method definition.
-----
Docstrings are not ignored by the Python interpreter, but for the
purposes of this textbook you may think of them that way. |
Docstrings
are delimited with triple quotation marks. |
Docstrings may be single lines,
thus:
```
def square(n):
"""Return the square of n."""
return n * n
```
or they may span multiple lines:
```
"""
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210, section Z
Homework 5
"""
```
It’s a good idea to include a docstring in every program file to explai... |
Jones
This is a simple program that
converts miles to kilometers.
We use the constant KM_PER_MILE
= 1.60934 for these calculations.
"""
###### Using comments as scaffolding
```
You may find it helpful to use comments as scaffolding for your code.
This involves using temporary comments that serve as placehol... |
In computer science, a description of steps
written in plain language embedded in code is known as pseudocode.
For example, if one were asked to write a program that prompts the
user for two integers and then prints out the sum, one might sketch
this out with comments, and then replace the comments with code. |
For
example:
```
# Get first integer from user
# Get second integer from user
# Calculate the sum
# Display the result
```
and then, implementing the code one line at a time:
-----
```
a = int(input('Please enter an integer: '))
# Get second integer from user
# Calculate the sum
# Display the result... |
TODO is commonly used to indicate
a part of your code which has been left unfinished. |
Many IDEs recognize
```
TODO and can automatically generate a list of unfinished to-do items.
###### Avoid over-commenting
```
While it is good practice to include comments in your code, well-written
code often does not require much by way of comments. |
Accordingly, it’s
important not to over-comment your code. |
Here are some examples of
over-commenting:
```
song.set_tempo(120) # set tempo to 120 beats / minute NO!
x = x + 1 # add one to x NO!
# I wrote this code before I had any coffee NO!
```
-----
###### 6.8 Exercises
**Exercise 01**
Here are some awful identifiers. |
Replace them with better ones.
```
# Newton's gravitational constant, G
MY_CONSTANT = 6.674E-11
# Circumference of a circle
circle = rad ** 2 * math.pi
# Clock arithmetic
# Calculate 17 hours after 7 o'clock
thisIsHowWeDoItInJava = (7 + 17) % 12
```
**Exercise 02**
The following Python code runs perfect... |
Using your chosen IDE, fix the issues and check to make
sure that the program still runs correctly.
```
def CIRCUMFERENCEOFCIRCLE(radius):
c=2*pi*radius
return c
pi=3.14159
CIRC=CIRCUMFERENCEOFCIRCLE(22)
print("The circumference of a circle with a radius of 22cm"
"is "+str(CIRC)+ "cm.")
```
-----
-... |
Things
get a lot more interesting when the user can provide such values.
In this chapter, we’ll learn how to get input from the user and use it
in our calculations. |
We’ll also learn how to format the output displayed
to the user.
We call getting and displaying data this way as console I/O (“I/O”
is just short for input/output).
We’ll also learn how to use Python’s f-strings (short for formatted
_string literals) to format output. |
For example, we can use f-strings with_
_format specifiers to display floating point numbers to a specific number_
of digits to the right of the decimal place. |
With f-strings we can align
strings for displaying data in tabular format.
� Warning
In this text, we will use f-strings exclusively for formatting output. Beware! |
There’s a lot of stale information out there on the
internet showing how to format strings in Python. |
For example,
you may see the so-called printf-style (inherited from the C programming language), or the str.format() method. |
These alternate
methods have their occasional uses, but for general purpose string
formatting, your default should be to use f-strings.
**Learning objectives**
- You will learn how to prompt the user for input, and handle input
from the user, converting it to an appropriate type if necessary.
- You will learn ho... |
For
example, imagine you were asked to write a calculator program. No
doubt, such a program would be expected to add, subtract, multiply,
and divide. But what should it add? What should it multiply? |
You, as
the programmer, would not know in advance. Thus, you’d need a way to
get information from the user into the program.
Of course, there are many ways to get input from a user. |
The most
common, perhaps, is via a graphical user interface or GUI. |
Most, or
likely all, of the software you use on your laptop, desktop, tablet, or
phone makes use of a GUI.
In this chapter, we’ll see how to get input in the most simple way,
without having to construct a GUI. |
Here we’ll introduce getting user
input from the console. |
Later, in Chapter 13, we’ll learn how to read
data from an external file.
###### 7.2 Command line interface
We’ve seen how to use the Python shell, where we type expressions or
other Python code and it’s executed interactively.
What we’ll learn now is how to write what are called CLI programs.
That’s short for comman... |
This distinguishes them from
GUI or graphical user interface programs.
When we interact with a CLI program, we run it from the command
line (or within your IDE) and we enter data and view program output
in text format. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.