>>> big = max('Hello world')
>>> print big
w
>>> tiny = min('Hello world')
>>> print tiny
>>>
big = max('Hello world')
Argument
'w'
Result
Assignment
Max Function
>>> big = max('Hello world')
>>> print big
'w'
max()
function
“Hello world”
(a string)
‘w’
(a string)
A function is some stored
code that we use. A
function takes some input
and produces an output.
Guido wrote this code
Max Function
>>> big = max('Hello world')
>>> print big
'w'
def max(inp):
blah
blah
for x in y:
blah
blah
“Hello world”
(a string)
‘w’
(a string)
A function is some stored
code that we use. A
function takes some input
and produces an output.
Guido wrote this code
Type Conversions
•
When you put an integer and
floating point in an expression
the integer is implicitly
converted to a float
•
You can control this with the
built in functions int() and float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
<type 'int'>
>>> f = float(i)
>>> print f
42.0
>>> type(f)
<type 'float'>
>>> print 1 + 2 * float(3) / 4 - 5
-2.5
>>>
String
Conversions
•
You can also use int() and
float() to convert between
strings and integers
•
You will get an error if the
string does not contain
numeric characters
>>> sval = '123'
>>> type(sval)
<type 'str'>
>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int'
>>> ival = int(sval)
>>> type(ival)
<type 'int'>
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Building our Own Functions
•
We create a new function using the def keyword followed by optional
parameters in parenthesis.
•
We indent the body of the function
•
This defines the function but does not execute the body of the function
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print 'Yo'
x = x + 2
print x
Hello
Yo
7
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print_lyrics():
Definitions and Uses
•
Once we have defined a function, we can call (or invoke) it as many
times as we like
•
This is the store and reuse pattern
x = 5
print 'Hello'
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print 'Yo'
print_lyrics()
x = x + 2
print x
Hello
Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
•
An argument is a value we pass into the function as its input when we
call the function
•
We use arguments so we can direct the function to do different kinds
of work when we call it at different times
•
We put the arguments in parenthesis after the name of the function
big = max('Hello world')
Argument
Không có nhận xét nào:
Đăng nhận xét