MC logo
Simple Numeric Computation
[^] Code Examples
<<Hello, World! num1.py Strings I>>
# Some calculations.  Note the lack of semicolons.  Statements end at the end
# of the line.  Also, variables need not start with a special symbol as in
# perl and some other Unix-bred languages.
fred = 18
barney = FRED = 44;                     # Case sensistive.
bill = (fred + barney * FRED - 10)
alice = 10 + bill / 100                 # Regular division does not truncate.
alice2 = 10 + bill // 100               # But the // operator provides int div.
frank = 10 + float(bill) / 100
print("fred =", fred)
print("FRED =", FRED)
print("bill =", bill)
print("alice =", alice)
print("alice2 =", alice2)
print("frank =", frank )

# Each variable on the left is assigned the corresponding value on the right.
fred, alice, frank = 2*alice, fred - 1, bill + frank
print("fred =", fred)
print("alice =", alice)
print("frank =", frank )

# Exchange w/o a temp.
fred, alice = alice, fred
print("fred =", fred)
print("alice =", alice)

# Python allows lines to be continued by putting a backslash at the end of
# the first part.  
fred = bill + alice + frank - \
print("fred =", fred)

# The compiler will also combine lines when the line break in contained
# in a grouping pair, such as parens.
joe = 3 * (fred +
        bill - alice)
print ("joe =", fred)

Some things to notice about this code:
  1. When integers are divided, integer division is used, discarding the fractional part. When at least one of the input numbers is floating point, floating division is done preserving the factional part. This is similar to many languages, but not usually to dynamically-typed ones. This means that you can't necessarily tell which type division will be used until you run the program, though this situation is rare in practice.

  2. The print operation automatically adds spaces between the items which is prints, and places a newline at the end. This is convenient, except when you don't want it. We'll see some alternatives later.

  3. The multiple assignment computes all values on the right before assigning anything, an extension of the usual rules for a single assignment. A number of scripting languages have some form of multiple assignment, but few compiled languages do.

  4. The second method of continuing lines seems to be the most common.
<<Hello, World! Strings I>>