1 Python Chapter 2 © Samuel Marateck, 2010. 2 After you install the compiler, an icon labeled IDLE...

Post on 22-Dec-2015

228 views 1 download

Transcript of 1 Python Chapter 2 © Samuel Marateck, 2010. 2 After you install the compiler, an icon labeled IDLE...

1

PythonChapter 2

© Samuel Marateck, 2010

2

After you install the compiler, an icon labeled IDLE (Python GUI) will appear on the screen. If you click it, a window will appear on the screen with some copyrightinformation. This window is called the shell.IDLE is an acronym for Integrated DeveLopment Environment which allows you to write, edit and run a program.

3

Under that a prompt indicated by >>> will

appear. This prompts you to type some

Instruction. For instance,

>>> 3*4

This instructs the computer to multiply

3 times 4. The computer responds with

the product, 12. So you see:

4

>>>3*4

12

There are two types of numbers we will

be working with, integers and floats.

Let’s discuss integers first.

5

An integer has no decimal point. Examples

3, 456, -12. These are called integer literals

We first list symbols that you are familiar

with:

+ (addition), - (subtraction), * (multiplication),

and / (division).

6

We first list symbols that you are familiar

with:

+ (addition), - (subtraction), * (multiplication),

and / (division).

The first three produce an integer; but the /

produces a number with a decimal point.

7

The / produces a number with a decimal point. So for instance typing 4/2 we get>>> 4/22.0

The number 2.0 in called a floating pointnumber or simply, a float. It is an exampleof a float literal.

8

There are three other operations you can use

with integers. Let’s try “//”, integer division:

>>> 7//2

3

Now 7/2 produces 3.5. The // operator

instructs the compiler to truncate the

results, i.e., lops off the part of the number

to the right of the decimal point. So 3.5 becomes 3

9

The second operator is %, the remainder

operator.

>>>7%2

1

Think of it this way, after 7//2 is performed,

the reminder is 1.

10

The third operator is ** which indicates

exponentiation, so

>>> 2**3

8

11

As oppose to other languages , there is no

limit to the number of digits in an integer.

So

>>>2**300

20370359763344860862684456884093781

61051468393665936250636140449354381

299763336706183397376

12

The operators have a precedence.

the operator with the highest precedence

is ** , then comes *, /, //, and %. These all

have the same precedence. Finally comes

+, -.

13

So 3*4 + 5 evaluates as 12+5 or 17.

How do you change the precedence, so that

the addition is done before the

multiplication?

.

14

.How do you change the precedence, so that the

addition is done before the multiplication?

Use (). So:

>>> 3*(4+5)

27

The operations in the () are always done first.

15

Similarly

>>> 3+2**4

19

How do you have the addition done before

the exponentiation?

16

To have the addition done before

the exponentiation, use ():

>>>(3+2)**4

625

or 5**4

17

Order of Operations

Operator Operation Precedence

() parentheses 0

** exponentiation 1

* multiplication 2

/ division 2

// int division 2

% remainder 2

+ addition 3

- subtraction 3

18

The computer scans the expression fromleft to right, first clearing parentheses,second, evaluating exponentiations from left to

right in the order they are encounteredthird, evaluating *, /, //, % from left to right in the order they are encountered,fourth, evaluating +, - from left to right in the order they are encountered

19

How would you evaluate (3+3*5)/2*3?

Is it 18/6 i.e, 3 or is it 9*3?

20

These are the steps in evaluating the

Expression (3+3*5)/2*3

1.(3 + 15)/2*3

2. 18/2*3

3. 9*3

4. 27

21

The same operators that apply to integers

apply to floats. For instance.

In 5.2//2.1 python first uses regular division,

5.2/2.1 getting 2.4761904761904763 and

truncates the answer to 2.

22

Let’s do 6.3//2.1. You might expect to get

3.0 but you get 2.0. Why?

23

First, let’s calculate 6.3/2.1 using regular

division, the answer is 3.0 .

But floats are only approximations. The

answer that’s stored in memory is 2.999999

but is printed as 3.0. The // operation

truncates the results. So 6.3//2.1 is 2.99999

truncated to 2.0

24

So we’d expect 6.4//2.1 to produce 3.0

and it does.

25

Integers are stored in the memory exactly;

whereas stored floats are only

approximations.

26

There are math functions that can be Imported. To do this, type import math. If you then type

help(math),

the computer will type all themath functions and what they do:>>>import math>>help(math)

27

Then if you want to find the √5, you type

>>>math.sqrt(5) and you get

2.2360679774997898

28

If you don’t want to type math each time

you use a function, type:

>>>from math import *

Then you can simply write:

>>>sqrt(5)

2.2360679774997898

29

If you just want to see the functions in the

math module, type

>>>dir(math)

and you get:

30

['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

31

If you want to see the meaning of a

function, place the function name in the

() in help. Example:

>>>help(hypot)

This gives:

32

>>> help(hypot)

Help on built-in function hypot in module math:

hypot(...)

hypot(x,y)

Return the Euclidean distance, sqrt(x*x + y*y).

33

What does

>>> hypot(3,4)

give you?

34

>>> hypot(3,4)

5.0

35

Strings

A string is a group of one or more characters

sandwiched between “ or ‘. So “123sd” and

‘sde’ are strings. The characters “ and ‘

are called delimiters. If the string starts with

a “, it must end with a “; if it starts with a

‘ it must end with a ‘.

36

The + operator is overloaded. This means it

use depends upon context. We have seen

its use with floats and integers. It can also

be used with strings.

37

When used with strings, it joins them

creating a new string. So

>>>’abc’ + “123”

‘abc123’

38

To get the number of characters in a string

Use the len function.

>>>len(’abc’ + “123”)

6

39

Using Variables

A variable is a name associated with a memory location. Examplesone = 12two = 12.5st = ‘123as’

One, two and s are variable names.The type of the literal determines the variabletype. So one is an integer, two a float, and st astring.

40

Variable names are case sensitive, so one

and One are two different variables (since

One is capitalized and one is not) and

describe two different memory locations.

41

Conversion functions

You can’t concatenate a string with anothertype. So>>> 'anc' + 3

producesTraceback (most recent call last): File "<pyshell#2>", line 1, in <module> 'anc' + 3 TypeError: Can't convert 'int' object to str

implicitly

42

The error message:

TypeError: Can't convert 'int' object to str implicitly

means that we have to explicitly make 3 in:'anc' + 3a string. The function str does this:

>>> 'anc' + str(3)'anc3‘

The error is an example of a syntax error since it doesn’t follow the grammaticalrules of Python.

43

The following table show the conversion

functions.

44

function use

Str() Converts a number to

a string

int() Converts an object to an

integer and truncates.

round() Converts an object to an

integer and rounds.

float Converts an object to a

float.

45

Examples:>>>int(‘1234’)1234>>>float(‘1234’)1234.0>>>round(12.56)13>>>str(12.34)’12.34’

46

When int() operates on a string, what is embedded between the quotes must bean integer, so>>>int(’1.234’)

because 1.234 is a float, produces:

int('1.234')ValueError: invalid literal for int() with base 10:

'1.234'

47

When an integer is used in an expression

containing a float, the result is also a float:

>>12 + 3.0

15.0