Main Page | Recent changes | Edit this page | Page history

Printable version | Disclaimers | Privacy policy

Not logged in
Log in | Help
 

Notes: R01 Basic Python

From 6.00 reference wiki

(These notes are not a subsitute for the readings or lectures)

<-- Back to main notes

Contents

Comments

Anything following a '#' character till the end of the line in a Python program is a comment.

   # this is a comment
   print 'hello world' # this is another comment

Comments are not interpreted by Python, and are used for documenting what your programs are attempting to do in a human readable form.

You will find comments to be invaluable.

Print statements

print statements are used to display information to the user.

The simplest form is the keyword print followed by a string (as above).

You can also print multiple expressions separated by commas:

 >> print 'The cost of Google stock is', google_cost, 'dollars'
 The cost of Google stock is 369 dollars

Variables and Types

A variable is a name that references a value. The value has a specific type (e.g., integer, string, etc).

An assignment statement sets the value of a variable. In Python, assignment statements create variables.

  >> bean_counter = 100
  >> school = "Massachusetts Institute of Technology"

When a variable name occurs in an expression, the value of that variable is substituted. For example, the following is an expression that increments the value of a counter variable by 1.

  >> bean_counter = bean_counter + 1

In Python, a variable has no type. When evaluating an expression, the type of the variable's value determines what is legal and what isn't.

The above increment is legal, because bean_counter was initialized above with the integer value 100.

We can, in Python, later assign another type of value to bean_counter

  >> bean_counter = "some beans"

And now, the earlier arithmetic increment no longer works:

  >> bean_counter = bean_counter + 1
  ...
  TypeError: cannot concatenate 'str' and 'int' objects

In 6.095/6.00, we will use the following convention: a variable will have one, and only one, type. If a variable is initialized as an integer, you should never assign a string value to it. Later in the course, we will use stylized comments to formally document this.

Operator precedence

  >> x = 4 * 2 + 3
  >> print x
  11

The multiplication is performed before the addition, when calculating the value for x. When evaluating an expression with multiple operators as above Python will first apply the operator with the 'highest precedence', followed by operators with lower precedence.

For now, you should know the following precedence rules:

You can avoid the default behaviour by adding parentheses to group sub-expressions in whatever way you want.

The parentheses below tell Python to do the addition before the multiplication.

  >> y = 4 * (2 + 3)
  >> print x, y
  11, 20

When in doubt about which operator will be applied first, use parentheses.

Integer and Float pitfalls

(Think of floating point numbers as real numbers; the book goes into too much detail.)

If you divide two integer values, the result of the division is floored down to an integer (the fractional part of the answer is discarded):

  >> print 10 / 6
  1

In contrast, dividing a float by an integer, gives us the correct answer:

  >> print 10.0 / 6
  1.66666666667

What will the following do?

  >> print x / 6

It depends on the value of x. If x = 10 was used, this will display 1; alternatively if x = 10.0 was used, this will display 1.66666666667. This sort of behaviour can sometimes be problematic. For instance, when calculating probabilities you might always get zero:

  probability_heads = num_heads / num_total # always < 1

You can use any of the following approaches to fix this:

  >> x = 10 # or x = 10.0
  >> print x / 6.0  # dividing by a float always gives a float answer, as long as x is a number
  1.66666666667
  >> print float(x) / 6  # type conversion: converts x into a float if it is another type of number
  1.66666666667

(The book will have more details on these kinds of numerical type conversion issues.)

if-else

if ... else blocks can be used to make decisions within a program. Often you will want to do different things depending on the value of a variable(s).

  if predicate_expression:
      print 'if executed'
  else:
      print 'else executed'

Notice the indentation. Python uses indentation to group blocks of code.

The else is always optional.

The above will print one (and only one) of the two messages, depending on whether the value of predicate_expression is true or false. A true value will cause if executed to be printed.

predicate_expression will usually be a comparison. Some examples are:

  if n <= 1: # if the value of n is 'less than or equal' to 1
  ...   
  if n > 1: # if the value of n is 'strictly greater than' 1
  ...
  if n != 1: # if the value of n is 'not equal to' 1
  ...
  if n == 1: # if the value of n is 'equal to' 1
  ...

Furthermore, more complicated predicates can be formed using logical and, or, and not. So, for example:

  if n > 1 and k < 10: # if and only if n is greater than 1 and k is less than 10
  ...
  if n == 1 or n == 5: # if n is equal to either 1 or 5
  ...

You also can nest if...else statements:

  if predicate_expression:
      if another_predicate:
          print 'both ifs executed'
      else:
          print 'the inner else was executed'
  else:
      print 'the outer else was executed'

The predicate can also be a variable:

  if n:
      print "the value of n is true"
  else:
      print "the value of n is false"

The values considered to be false by Python are:

  0
  False
  None
  []
  ""

Other values of these types are considered to be true. Some examples are:

  1
  -1
  True
  [1, 2 ,3]
  "a string"
  'False'

Loops: while

While loops will execute the body of a loop, as long as a given predicate is true.

  i = 0
  while i < 10:
     print i
     i = i + 1

The above will print the integers 0 through 9.

Infinite loops
Be careful! With while loops: the predicate can always remain true. For example, if we take away the increment line, this program will never terminate. In contrast, you cannot get infinite loops with for loops (discussed in the book).

Retrieved from "http://slice.csail.mit.edu../../../r/0/1/Notes%7E_R01_Basic_Python_d3dc.html"

This page has been accessed 115 times. This page was last modified 15:35, 14 February 2006 by 6.00 reference wiki user Asfandyar.


[Main Page]
Main Page
Recent changes

Edit this page
Discuss this page
Page history
What links here
Related changes

Special pages
Bug reports