This page intentionally left blank Python for Software Design


variable: A name that refers to a value. 2.12



tải về 1.38 Mb.
Chế độ xem pdf
trang14/83
Chuyển đổi dữ liệu13.08.2023
Kích1.38 Mb.
#55046
1   ...   10   11   12   13   14   15   16   17   ...   83
- Python for Software Design How to Think Like a Computer Scientist-Cambridge University Press (2009)

variable: A name that refers to a value.
2.12
EXERCISES
Exercise 2.3
Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression and the type
(of the value of the expression):
(1) width / 2
(2) width / 2.0
(3) height / 3
(4) 1 + 2 * 5
(5) delimiter * 5
Use the Python interpreter to check your answers.


20
Variables, Expressions, and Statements
Exercise 2.4
Practice using the Python interpreter as a calculator:
(1) The volume of a sphere with radius is
4
3
πr
3
. What is the volume of a sphere
with radius 5? Hint: 392.6 is wrong!
(2) Suppose the cover price of a book is $24.95, but bookstores get a 40% discount.
Shipping costs $3 for the first copy and 75 cents for each additional copy. What
is the total wholesale cost for 60 copies?
(3) If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile),
then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time
do I get home for breakfast?


3
Functions
3.1
FUNCTION CALLS
In the context of programming, a function is a named sequence of statements that
performs a computation. When you define a function, you specify the name and the
sequence of statements. Later, you can “call” the function by name. We have already
seen one example of a function call:
>>> type(32)

The name of the function is type. The expression in parentheses is called the
argument of the function. The result, for this function, is the type of the argument.
It is common to say that a function “takes” an argument and “returns” a result. The
result is called the return value.
3.2
TYPE CONVERSION FUNCTIONS
Python provides built-in functions that convert values from one type to another. The
int
function takes any value and converts it to an integer, if it can, or complains
otherwise:
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int(): Hello
21


22
Functions
int
can convert floating-point values to integers, but it doesn’t round off; it chops
off the fraction part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
float
converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float('3.14159')
3.14159
Finally, str converts its argument to a string:
>>> str(32)
'32'
>>> str(3.14159)
'3.14159'

tải về 1.38 Mb.

Chia sẻ với bạn bè của bạn:
1   ...   10   11   12   13   14   15   16   17   ...   83




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương