47
1 Programming Thinking and Method (2) Zhao Hai 赵赵 Department of Computer Science and Engineering Shanghai Jiao Tong University zhaohai @cs.sjtu.edu.cn

Programming Thinking and Method (2)

Embed Size (px)

DESCRIPTION

Programming Thinking and Method (2). Zhao Hai 赵海 Department of Computer Science and Engineering Shanghai Jiao Tong University zhaohai @cs.sjtu.edu.cn. Outline. Values and Types Variables Assignment Type Conversion Summary. Values and Types. Numbers - PowerPoint PPT Presentation

Citation preview

Page 1: Programming Thinking and Method  (2)

1

Programming Thinking and Method

(2)

Zhao Hai 赵海

Department of Computer Science and EngineeringShanghai Jiao Tong University

 [email protected]

Page 2: Programming Thinking and Method  (2)

2

Outline

• Values and Types

• Variables

• Assignment

• Type Conversion

• Summary

Page 3: Programming Thinking and Method  (2)

3

Values and Types • Numbers

Integers: 12 0 12987 0123 0X1A2

Type ‘int’

Can’t be larger than 2**31

Octal literals begin with 0 (0981 illegal!)

Octal literals begin with 0O in python 3.x

Hex literals begin with 0X, contain 0-9 and A-F

Floating point: 12.03 1E1 1.54E21

Type ‘float’

Same precision and magnitude as C double

Page 4: Programming Thinking and Method  (2)

4

Values and Types

Long integers: 10294L

Type ‘long’

Any magnitude

Python usually handles conversions from ‘int’ to ‘long’

Complex numbers: 1+3J

Type ‘complex’

Python provides a special function called type(…) that tells

us the data type of any value. For example,

Page 5: Programming Thinking and Method  (2)

5

Values and Types >>> type(3)

<type 'int'> (python 2.x)

<class 'int'> (python 3.x)

>>> type(1E1)

<type 'float'>

>>> type(10294L)

<type 'long'>

>>> type(1+3J)

<type 'complex'>

Page 6: Programming Thinking and Method  (2)

6

Values and Types String

A string is a sequence of characters.

>>> type("Hello world!")

<type 'str'>

Single quotes or double quotes can be used for string literals.

>>> a = 'Hello world!'

>>> b = "Hello world!"

>>> a == b

True

Page 7: Programming Thinking and Method  (2)

7

Values and Types Produces exactly the same value.

>>> a = "Per's lecture"

>>> print a

Per's lecture

Special characters (escape sequence) in string literals: \n

newline, \t tab, others.

Page 8: Programming Thinking and Method  (2)

8

Values and Types

Page 9: Programming Thinking and Method  (2)

9

Values and Types Triple quotes useful for large chunks of text in program code.

>>> big = """This is

... a multi-line block

... of text; Python puts

... an end-of-line marker

... after each line. """

>>> big

'This is\na multi-line block\nof text; Python puts\nan end-of-line marker\

nafter each line. '

Page 10: Programming Thinking and Method  (2)

10

Variables

Variable Definition

A variable is a name that refers to a value.

Every variable has a type, a size, a value and a location in the

computer’s memory.

A state diagram can be used for representing variable’s state

including name, type, size and value.

Page 11: Programming Thinking and Method  (2)

11

Variables Variable Names and Keywords

Variable names (also called identifier) can be arbitrarily long.

They can contain both letters and numbers, but they have to begin

with a letter or underscore character (_) .

The underscore character is often used in names with multiple words,

such as my_name.

Although it is legal to use uppercase letters, by convention we don’t.

Note that variable names are case-sensitive, so spam, Spam, sPam,

and SPAM are all different.

Page 12: Programming Thinking and Method  (2)

12

Variables For the most part, programmers are free to choose any name that

conforms to the above rules. Good programmers always try to choose

names that describe the thing being named (meaningful), such as

message, price_of_tea_in_china.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = ’big parade’

SyntaxError: invalid syntax

Page 13: Programming Thinking and Method  (2)

13

Variables >>> more$ = 1000000

SyntaxError: invalid syntax

>>> class = ’Computer Science 101’

SyntaxError: invalid syntax

Keywords (also called reserved words) define the language’s rules

and structure, and they cannot be used as variable names. Python has

twenty-nine keywords:

Page 14: Programming Thinking and Method  (2)

14

Variables

Variable Usage

Variables are created when they are assigned. (Rule 1)

