Built in operations: + (addition), - (subtraction), * (multiplication), / (division), ** (exponentiation), % (remainder or mod), abs() (absolute value).
One tricky thing about python is that if a mathematical expression involves only integers, the result must be an integer. If an expression has at least one floating point number, the result is a float. Floating point numbers are approximations to real numbers. Usually this approximation is good enough (unless you are flying a spacecraft to Mars or trying to forecast the path of a Hurricane), but the answers may surprise you.
You may want to convert an int to a float. This can be done via casting using e.g., float(3). Alternatively, if we remember that an operation involving a float and an int returns an int, we can convert a possible integer variable val to a float using val=1.0*val, or val=1.*val.
You can import additional math functions from the math library.
>>> from math import * >>> pi 3.1415926535897931 >>> sqrt(2) 1.4142135623730951 >>> sin(pi/4) 0.70710678118654746 >>> sin(pi/2) 1.0 >>> import math >>> help(math) #displays all functions available to you.
If you need to import additional feature use the from <library> import * at the top of your program. You only need to import a library once. If you want to get help on a library, start a python shell, run import <library> followed by help(<library>).
cumin[~]$ python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> range(5) [0, 1, 2, 3, 4] >>>
#List types. A list of what? range(5) range(1,5) range(1,5,2)Think about the following questions and discuss them with a neighbor:
[2, 4, 6, 8] [-1, 0, 1, 2, 3] [0, 3, 6, 9, 12] [1, 1.5, 2, 2.5] [4, 3, 2, 1, 0] [1, 2, 4, 8, 16]
for <var> in <sequence>: <body>Whitespace is significant. Loop body starts when indentation starts. Loop body ends when indentation ends.
for i in range(1,5,2): print i for i in range(3): print "Hello there" print "i=", iTracing. Loop semantics.
Python supports a few standard operations on strings including + (concatenation), * (duplication), and % (string formatting, more later).
>>> s="Swarthmore" >>> for ch in s: ... print ch ... S w a r t h m o r eFor any list, we can also use the function len() to determine the number of items in the list.
>>> len(s) 10 >>> values=range(3) >>> len(values) 3We can also select parts of a list using the indexing operator. Try the following statements in the python shell. What are the semantics of ls, ls[-1], ls[2:4], ls[:-1], and ls[2:]? Try some more examples to experiment.
ls=range(1,11) s="Swarthmore" ls ls[-1] ls[2:4] ls[:-1] ls[2:] s s[-1] s[-4:] s[:3]+s
The primary difference between lists and strings is that lists are mutable while strings are not. Thus, we can change elements in a list, but not in a string.
print ls ls=2009 s='a'
A design pattern is a generic method for solving a class of problems. The standard algorithm might be described as follows:
get input process input and do computation display output
Almost any computational problem can be set up in this very general way, but step two is a very vague. Let's look at another common pattern, the accumulator.
initialize accumulator variable(s) loop until done: update accumulator variable(s) display outputMany useful computational problems fit this pattern. Examples include computing a sum, average, or standard deviation of a list of numbers, reversing a string, or counting the number of times a particular value occurs in a list. Let's try to compute the average of a list of numbers entered by the user. Prompt the user to first enter the number of values he/she wishes to average and then prompt for each number. Finally display the average. Start with pseudocode, a written idea that organizes your thought process. Then write your solution in python and test.
myInt = 86 myFloat = 1./3 print "The value", myInt, "is an integer but ", myFloat, "is not"We can get more control over how data values are displayed using string formatting.
myInt = 86 myFloat = 1./3 print "The value %d is an integer but %0.2f is not" % (myInt, myFloat)Using this new style requires a few steps. First, set up a string that contains one or more formatting tags. All tags have the form %<width><.><precision><type-char>. The type-char is s for strings, d for integers (don't ask why), and f for floats. Do not put any variable names in the format string, just tags which serve as placeholders for data that will come later. After the format string put a single % symbol after the close quote. Finally, place the data elements that you wish to substitute for the tags separated by commas and enclosed in parentheses. Let's step through a few examples in the python shell.
>>> month="Sep" >>> day=17 >>> year=2012 >>> print "Today is %d %s %d" % (day, month, year) Today is 17 Sep 2012 >>> print "Tomorrow is %d/%d/%d" %(9,day+1, year) Tomorrow is 9/18/2012 >>> for val in range(1,200,20): ... print "%7.2f" % (val*6.582118) ... 6.58 138.22 269.87 401.51 533.15 664.79 796.44 928.08 1059.72 1191.36