(→Very simple Python) |
(→Very simple Python) |
||

Line 4: | Line 4: | ||

Start a Python interactive session using the "python" command to get a >>> prompt. | Start a Python interactive session using the "python" command to get a >>> prompt. | ||

+ | |||

+ | === Command line math == | ||

Type | Type | ||

Line 63: | Line 65: | ||

>>>a | >>>a | ||

1.001 | 1.001 | ||

+ | |||

+ | |||

+ | === Importing math == | ||

+ | |||

+ | There's much more you can do, of course, but you need to import the math functions first. Here's one way to do that. | ||

+ | |||

+ | >>>import math | ||

+ | |||

+ | Now try | ||

+ | |||

+ | >>>math.pi | ||

+ | |||

+ | and you'll see | ||

+ | |||

+ | 3.141592653589793 | ||

+ | |||

+ | The functions in the math package need the "math." in front of them. | ||

+ | |||

+ | >>>math.sin(math.pi/4.) | ||

+ | |||

+ | returns | ||

+ | |||

+ | 0.7071067811865475 | ||

+ | |||

+ | as does | ||

+ | |||

+ | >>>math.sqrt(0.5) | ||

+ | |||

+ | Similarly | ||

+ | |||

+ | >>>4.*math.asin(math.sqrt(0.5)) | ||

+ | |||

+ | returns | ||

+ | |||

+ | 3.1415926535897936 |

This page contains examples and links to programs used for our Research Methods - Programming with Python short course.

Start a Python interactive session using the "python" command to get a >>> prompt.

Type

>>>x=1

and then simply

>>>x

and you'll see

1

Type

>>>x=1.01

and then after you type "x" you'll see

>>>x 1.01

Clearly you have a real-time calculator in hand, so try something more exciting.

>>>x=1.01 >>>y=1.0001 x/y

and you'll see something like this

1.0098990100989902

Modify that with

>>>z=x/y >>>z

and you'll see the same result. But now try

>>>int(z)

and you'll see

1

That is, the function int() took the integer part of z. You can put that in another variable such as

>>>a=int(z) >>>a 1

Curiously, a seems to be an integer. It is said to be *dymanically typed* in this assignment. That can change. If you now add a little bit to a you'll see it turns into a floating point number

>>>a = a + 0.001 >>>a 1.001

There's much more you can do, of course, but you need to import the math functions first. Here's one way to do that.

>>>import math

Now try

>>>math.pi

and you'll see

3.141592653589793

The functions in the math package need the "math." in front of them.

>>>math.sin(math.pi/4.)

returns

0.7071067811865475

as does

>>>math.sqrt(0.5)

Similarly

>>>4.*math.asin(math.sqrt(0.5))

returns

3.1415926535897936