Think Python C2: Difference between revisions

From XPUB & Lens-Based wiki
(New page: = Chapter 2: Variables, expressions and statements = == Exercise 2.1 == Numbers starting with a 0 are interpreted as being "octal" (or base-8). So 010 represents 8 (1 eights and 0 ones),...)
 
(→‎Exercise 2.4: pwetty color)
 
(One intermediate revision by the same user not shown)
Line 29: Line 29:
== Exercise 2.4 ==
== Exercise 2.4 ==


(4*pi/3)*(5**3)
<source lang="python">
#!/usr/bin/python
 
# 1. Sphere
r = 5
pi = 3.14159265
vol = (4.0/3.0)*pi*(r**3)
 
print vol
 
# 2. Books
book = 24.95*0.4
order = 60
shipping = (order - 1)*0.75+3
wholesale = book*order+shipping
 
print wholesale
</source>

Latest revision as of 12:44, 5 January 2009

Chapter 2: Variables, expressions and statements

Exercise 2.1

Numbers starting with a 0 are interpreted as being "octal" (or base-8). So 010 represents 8 (1 eights and 0 ones), and 011 is nine (1 eights and 1 ones). It can be sometimes be convenient to write computer-specific numbers in octal notation (such as UNIX file permissions), this is because 8 better fits the way computer memory is organized than normal decimal (base-10) notation.

Exercise 2.3

>>> width/2
8
>>> type(width/2)
<type 'int'>
>>> width/2.0
8.5
>>> type(width/2.0)
<type 'float'>
>>> 1+2*5
11
>>> type(1+2*5)
<type 'int'>
>>> delimiter*5
'.....'
>>> type(delimiter*5)
<type 'str'>

Exercise 2.4

#!/usr/bin/python

# 1. Sphere
r = 5
pi = 3.14159265
vol = (4.0/3.0)*pi*(r**3)

print vol

# 2. Books
book = 24.95*0.4
order = 60
shipping = (order - 1)*0.75+3
wholesale = book*order+shipping

print wholesale