No declaration required. (Rule 2)

The type of the variable is determined by Python. (Rule 3)

For example,

>>> a = 'Hello world!' # Rule 1 and 2

>>> print a

'Hello world!'

>>> type(a) # Rule 3

<type 'str'>

Page 15: Programming Thinking and Method  (2)

15

Variables A variable can be reassigned to whatever, whenever. (Rule 4)

For instance,

>>> n = 12

>>> print n

12

>>> type(n)

<type 'int'>

>>> n = 12.0 # Rule 4

>>> type(n)

<type 'float'>

Page 16: Programming Thinking and Method  (2)

16

Variables

>>> n = 'apa' # Rule 4

>>> print n

'apa'

>>> type(n)

<type 'str'>

Page 17: Programming Thinking and Method  (2)

17

Assignment Expressions

Numeric expressions

Operators: special symbols that represent computations like addition and

multiplication.

Operands: the values the operator uses.

Page 18: Programming Thinking and Method  (2)

18

Assignment The “/” operator performs true division (floating-point division) and the

“//” operator performs floor division (integer division). But you should

use a statement “from __future__ import division” to distinguish the

above divisions.

For example,

>>> 3 / 4

0

>>> 3 // 4

0

>>> from __future__ import division

Page 19: Programming Thinking and Method  (2)

19

Assignment

>>> 3 / 4

0.75

>>> 3 // 4

0

The modulus operator (%) yields the remainder after integer

division.

For instance,

>>> 17 % 5

2

Page 20: Programming Thinking and Method  (2)

20

Assignment Order of operations: When more than one operator appears in an

expression, the order of evaluation depends on the rules of

precedence.

Page 21: Programming Thinking and Method  (2)

21

Assignment For example:

y = ( a * ( x ** 2 ) ) + ( b * x ) + c

a = 2; x = 5; b = 3; c = 7.

Page 22: Programming Thinking and Method  (2)

22

Assignment

Page 23: Programming Thinking and Method  (2)

23

Assignment Boolean expressions

‘True’ and ‘ False’ are predefined values, actually integers 1 and 0.

Value 0 is considered False, all other values True.

The usual Boolean expression operators: not, and, or.

For example,

>>> True or False

True

>>> not ((True and False) or True)

False

Page 24: Programming Thinking and Method  (2)

24

Assignment

>>> True * 12

12

>>>

0 and 1

0

Comparison operators produce Boolean values.

Page 25: Programming Thinking and Method  (2)

25

Assignment

Page 26: Programming Thinking and Method  (2)

26

Assignment

>>> 1 < 2

True

>>> 1 > 2

False

>>> 1 <= 1

True

>>> 1 != 2

True

Page 27: Programming Thinking and Method  (2)

27

Assignment

Statements

A statement is an instruction that the Python interpreter can execute.

For example, simple assignment statements:

>>> message = “What’s up, Doc?”

>>> n = 17

>>> pi = 3.14159

Page 28: Programming Thinking and Method  (2)

28

Assignment

A basic (simple) assignment statement has this form:

<variable> = <expr>

Here variable is an identifier and expr is an expression.

For example:

>>> myVar = 0

>>> myVar

0

>>> myVar = myVar + 1

>>> myVar

1

Page 29: Programming Thinking and Method  (2)

29

Assignment

A simultaneous assignment statement allows us to calculate several values all

at the same time:

<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>

It tells Python to evaluate all the expressions on the right-hand side and then

assign these values to the corresponding variables named on the left-hand

side.

For example,

sum, diff = x+y, x-y

Here sum would get the sum of x and y and diff would get the difference.

Page 30: Programming Thinking and Method  (2)

30

Assignment Another interesting example:

If you would like to swap (exchange) the values of two variables, e.g.,

x and y, maybe you write the following statements:

>>> x = 1

>>> y = 2

>>> x = y

>>> y = x

>>> x

2

Page 31: Programming Thinking and Method  (2)

31

Assignment >>> y

2

What’s wrong? Analysis:

variables x y

initial values 1 2

x = y

now 2 2

y = x

final 2 2

Page 32: Programming Thinking and Method  (2)

32

Assignment

Now we can resolve this problem by adopting a simultaneous

assignment statement:

>>> x = 1

>>> y = 2

>>> x, y = y, x

>>> x

2

>>> y

1

Page 33: Programming Thinking and Method  (2)

33

Assignment Because the assignment is simultaneous, it avoids wiping out one of

