Cryptography Reference
In-Depth Information
The only other thing to mention here is the
print
statement. In the case I provided above, we can print a
literal string, such as
"x = "
, or a value (which will be converted to a string). We can print multiple things
(with spaces separating them) by using a comma, as is shown above.
Let's go through one more quick example to illustrate a few more concepts.
The program shown in
Listing 3-2
will have the following output:
Listing 3-2
A factorial function written in Python.
def
factorial(n):
if
n == 0
or
n == 1:
return
1
else:
return
n * factorial(n - 1)
x = 0
f = 0
while
f = 100:
f = factorial(x)
print
f
x = x + 1
1
1
2
6
24
120
This program gives a taste of a few more tools: functions, conditionals, and the
while
loop.
Functions are defined using the
def
statement, as in the above example (its parameters specified in paren-
theses after the function name). Values of functions are returned using the
return
statement.
Conditionals are most commonly performed using
if
statements. The
if
statement takes an argument that
is Boolean (expressions that return true or false), such as a comparison like == (equals) and < (less than), and
combinations of Booleans, combined using
and
and
or
. There can be an optional
else
statement for when
the
if's
condition evaluates to false (and there can be, before the
else
, one or more
elif
, which allow ad-
ditional conditionals to be acted on).
Finally, we have another loop, the
while
loop. Simply put, it evaluates the condition at the beginning of
the loop each time. If the condition is true, it executes the loop; if false, it breaks out and continues to the next
statement outside the loop.
Python automatically converts fairly well between floating point numbers, arbitrarily large numbers, strings,
and so on. For example, if we used the above code to calculate
factorial(20)
, we would simply obtain
2432902008176640000L
The
L
on the end indicates that the result is a large integer (beyond machine precision). No modification of
the code was necessary — Python automatically converted the variables to these large-precision numbers.
I'll spread a little Python here and there throughout this and later chapters to have some concrete examples
and results. The rest ofthis chapter is devoted to algorithms forfactoring integers and solving discrete logarithm
problems, of different complexities and speeds.
Search WWH ::
Custom Search