python – part 2 variables, expressions and statements 1

Post on 05-Jan-2016

233 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

Prepared by Department of Preparatory year

Python – Part 2

Variables, Expressions and Statements

Prepared by Department of Preparatory year

2

Values and Types

• Values– Basic things program works with– e.g. letter, number– 1, 2, ‘Hello World!’

• Types– Values belong to different types– 2 is an interger– ‘Hello World!’ is a string

Prepared by Department of Preparatory year

3

Numbers• Integers: 12 0 -12987 0123 0X1A2

– Type ‘int’

– Can’t be larger than 2**31(2 31)

– Octal literals begin with 0 (0981 illegal!)

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

• Floating point: 12.03 1E1 -1.54E-21– 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’

Prepared by Department of Preparatory year

4

String

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

• Produces exactly the same value• Special characters in string literals: \n newline, \t tab,

others• Triple quotes useful for large chunks of text in program

code

>>> print "One line.\nAnother line.“One line.Another line.

>>> print """One line,another line.""“One line,another line.

>>> print "Per's lecture“Per's lecture

Prepared by Department of Preparatory year

5

Values and Types

• Print statement for integers>>>print 44

• Can check the value type>>> type(‘Hello world!’)<type ‘str’>>>> type (17)<type ‘int’>

Prepared by Department of Preparatory year

6

Values and Types

• Strings belog to the type str• Integers belong to the type int• Numbers with a decimal point belong to the

type float.>>>type (3.2)<type ‘float’>

Prepared by Department of Preparatory year

7

Values and Types

• What about ’17’ and ‘3.2’?>>>type (’17’)

<type ‘str’> >>>type (‘3.2’) <type ‘str’>

Prepared by Department of Preparatory year

8

Values and Types

• >>>print 1,000,000• Output ?• 1 0 0• Semantic error

Prepared by Department of Preparatory year

9

Variables

• Variable is a name that refers to a value• Assignment statement creates new variables

and gives them values.>>>message=‘New message’>>>n=17>>>pi=3.1415926535897931

Prepared by Department of Preparatory year

10

Variables

• Use print statement to display the value of a variable>>> print n17>>> print messageNew message

Prepared by Department of Preparatory year

11

Variables

• Type of variable is the type of value it refers to(The type of the variable is determined by Python)

>>>type (pi)<type ‘float’>>>>type (n)<type ‘int’>>>>type (message)<type ‘str’>

Prepared by Department of Preparatory year

12

Variable Names

• Can contain both letters and numbers• Begin with a letter• Good idea to begin variable names with a

lowercase letter• Underscore character (_) can appear in a

name (often in names with multiple words), e.g. my_name

• The variable name is case sensitive: ‘val’ is not the same as ‘Val’

Prepared by Department of Preparatory year

13

Variable Names

• >>> 76trombones = 'big parade'SyntaxError: invalid syntax

• >>>more@=100000SytaxError: invalid syntax

• >>>class =‘CS104’SyntaxError: invalid syntax

• Class -> one of Python’s keywords

Prepared by Department of Preparatory year

14

Python Keywords

• And del from not while• As elif global or with• Assert else if pass yield• Break except import print• Class exec in raise• Continue finally is return• Def for lambda try

Prepared by Department of Preparatory year

15

Statements

• Unit of code that Python interpreter can execute (print, assignment statement)print 1x=2print x

Prepared by Department of Preparatory year

16

Operators and operands

• Operators – special symbols that represent computations (e.g. addition, division)

• Values the operator is applied to are called operands

+ addition- subtraction* multiplication/ division** exponentiation%modulus

Prepared by Department of Preparatory year

17

Operators and operands

• 20+32• Hour-1• Hour*60+minute• 5**2• (5+9)*(15-7)• 7%3

Prepared by Department of Preparatory year

18

Operators and Operands

>>>minute=59 >>>minute/60 0

?

Prepared by Department of Preparatory year

19

Operators and operands

• If both operands are integers, result is also an integer

• If either of the operands is a floating-point number Python performs floatin-point division; result is a float>>>minute/60.00.98333333333333328

• In Python 3.0 or later the result is a float• // operator performs integer division

Prepared by Department of Preparatory year

20

Expressions

• Combination of values, variables and operators17XX+17

Prepared by Department of Preparatory year

21

Expressions

>>>1+1 2

In a script, expression by itself doesn’t do anything.

Prepared by Department of Preparatory year

22

Order of operations

• Order of evaluation depends on rules of precedence.

• Python follows mathematical convention– Parentheses – highest precedence– Exponentiation –next highest precedence– Multiplication, Division, Modulus (same

precedence)– Addition and Subtraction (same prec.)

• Same precedence operators – left to right

Prepared by Department of Preparatory year

23

Order of operations

• 2*(3-1)• (1+1)**(5-2)• 2**1+1• 3*1**3• 2*3-1• 6+4/2*3• 7%3+8/2

Prepared by Department of Preparatory year

24

String operations

• Concatenation operator +first =‘CS’

second=‘104’ print first+second

• Repitition operator *‘spam’*3‘spamspamspam’

Prepared by Department of Preparatory year

25

Comments

• Notes that can be added to program to explain what the program is doing

• Start with the # symbol#compute the percentage of the hour that has elapsed

percentage=(minute*100)/60 percentage=(minute*100)/60 #percentage of an hour

2-26

•Programs commonly need to read input typed by the user on the keyboard. We will use the Python functions to do this.•Python uses built-in functions to read input from the keyboard.•A function is a piece of prewritten code that performs an operation and then returns a value back to the program.•The input function can be used to read numeric data from the keyboard.

Reading Input from the Keyboard

2-27

Reading Numbers with the input FunctionUse the input function in an assignment statement:

variable = input (prompt)where,

variable name of the variable that will reference the data= assignment operatorinput name of the functionprompt string that is displayed on the screen

For example: hours = input (‘How many hours did you work?’)

Reading Input from the Keyboard

Reading Input from the Keyboard

Reading Strings with the raw_input FunctionThe raw_input function retrieves all keyboard input as a string.

>>> name = raw_input(‘Enter your name:’)>>> print nameEnter your name: Ahmad

2-28

Prepared by Department of Preparatory year

29

Write scripts in IDLE

• Now we need to write proper scripts, saved in files• In IDLE:

– 'File'– 'New Window'– Do immediately 'Save as…'

• Browse to directory 'Desktop'• Create a directory 'Python course'• Go down into it• Enter the file name 't1.py'• Save

• Work in the window called 't1.py'

– Enter the following code:

– Save the file: Ctrl-S, or menu 'File', 'Save'– Run the script: F5, or menu 'Run', 'Run Module'

"file Ex1.py" # this is a documentation stringprint "Hello world!"

30

Prepared by Department of Preparatory year

Part 2

End

top related