Docsity

Lecture Notes for CPSC 121 Fall 2012: Comments, White Space, Operators, and Expressions, Study notes of Computer Science

Partial preview of the text

Download Lecture Notes for CPSC 121 Fall 2012: Comments, White Space, Operators, and Expressions and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Quiz 2
  • Comments and white space

Homework

  • HW 3 out

Reminder

  • No class on Wed.

Comments

Comments are special notes you can add to your programs

  • We’ll talk more about comments as we go

It’s always a good idea to comment your code

  • Helps others read your code
  • Helps you remember what your code does

Regular comments start with a # in Python

compute the percentage of the hour that has elapsed

percentage = (minute * 100) / 60

  • or –

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

Comments are useful when they highlight non-obvious features v = 5 # assign 5 to v

  • vs. –

v = 5 # velocity in meter/second

You should always try to choose descriptive variable and function names

  • E.g., instead of v use velocity
  • Or instead of f use calculate percentage of hour
  • Good names can reduce need for associated comments

Using white space

Put at least one blank line between header and function definitions

Incorrect:

def f(x): print(x)

Correct:

def f(x): print(x)

Put a blank line between function definitions

Incorrect: def f(x): print(x) def g(x): print(x)

Correct:

def f(x): print(x)

def g(x): print(x)

Don’t put white space before or after function ()’s

Incorrect:

def f (x) : print(x)

Correct:

def f(x): print(x)

Put white space between arguments/parameters

Incorrect:

def f(x,y): print(x,y)

Correct:

def f(x, y): print(x, y)

Expressions

Expressions are statements that always evaluate to (return) a value

Expressions can combine values, variables, and operators

Examples of expressions

  • 7 A value by itself
  • pi A variable by itself
  • pi + 7 An operator
  • 3 * 4 - 1 A series of operators

What should the value of the last expression be?

  • It depends on the order of operator evaluation!
  • To be explicit, use parenthesis: (34)-1 –or– 3(4-1)

Beware the Python interpreter! (common mistake)

  • The read-eval-print loop results in:

>>> 1 + 1 2

  • In a script the result of expressions are not printed
  • To print a result in a script, use the print function

An aside – What happens if we enter the following: >>> 12 = 3* SyntaxError: can’t assign to literal

Order of Operations

Precendence rules define the order of operator evaluation

  1. Parentheses have the highest precedence (evaluated inside out)
  2. Exponentiation is next (22+1 is 5 and 32*2 is 12 )
  3. Multiplication and Division are next, with the same precendence
  4. Addition and Subtraction come next, with the same precedence
    • Operators (except *) with same precedence are evaluated left to right (4//22 is 4 )

This spells PEMDAS