the original values.

Assigning input mode: in Python, input is accomplished using an

assignment statement combined with a special expression called

input. The following template shows the standard form:

<variable> = input(<prompt>)

Here prompt is an expression that serves to prompt the user for input.

It is almost always a string literal.

For instance:

Page 34: Programming Thinking and Method  (2)

34

Assignment

>>> ans = input("Enter an expression: ")

Enter an expression: 3 + 4 * 5

>>> print ans

23

Simultaneous assignment can also be used to get multiple values from

the user in a single input. e.g., a script:

# avg2.py

# A simple program to average two exam scores

# Illustrates use of multiple input

Page 35: Programming Thinking and Method  (2)

35

Assignment def main():

print "This program computes the average of two exam scores."

score1, score2 = input("Enter two scores separated

by a comma: ")

average = (score1 + score2) / 2.0

print "The average of the scores is:", average

main()

Page 36: Programming Thinking and Method  (2)

36

Assignment This program computes the average of two exam scores.

Enter two scores separated by a comma: 86, 92

The average of the scores is: 89.0

Page 37: Programming Thinking and Method  (2)

37

Type Conversion Type conversion converts between data types without

changing the value of the variable itself.

• Python provides a collection of built-in functions that convert values from one type to another.

For example, the int function takes any value and converts it

to an integer:

>>> int("32")

32

>>> int("Hello")

Page 38: Programming Thinking and Method  (2)

38

Type Conversion Traceback (most recent call last):

File "<interactive input>", line 1, in <module>

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

• int can also convert floating-point values to integers, but remember that it truncates the fractional part:

>>> int(3.99999)

3

>>> int(-2.3)

-2

Page 39: Programming Thinking and Method  (2)

39

Type Conversion The float function converts integers and strings to floating-

point numbers:

>>> float(32)

32.0

>>> float("3.14159")

3.1415899999999999

The str function converts to type string:

>>> str(32)

'32'

Page 40: Programming Thinking and Method  (2)

40

Type Conversion

>>> str(3.14149)

'3.14149'

• The repr function is a variant of str function intended for strict, code-like representation of values str function usually gives nicer-looking representation

>>> repr(32)

'32'

>>> repr(3.14149)

'3.1414900000000001'

Page 41: Programming Thinking and Method  (2)

41

Type Conversion

The function eval interprets a string as a Python expression:

>>> eval('23-12')

11

• Note that obj == eval(repr(obj)) is usually satisfied.

Page 42: Programming Thinking and Method  (2)

42

Summary There are different number types including integer, floating point, long integer,

and complex number.

A string is a sequence of characters. Python provides strings as a built-in data

type.

Strings can be created using the single-quote (') and double-quote characters (").

Python also supports triple-quoted strings. Triple-quoted strings are useful for

programs that output strings with quote characters or large blocks of text.

Page 43: Programming Thinking and Method  (2)

43

Python offers special characters that perform certain tasks,

such as backspace and carriage return.

A special character is formed by combining the backslash (\)

character, also called the escape character, with a letter.

A variable is a name that refers to a value, whose consists of

letters, digits and underscores (_) and does not begin with a

digit.

Every variable has a type, a size, a value and a

Summary

Page 44: Programming Thinking and Method  (2)

44

location in the computer’s memory.

Python is case sensitive—uppercase and lowercase letters are

different, so a1 and A1 are different variables.

Keywords (reserved words) are only used for Python system,

and they cannot be used as variable names.

Operators are special symbols that represent computations.

Operands are the values that the operator uses.

Summary

Page 45: Programming Thinking and Method  (2)

45

If the operands are both integers, the operator performs floor

division. If one or both of the operands are floating-point

numbers, the operator perform true division.

When more than one operator appears in an expression, the

order of evaluation depends on the rules of precedence.

The usual Boolean expression operators: not, and, or.

Comparison operators produce Boolean values.

Summary

Page 46: Programming Thinking and Method  (2)

46

A statement is an instruction that the Python interpreter can execute.

A simultaneous assignment statement allows us to calculate several values

all at the same time.

Because the assignment is simultaneous, it avoids wiping out one of the

original values.

Simultaneous assignment can also be used to get multiple values from the

user in a single input.

Summary

Page 47: Programming Thinking and Method  (2)

47

Type conversion converts between data types

without changing the value of the variable itself.

Python provides a collection of built-in functions

that convert values from one type to another.

Summary