def sphereVol(radius):
import math
vol = 4.0 / 3.0 * math.pi * radius ** 3
# exponentiation has higher precedence than multiplication!
return vol
print(sphereVol(5))
def method1(dividend, divisor):
# use +, -, * and / operators
quotient = dividend / divisor
remainder = dividend - quotient * divisor
return remainder
def method2(dividend, divisor):
# use divmod function
quotient, remainder = divmod(dividend, divisor)
return remainder
def method3(dividend, divisor):
# use % operator
return dividend % divisor
print(method1(42, 5))
print(method2(42, 5))
print(method3(42, 5))
/Users/tef> sudo pip3 install http://www.rbvi.ucsf.edu/Outreach/pc204/swampy-2.1.7.tar.gz
Password:
Collecting http://preview.rbvi.ucsf.edu/Outreach/pc204/swampy-2.1.7.tar.gz
Downloading http://preview.rbvi.ucsf.edu/Outreach/pc204/swampy-2.1.7.tar.gz (49kB)
Installing collected packages: swampy
Running setup.py install for swampy ... done
Successfully installed swampy-2.1.7
I needed the "sudo" and associated password because the directory
where the package of files gets installed is not writable by most users.
If you get an error about the pip command "not found", just Google for "how to install pip" and follow the given directions.
import swampy.TurtleWorld
import swampy.TurtleWorld
world = swampy.TurtleWorld.TurtleWorld()
import swampy.TurtleWorld as tw
world = tw.TurtleWorld()
import swampy.TurtleWorld as tw
world = tw.TurtleWorld() # create a new world
bob = tw.Turtle() # create a new turtle
print(bob) # print out what kind of thing "bob" is
tw.fd(bob, 100) # move bob forward 100 steps
tw.rt(bob) # turn bob to the right
tw.fd(bob, 100) # move forward 100 steps
tw.rt(bob) # turn right, and so on
tw.fd(bob, 100)
tw.rt(bob)
tw.fd(bob, 100)
tw.rt(bob)
tw.wait_for_user() # pause and wait for the user to close the window
import swampy.TurtleWorld as tw
world = tw.TurtleWorld()
bob = tw.Turtle()
print(bob)
for i in range(4):
tw.fd(bob, 100)
tw.rt(bob)
tw.wait_for_user()
import swampy.TurtleWorld as tw
def square(t, edgeLength):
for i in range(4):
tw.fd(t, edgeLength)
tw.rt(t)
world = tw.TurtleWorld()
bob = tw.Turtle()
square(bob, 100) # call the "square" function
tw.wait_for_user()
import swampy.TurtleWorld as tw
def polygon(t, n, edgeLength):
angle = 360.0 / n;
for i in range(n):
tw.fd(t, edgeLength)
tw.rt(t, angle)
world = tw.TurtleWorld()
bob = tw.Turtle()
polygon(bob, 15, 100)
tw.wait_for_user()
def circle(t, radius):
import math # import the Python math module
circumference = 2 * math.pi * radius
numSides = 100
edgeLength= circumference / numSides
polygon(t, numSides, edgeLength)
def circle(t, radius):
import math
circumference = 2 * math.pi * radius
numSides = int(circumference / 3) + 1
edgeLength= circumference / numSides
polygon(t, numSides, edgeLength)
Now the number of sides is approximately 1/3 of the circumference,
which produces reasonable nice looking circles regardless of size.
import swampy.TurtleWorld as tw
def circle(t, radius):
import math
circumference = 2 * math.pi * radius
numSides = int(circumference / 3) + 1
edgeLength= circumference / numSides
polygon(t, numSides, edgeLength)
def polygon(t, n, edgeLength):
angle = 360.0 / n;
for i in range(n):
tw.fd(t, edgeLength)
tw.rt(t)
world = tw.TurtleWorld()
bob = tw.Turtle()
bob.delay = 0.01 # draw faster
polygon(bob, edgeLength=100, n=5) # note use of parameter names
wait_for_user()
import swampy.TurtleWorld as tw
def circle(t, radius):
import math
circumference = 2 * math.pi * radius
numSides = int(circumference / 3) + 1
edgeLength= circumference / numSides
polygon(t, numSides, edgeLength)
def polygon(t, n=4, edgeLength=50): # note use of default parameters
angle = 360.0 / n;
for i in range(n):
tw.fd(t, edgeLength)
tw.rt(t)
def move(x, y):
tw.pu(bob) # "pen up"
tw.bk(bob, x) # back "x" units
tw.lt(bob)
tw.fd(bob, y) # up "y" units
tw.rt(bob)
tw.pd(bob) # "pen down"
world = tw.TurtleWorld()
bob = tw.Turtle()
bob.delay = 0.01
polygon(bob, edgeLength=100, n=5) # note use of parameter names
move(150, 150)
polygon(bob, edgeLength=50) # note number of sides not given
tw.wait_for_user()
import swampy.TurtleWorld as tw
But Chapter 4 of ThinkPython does this...
from swampy.TurtleWorld import *
Importing this way is now considered poor programming practice.
The problem with this approach is that all of the functions in the TurtleWorld module
become part of our "namespace." So if TurtleWorld happened to have a function
called polygon() its definition would conflict with our definition
of polygon(). The former approach to importing avoids this issue, since
functions in the TurtleWorld module are always referenced as "tw.something".
if test_expression1:
statement_block_1 # these statements executed if test_expression evalutes to true
elif test_expression2:
statement_block_2 # if expression1 is false but expression2 is true
else:
statement_block_3 # if neither expression1 nor expression2 are true
Operator | Meaning |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
>= | Greater than or equal |
<= | Less than or equal |
a = 42
if a == 42:
print("a equals 42")
if a % 2 == 0:
print("a is even")
else:
print("a is odd")
s1 = "today is the first day"
s2 = "of the rest of your life"
if s1 != s2:
print("the strings are different")
if s1 < s2:
print("s1 is less than s2")
a = 9
b = 12
a<b, a==b, a>b, b>=a
(True, False, False, True)
if a % 2 == 0:
# here's one level of indentation
y = 3.1415 * 2 / r
if y > 360:
# here's another level of indentation
print("y greater than 360")
y = y - 360
# now we're back to the first level of indentation
z = y / 4
# now there's no indentation
# and if the "if a % 2 == 0" wasn't true this is where execution would have jumped to
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
print(factorial(10))
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
print(factorial(10))
def factorial(n):
if n == 1:
return n / 0 # dividing by zero causes a run time error
else:
return n * factorial(n-1)
Traceback (most recent call last):
File "factorial.py", line 7, in ?
print(factorial(10))
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 5, in factorial
return factorial(n-1) * n
File "factorial.py", line 3, in factorial
n / 0
ZeroDivisionError: integer division or modulo by zero
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
print(factorial(0))
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n-1)
def factorial(n):
"""Return the factorial of integer n"""
if type(n) != type(1):
print("n must be an integer")
return None
if n < 0:
print("factorial only defined for positive integers")
return None
if n <= 1:
return 1
else:
return n * factorial(n-1)
print(factorial.__doc__)
/Users/tef> python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import swampy.TurtleWorld as tw
>>> print(tw.TurtleWorld.__doc__)
An environment for Turtles and TurtleControls.
>>>
>>> print(tw.Turtle.__doc__)
Represent a Turtle in a TurtleWorld.
Attributes:
x: position (inherited from Animal)
y: position (inherited from Animal)
r: radius of shell
heading: what direction the turtle is facing, in degrees. 0 is east.
pen: boolean, whether the pen is down
color: string turtle color
>>> ^D
/Users/tef>
Help on class Turtle in module swampy.TurtleWorld:
class Turtle(swampy.World.Animal)
| Represents a Turtle in a TurtleWorld.
|
| Attributes:
| x: position (inherited from Animal)
| y: position (inherited from Animal)
| r: radius of shell
| heading: what direction the turtle is facing, in degrees. 0 is east.
| pen: boolean, whether the pen is down
| color: string turtle color
|
| Method resolution order:
| Turtle
| swampy.World.Animal
| __builtin__.object
|
| Methods defined here:
|
| __init__(self, world=None)
|
| bk(self, dist=1)
| Moves the turtle backward by the given distance.
|
| draw(self)
| Draws the turtle.
|
| fd(self, dist=1)
| Moves the turtle foward by the given distance.
|
| get_heading(self)
| Returns the current heading in degrees. 0 is east.
|
| get_x(self)
| Returns the current x coordinate.
|
| get_y(self)
| Returns the current y coordinate.
|
| lt(self, angle=90)
| Turns left by the given angle.
|
| pd(self)
| Puts the pen down (active).
|
| pu(self)
| Puts the pen up (inactive).
|
| rt(self, angle=90)
| Turns right by the given angle.
|
| set_color(self, color)
| Changes the color of the turtle.
|
| Note that changing the color attribute doesn't change the
| turtle on the canvas until redraw is invoked. One way
| to address that would be to make color a property.
|
| set_pen_color(self, color)
| Changes the pen color of the turtle.
|
| step(self)
| Takes a step.
|
| Default step behavior is forward one pixel.
|
| ----------------------------------------------------------------------
| Methods inherited from swampy.World.Animal:
|
| die(self)
|
| lt(self, angle=90)
| Turns left by the given angle.
|
| pd(self)
| Puts the pen down (active).
|
| pu(self)
| Puts the pen up (inactive).
|
| rt(self, angle=90)
| Turns right by the given angle.
|
| set_color(self, color)
| Changes the color of the turtle.
|
| Note that changing the color attribute doesn't change the
| turtle on the canvas until redraw is invoked. One way
| to address that would be to make color a property.
|
| set_pen_color(self, color)
| Changes the pen color of the turtle.
|
| step(self)
| Takes a step.
|
| Default step behavior is forward one pixel.
|
| ----------------------------------------------------------------------
| Methods inherited from swampy.World.Animal:
|
| die(self)
| Removes the animal from the world and undraws it.
|
| polar(self, x, y, r, theta)
| Converts polar coordinates to cartesian.
|
| Args:
| x, y: location of the origin
| r: radius
| theta: angle in degrees
|
| Returns:
| tuple of x, y coordinates
|
| redraw(self)
| Undraws and then redraws the animal.
|
| set_delay(self, delay)
| Sets delay for this animal's world.
|
| delay is made available as an animal attribute for backward
| compatibility; ideally it should be considered an attribute
| of the world, not an animal.
|
| Args:
| delay: float delay in seconds
|
| undraw(self)
| Undraws the animal.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from swampy.World.Animal:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| delay
0! = 1
n! = n(n-1)!
Or the definition of the fibonacci sequence of numbers...
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)