Learning to program is hard and there are lots of points of confusion among beginners. Here are some reminders and demonstrations to help overcome some of the most common.
return
something from the function to us it.Variables inside the function do not exist after the function has finished executing.
This return
is the last thing done by the function.
On it's own, the following function does nothing
def concatenate(string1, string2):
combined_string = string1 + string2
return combined_string
If we call it but do not do something with the output, it is lost.
concatenate('ethan', 'white')
print combined_string
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-882da32f77aa> in <module>() 1 concatenate('ethan', 'white') ----> 2 print combined_string NameError: name 'combined_string' is not defined
If we store the output then we can use it, or we can use it directly.
result = concatenate('ethan', 'white')
print result
ethanwhite
print "The name of our professor is %s" % concatenate('ethan ', 'white')
The name of our professor is ethan white
But, this only works if we have returned the value explicitly.
def concatenate(string1, string2):
combined_string = string1 + string2
result = concatenate('ethan', 'white')
print result
None
Only one set of commands in an if/elif/else block will execute. If multiple sets of conditions are met, then the first set of conditions will be used.
a = 10
b = 20
if a > 15:
print 1
elif a == 10 and b < 100:
print 2
elif b == 20:
print 3
else:
print 4
2
If we wanted to actually check all of the conditions, regardless of what had already happened, then we would just want a series of if statements.
a = 10
b = 20
if a > 15:
print 1
if a == 10 and b < 100:
print 2
if b == 20:
print 3
else:
print 4
2 3
However, in this case the else
will only apply to the last if statement.
Methods are functions that are attached to particular objects and they operate on those objects. As a result, sometimes they do not require arguments (but sometimes they do).
mystring = "hello world"
print mystring.upper()
print mystring.count('l')
HELLO WORLD 3
None
¶In contrast to String methods, methods that work on lists often change the list
and return a special keyword None
.
mylist = [1, 3, 4, 2, 7]
print mylist.sort()
print mylist
None [1, 2, 3, 4, 7]
This means that an easy mistake to make is to treat lists methods like we do most things
and end up replacing our list with None
.
mylist = [1, 3, 4, 2, 7]
mylist = mylist.sort()
print mylist
None