- 52 Views
- Uploaded on
- Presentation posted in: General

Programming Thinking and Method (2)

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Programming Thinking and Method (2)

Zhao Hai 赵海Department of Computer Science and EngineeringShanghai Jiao Tong Universityzhaohai@cs.sjtu.edu.cn

Values and Types

Variables

Assignment

Type Conversion

Summary

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

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,

>>> 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'>

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

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.

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. '

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.

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.

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

>>> 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:

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'>

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'>

>>> n = 'apa' # Rule 4

>>> print n

'apa'

>>> type(n)

<type 'str'>

Expressions

Numeric expressions

Operators: special symbols that represent computations like addition and multiplication.

Operands: the values the operator uses.

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

>>> 3 / 4

0.75

>>> 3 // 4

0

The modulus operator (%) yields the remainder after integer division.

For instance,

>>> 17 % 5

2

Order of operations: When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence.

For example:

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

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

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

>>> True * 12

12

>>>

0 and 1

0

Comparison operators produce Boolean values.

>>> 1 < 2

True

>>> 1 > 2

False

>>> 1 <= 1

True

>>> 1 != 2

True

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

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

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.

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

>>> y

2

What’s wrong? Analysis:

variables x y

initial values 1 2

x = y

now 2 2

y = x

final 2 2

Now we can resolve this problem by adopting a simultaneous assignment statement:

>>> x = 1

>>> y = 2

>>> x, y = y, x

>>> x

2

>>> y

1

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:

>>> 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

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()

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

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")

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

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'

>>> 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'

The function eval interprets a string as a Python expression:

>>> eval('23-12')

11

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

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.

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

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

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

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

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