else
clausesEach if
statement is allowed to have an else
clause,
specifying statements that should be done only when the if
condition fails. In writing this,
the e starting else should line
up directly under the i in if.
password = input()
if password == 'friend':
print('Enter')
else:
print('Fail')
print('Ready')
If the user types friend, the computer will display Enter followed by Ready (skipping over any statements in the
else
block). If the user types something else, then the computer
will display Fail followed by Ready.
for
loop over listsSo far, we have only used the for
loop to iterate over
integers, using the range
function.
However, we can simply name a list after the in
keyword:
primes = [2, 3, 5, 7, 11, 13]
total = 1
for p in primes:
total = total * p
print(total)
Python does the for
loop's body once for each
element in the list. In this case, it does the body with p
being 2, then with p
being 3, then with 5, then with 7, then with
11, and finally with p
being 13.
Thus far, we've seen a wide variety of functions.
abs
int
min
round
str
float
len
sorted
sum
input
max
range
You call a function by first writing the function name, followed by parentheses stating the arguments. The function does some work and provides a return value.
num_letters = len(name)
A method is a different way of getting Python to do some work and produce a return value. However, a method “belongs” to a value, so in calling a method you first write the value followed by a period and the method name, followed by parentheses including any arguments.
num_bs = name.count('e')
This invokes the count
method of the
string name
, passing it the string e as an argument.
As it happens, the count
method counts and returns the number of
times times e appears in name
.
So if name
refers to the string Shannon,
name.count('n')
returns 3.
Python includes many methods — many more than the number of functions. Each type of data has its own set of methods, but for now we'll concentrate just on the methods that strings have. Here are seven worth knowing about at first.
s.lower()
s
is Shannons.upper()
s
is Shannons.trim()
s
is “ Eva Lu ”s.ltrim()
s
is “ Eva Lu ”s.rtrim()
s
is “ Eva Lu ”s.split()
s
,
returning a list of those “words” found;
if s
is
“ Eva Lu Ator ”,
the list [Eva, Lu, Ator] is returned.s.join(words)
words
that is a list of strings, creates a larger
single string containing each string in words
separated by the
string s
;
if s
is “-&-” and
words
is [Eva, Lu, Ator],
s.join(words)
is Eva-&-Lu-&-Ator.