Text stringlengths 1 9.41k |
|---|
Statements like this are called compound statements because
they stretch across more than one line.
There is no limit on the number of statements that can appear in the body, but
there must be at least one. |
Occasionally, it is useful to have a body with no
statements (usually as a placekeeper for code you haven’t written yet). |
In that
case, you can use the pass statement, which does nothing.
**if x < 0 :**
**pass** _# need to handle negative values!_
If you enter an if statement in the Python interpreter, the prompt will change
from three chevrons to three dots to indicate you are in the middle of a block of
statements, as shown below:
>... |
print('Small')
...
Small
>>>
##### 3.4 Alternative execution
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. |
The syntax
looks like this:
**if x%2 == 0 :**
print('x is even')
**else :**
print('x is odd')
If the remainder when x is divided by 2 is 0, then we know that x is even, and the
program displays a message to that effect. |
If the condition is false, the second set
of statements is executed.
Since the condition must either be true or false, exactly one of the alternatives will
be executed. |
The alternatives are called branches, because they are branches in
the flow of execution.
1We will learn about functions in Chapter 4 and loops in Chapter 5.
-----
print(‘x is even’)
Figure 3.2: If-Then-Else Logic
x%2 == 0
##### 3.5 Chained conditionals
Sometimes there are more than two possibilities and we ... |
One way to express a computation like that is a chained conditional:
**if x < y:**
print('x is less than y')
**elif x > y:**
print('x is greater than y')
**else:**
print('x and y are equal')
elif is an abbreviation of “else if.” Again, exactly one branch will be executed.
x < y
print(‘less’)
Figure 3.3: If... |
If there is an else clause, it
has to be at the end, but there doesn’t have to be one.
**if choice == 'a':**
print('Bad guess')
**elif choice == 'b':**
print('Good guess')
**elif choice == 'c':**
print('Close, but not correct')
print (‘greater’)
-----
Each condition is checked in order. |
If the first is false, the next is checked, and so
on. If one of them is true, the corresponding branch executes, and the statement
ends. |
Even if more than one condition is true, only the first true branch executes.
##### 3.6 Nested conditionals
One conditional can also be nested within another. |
We could have written the
three-branch example like this:
**if x == y:**
print('x and y are equal')
**else:**
**if x < y:**
print('x is less than y')
**else:**
print('x is greater than y')
The outer conditional contains two branches. |
The first branch contains a simple
statement. The second branch contains another if statement, which has two
branches of its own. |
Those two branches are both simple statements, although
they could have been conditional statements as well.
x == y
print(‘less’)
print(‘equal’)
Figure 3.4: Nested If Statements
x < y
Although the indentation of the statements makes the structure apparent, nested
_conditionals become difficult to read very ... |
In general, it is a good idea to_
avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements.
For example, we can rewrite the following code using a single conditional:
**if 0 < x:**
**if x < 10:**
print('x is a positive single-digit number.')
The print statement is ex... |
We also saw how treacherous
doing this could be:
>>> prompt = "What...is the airspeed velocity of an unladen swallow?\n"
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10... |
It does not execute the following
statement.
Here is a sample program to convert a Fahrenheit temperature to a Celsius temperature:
inp = input('Enter Fahrenheit Temperature: ')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
_# Code: http://www.pythonlearn.com/code3/fahren.py_
If we execute this code ... |
The idea of try and
except is that you know that some sequence of instruction(s) may have a problem
and you want to add some statements to be executed if an error occurs. |
These
extra statements (the except block) are ignored if there is no error.
You can think of the try and except feature in Python as an “insurance policy”
on a sequence of statements.
We can rewrite our temperature converter as follows:
inp = input('Enter Fahrenheit Temperature:')
**try:**
fahr = float(inp)
cel = (f... |
If all goes
well, it skips the except block and proceeds. |
If an exception occurs in the try
block, Python jumps out of the try block and executes the sequence of statements
in the except block.
python fahren2.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren2.py
Enter Fahrenheit Temperature:fred
Please enter a number
Handling an exception with a try statem... |
In
this example, the except clause prints an error message. |
In general, catching an
exception gives you a chance to fix the problem, or try again, or at least end the
program gracefully.
##### 3.8 Short-circuit evaluation of logical expressions
When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it
evaluates the expression from left to right. |
Because of the definition of and, if x is
less than 2, the expression x >= 2 is False and so the whole expression is False
regardless of whether (x/y) > 2 evaluates to True or False.
When Python detects that there is nothing to be gained by evaluating the rest
of a logical expression, it stops its evaluation and does ... |
When the evaluation of a logical expression
-----
stops because the overall value is already known, it is called short-circuiting the
evaluation.
While this may seem like a fine point, the short-circuit behavior leads to a clever
technique called the guardian pattern. |
Consider the following code sequence in the
Python interpreter:
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>... |
But the second example did not fail because the
first part of the expression x >= 2 evaluated to False so the (x/y) was not ever
executed due to the short-circuit rule and there was no error.
We can construct the logical expression to strategically place a guard evaluation
just before the evaluation that might cause a... |
The most useful parts are usually:
- What kind of error it was, and
- Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. |
Whitespace
errors can be tricky because spaces and tabs are invisible and we are used to
ignoring them.
>>> x = 5
>>> y = 6
File "<stdin>", line 1
y = 6
^
IndentationError: unexpected indent
In this example, the problem is that the second line is indented by one space. |
But
the error message points to y, which is misleading. |
In general, error messages
indicate where the problem was discovered, but the actual error might be earlier
in the code, sometimes on a previous line.
In general, error messages tell you where the problem was discovered, but that is
often not where it was caused.
##### 3.10 Glossary
**body The sequence of statements... |
The**
header ends with a colon (:). |
The body is indented relative to the header.
**guardian pattern Where we construct a logical expression with additional com-**
parisons to take advantage of the short-circuit behavior.
**logical operator One of the operators that combines boolean expressions: and,**
or, and not.
**nested conditional A conditional st... |
The following shows two executions of the program:
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
-----
Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. |
If the
score is out of range, print an error message. |
If the score is between 0.0 and 1.0,
print a grade using the following table:
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
~~~
Enter score: 0.95 A ~~
Enter score: perfect
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
F
Run the program repeatedly as shown above to test the ... |
When you define a function, you specify the name and
the sequence of statements. Later, you can “call” the function by name. |
We have
already seen one example of a function call:
>>> type(32)
<class 'int'>
The name of the function is type. The expression in parentheses is called the
_argument of the function. |
The argument is a value or variable that we are passing_
into the function as input to the function. |
The result, for the type function, is the
type of the argument.
It is common to say that a function “takes” an argument and “returns” a result.
The result is called the return value.
##### 4.2 Built-in functions
Python provides a number of important built-in functions that we can use without
needing to provide the f... |
The creators of Python wrote a set of
functions to solve common problems and included them in Python for us to use.
The max and min functions give us the largest and smallest values in a list, respectively:
>>> max('Hello world')
_'w'_
>>> min('Hello world')
_' '_
>>>
-----
The max function tells us the “largest c... |
If the argument to len is a string, it returns the number
of characters in the string.
>>> len('Hello world')
11
>>>
These functions are not limited to looking at strings. |
They can operate on any set
of values, as we will see in later chapters.
You should treat the names of built-in functions as reserved words (i.e., avoid using
“max” as a variable name).
##### 4.3 Type conversion functions
Python also provides built-in functions that convert values from one type to another. |
The int function takes any value and converts it to an integer, if it can, or
complains otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
int can convert floating-point values to integers, but it doesn’t round off; it chops
off the fraction part:
>>> int(3.99999... |
Determinism is usually a good thing,
since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. |
Games are an obvious
example, but there are more.
Making a program truly nondeterministic turns out to be not so easy, but there
are ways to make it at least seem nondeterministic. |
One of them is to use al_gorithms that generate pseudorandom numbers. |
Pseudorandom numbers are not_
truly random because they are generated by a deterministic computation, but just
by looking at the numbers it is all but impossible to distinguish them from random.
The random module provides functions that generate pseudorandom numbers
(which I will simply call “random” from here on).
T... |
Each time you call random, you get the next number in a long series.
To see a sample, run this loop:
import random
**for i in range(10):**
x = random.random()
print(x)
This program produces the following list of 10 random numbers between 0.0 and
up to but not including 1.0.
0.11132867921152356
0.5950949227890241
0.... |
Run
the program more than once and see what numbers you get.
The random function is only one of many functions that handle random numbers.
The function randint takes the parameters low and high, and returns an integer
between low and high (including both).
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
---... |
Before we can use the module, we have to import it:
>>> import math
This statement creates a module object named math. |
If you print the module
object, you get some information about it:
>>> print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. |
To
access one of the functions, you have to specify the name of the module and the
name of the function, separated by a dot (also known as a period). |
This format is
called dot notation.
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
The first example computes the logarithm base 10 of the signal-to-noise ratio. |
The
math module also provides a function called log that computes logarithms base e.
The second example finds the sine of radians. |
The name of the variable is a hint
that sin and the other trigonometric functions (cos, tan, etc.) take arguments in
radians. |
To convert from degrees to radians, divide by 360 and multiply by 2π:
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865476
-----
The expression math.pi gets the variable pi from the math module. |
The value of
this variable is an approximation of π, accurate to about 15 digits.
If you know your trigonometry, you can check the previous result by comparing it
to the square root of two divided by two:
>>> math.sqrt(2) / 2.0
0.7071067811865476
##### 4.6 Adding new functions
So far, we have only been using the fu... |
A function definition specifies the name of a new
function and the sequence of statements that execute when the function is called.
Once we define a function, we can reuse the function over and over throughout our
program.
Here is an example:
**def print_lyrics():**
print("I'm a lumberjack, and I'm okay.")
print('I ... |
The name of
the function is print_lyrics. |
The rules for function names are the same as for
variable names: letters, numbers and some punctuation marks are legal, but the
first character can’t be a number. |
You can’t use a keyword as the name of a
function, and you should avoid having a variable and a function with the same
name.
The empty parentheses after the name indicate that this function doesn’t take any
arguments. |
Later we will build functions that take arguments as their inputs.
The first line of the function definition is called the header; the rest is called
the body. |
The header has to end with a colon and the body has to be indented.
By convention, the indentation is always four spaces. |
The body can contain any
number of statements.
The strings in the print statements are enclosed in quotes. |
Single quotes and double
quotes do the same thing; most people use single quotes except in cases like this
where a single quote (which is also an apostrophe) appears in the string.
If you type a function definition in interactive mode, the interpreter prints ellipses
(. |
. . ) to let you know that the definition isn’t complete:
>>> def print_lyrics():
... print("I'm a lumberjack, and I'm okay.")
... |
print('I sleep all night and I work all day.')
...
-----
To end the function, you have to enter an empty line (this is not necessary in a
script).
Defining a function creates a variable with the same name.
>>> print(print_lyrics)
<function print_lyrics at 0xb7e99e9c>
>>> print(type(print_lyrics))
<class 'function'... |
For example, to repeat the previous refrain, we could write a function called repeat_lyrics:
**def repeat_lyrics():**
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night ... |
The statements inside the function do not get executed
until the function is called, and the function definition generates no output.
As you might expect, you have to create a function before you can execute it. |
In
other words, the function definition has to be executed before the first time it is
called.
Exercise 2: Move the last line of this program to the top, so the function call
appears before the definitions. |
Run the program and see what error message you
get.
Exercise 3: Move the function call back to the bottom and move the definition of
print_lyrics after the definition of repeat_lyrics. |
What happens when you
run this program?
##### 4.8 Flow of execution
In order to ensure that a function is defined before its first use, you have to know
the order in which statements are executed, which is called the flow of execution.
Execution always begins at the first statement of the program. |
Statements are
executed one at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is
called.
A function call is like a detour in the flow of execution. |
Instead of going to the next
statement, the flow jumps to the body of the function, executes all the statements
there, and then comes back to pick up where it left off.
That sounds simple enough, until you remember that one function can call another.
While in the middle of one function, the program might have to execu... |
But while executing that new function, the program
might have to execute yet another function!
Fortunately, Python is good at keeping track of where it is, so each time a function
completes, the program picks up where it left off in the function that called it.
When it gets to the end of the program, it terminates.
W... |
When you read a program, you don’t always
want to read from top to bottom. |
Sometimes it makes more sense if you follow the
flow of execution.
-----
##### 4.9 Parameters and arguments
Some of the built-in functions we have seen require arguments. |
For example, when
you call math.sin you pass a number as an argument. |
Some functions take more
than one argument: math.pow takes two, the base and the exponent.
Inside the function, the arguments are assigned to variables called parameters.
Here is an example of a user-defined function that takes an argument:
**def print_twice(bruce):**
print(bruce)
print(bruce)
This function assigns... |
When the function is called, it prints the value of the parameter (whatever it is) twice.
This function works with any value that can be printed.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice(17)
17
17
>>> import math
>>> print_twice(math.pi)
3.141592653589793
3.141592653589793
The same rules of composition that... |
It doesn’t matter what the value was
called back home (in the caller); here in print_twice, we call everybody bruce.
-----
##### 4.10 Fruitful functions and void functions
Some of the functions we are using, such as the math functions, yield results;
for lack of a better name, I call them fruitful functions. |
Other functions, like
print_twice, perform an action but don’t return a value. |
They are called void
_functions._
When you call a fruitful function, you almost always want to do something with
the result; for example, you might assign it to a variable or use it as part of an
expression:
x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
When you call a function in interactive mode, Python di... |
If you try to assign the result to a variable,
you get a special value called None.
>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
The value None is not the same as the string “None”. |
It is a special value that has
its own type:
>>> print(type(None))
<class 'NoneType'>
To return a result from a function, we use the return statement in our function.
For example, we could make a very simple function called addtwo that adds two
numbers together and returns a result.
-----
**def addtwo(a, b):**
add... |
Within the function, the
parameters a and b were 3 and 5 respectively. The function computed the sum of
the two numbers and placed it in the local function variable named added. |
Then
it used the return statement to send the computed value back to the calling code
as the function result, which was assigned to the variable x and printed out.
##### 4.11 Why functions?
It may not be clear why it is worth the trouble to divide a program into functions.
There are several reasons:
- Creating a n... |
Later,
if you make a change, you only have to make it in one place.
- Dividing a long program into functions allows you to debug the parts one at
a time and then assemble them into a working whole.
- Well-designed functions are often useful for many programs. |
Once you write
and debug one, you can reuse it.
Throughout the rest of the book, often we will use a function definition to explain
a concept. |
Part of the skill of creating and using functions is to have a function
properly capture an idea such as “find the smallest value in a list of values”. |
Later
we will show you code that finds the smallest in a list of values and we will present
it to you as a function named min which takes a list of values as its argument and
returns the smallest value in the list.
##### 4.12 Debugging
If you are using a text editor to write your scripts, you might run into problems ... |
The best way to avoid these problems is to use spaces exclusively
(no tabs). |
Most text editors that know about Python do this by default, but some
don’t.
Tabs and spaces are usually invisible, which makes them hard to debug, so try to
find an editor that manages indentation for you.
-----
Also, don’t forget to save your program before you run it. |
Some development
environments do this automatically, but some don’t. |
In that case, the program
you are looking at in the text editor is not the same as the program you are
running.
Debugging can take a long time if you keep running the same incorrect program
over and over!
Make sure that the code you are looking at is the code you are running. |
If you’re
not sure, put something like print("hello") at the beginning of the program and
run it again. |
If you don’t see hello, you’re not running the right program!
##### 4.13 Glossary
**algorithm A general process for solving a category of problems.**
**argument A value provided to a function when the function is called. |
This value**
is assigned to the corresponding parameter in the function.
**body The sequence of statements inside a function definition.**
**composition Using an expression as part of a larger expression, or a statement**
as part of a larger statement.
**deterministic Pertaining to a program that does the same thing... |
It consists of the function**
name followed by an argument list.
-----
**function definition A statement that creates a new function, specifying its name,**
parameters, and the statements it executes.
**function object A value created by a function definition. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.