Lesson3 Python
Lesson3 Python
Conditional Statements
Boolean Expressions
For and While Loops
Break and Continue
Zip and Enumerate
List Comprehensions
If Statement
An if statement is a conditional statement that runs or skips code based
on whether a condition is true or false. Here's a simple example.
if phone_balance < 5:
phone_balance += 10
bank_balance -= 10
Let's break this down.
2. elif: elif is short for "else if." An elif clause is used to check for an
additional condition if the conditions in the previous clauses in
the if statement evaluate to False. As you can see in the example, you
can have multiple elif blocks to handle different situations.
3. else: Last is the else clause, which must come at the end of
an if statement if used. This clause doesn't require a condition. The
code in an else block is run if all conditions above that in
the if statement evaluate to False.
Indentation
Some other languages use braces to show where blocks of code begin
and end. In Python we use indentation to enclose blocks of code. For
example, if statements use indentation to tell Python what code is
inside and outside of different clauses.
In Python, indents conventionally come in multiples of four spaces. Be
strict about following this convention, because changing the indentation
can completely change the meaning of the code. If you are working on a
team of Python programmers, it's important that everyone follows the
same indentation convention!
For Loops
Python has two kinds of loops - for loops and while loops. A for loop
is used to "iterate", or do something repeatedly, over an iterable.
An iterable is an object that can return one of its elements at a time.
This can include sequence types, such as strings, lists, and tuples, as
well as non-sequence types, such as dictionaries and files.
Example
Let's break down the components of a for loop, using this example
with the list cities:
cities = ['new york city', 'mountain view', 'chicago', 'los angeles']
for city in cities:
print(city)
print("Done!")
Components of a for Loop
1. The first line of the loop starts with the for keyword, which signals
that this is a for loop
2. Following that is city in cities, indicating city is the iteration
variable, and cities is the iterable being looped over. In the first
iteration of the loop, city gets the value of the first element in cities,
which is “new york city”.
3. The for loop heading line always ends with a colon :
4. Following the for loop heading is an indented block of code, the body
of the loop, to be executed in each iteration of this loop. There is only
one line in the body of this loop - print(city).
5. After the body of the loop has executed, we don't move on to the next
line yet; we go back to the for heading line, where the iteration
variable takes the value of the next element of the iterable. In the
second iteration of the loop above, city takes the value of the next
element in cities, which is "mountain view".
6. This process repeats until the loop has iterated through all the
elements of the iterable. Then, we move on to the line that follows the
body of the loop - in this case, print("Done!"). We can tell what the next
line after the body of the loop is because it is unindented. Here is
another reason why paying attention to your indentation is very
important in Python!
Executing the code in the example above produces this output:
new york city
mountain view
chicago
los angeles
Done!
You can name iteration variables however you like. A common pattern
is to give the iteration variable and iterable the same names, except
the singular and plural versions respectively (e.g., 'city' and 'cities').
Building Dictionaries
By now you are familiar with two important concepts: 1) counting
with for loops and 2) the dictionary get method. These two can actually
be combined to create a useful counter dictionary, something you will
likely come across again. For example, we can create a
dictionary, word_counter , that keeps track of the total count of each word
in a string.
The following are a couple of ways to do it:
While Loops
For loops are an example of "definite iteration" meaning that the loop's
body is run a predefined number of times. This differs from "indefinite
iteration" which is when a loop repeats an unknown number of times and
ends when some condition is met, which is what happens in a while loop.
Here's an example of a while loop.
card_deck = [4, 11, 8, 5, 13, 2, 8, 10]
hand = []
# adds the last element of the card_deck list to the hand list
# until the values in hand add up to 17 or more
while sum(hand) < 17:
hand.append(card_deck.pop())
This example features two new functions. sum returns the sum of the
elements in a list, and pop is a list method that removes the last element
from a list and returns it.
Components of a While Loop
1. The first line starts with the while keyword, indicating this is
a while loop.
2. Following that is a condition to be checked. In this example,
that's sum(hand) <= 17.
3. The while loop heading always ends with a colon :.
4. Indented after this heading is the body of the while loop. If the condition
for the while loop is true, the code lines in the loop's body will be
executed.
5. We then go back to the while heading line, and the condition is evaluated
again. This process of checking the condition and then executing the loop
repeats until the condition becomes false.
6. When the condition becomes false, we move on to the line following the
body of the loop, which will be unindented.
The indented body of the loop should modify at least one variable in the
test condition. If the value of the test condition never changes, the result
is an infinite loop!
Break, Continue
Sometimes we need more control over when a loop should end, or skip
an iteration. In these cases, we use the break and continue keywords,
which can be used in both for and while loops.
break terminates a loop
continue skips one iteration of a loop
Watch the video and experiment with the examples below to see how
these can be helpful.
In the video above, at the 0:55 mark, the instructor says "... you can
separate it into an items and weights list, like this," but she should
instead say, "... you can separate it into an items tuple and a
weights tuple, like this."
Zip
zip returns an iterator that combines multiple iterables into one
sequence of tuples. Each tuple contains the elements in that position
from all the iterables. For example, printing
list(zip(['a', 'b', 'c'], [1, 2, 3])) would output [('a', 1), ('b', 2),
('c', 3)].
Like we did for range() we need to convert it to a list or iterate through it
with a loop to see the elements.
You could unpack each tuple in a for loop like this.
letters = ['a', 'b', 'c']
nums = [1, 2, 3]
Enumerate
enumerate is a built in function that returns an iterator of tuples containing
indices and values of a list. You'll often use this when you want the index
along with each element of an iterable in a loop.
letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
print(i, letter)
This code would output:
0 a
1 b
2 c
3 d
4 e
List Comprehensions
In Python, you can create lists really quickly and concisely with list
comprehensions. This example from earlier:
capitalized_cities = []
for city in cities:
capitalized_cities.append(city.title())
can be reduced to:
capitalized_cities = [city.title() for city in cities]
List comprehensions allow us to create a list using a for loop in one
step.
You create a list comprehension with brackets [], including an
expression to evaluate for each element in an iterable. This list
comprehension above calls city.title() for each
element city in cities, to create each element in the new
list, capitalized_cities.
Conditionals in List Comprehensions
You can also add conditionals to list comprehensions (listcomps).
After the iterable, you can use the if keyword to check a condition in
each iteration.
squares = [x**2 for x in range(9) if x % 2 == 0]
The code above sets squares equal to the list [0, 4, 16, 36, 64], as x to
the power of 2 is only evaluated if x is even. If you want to add an else,
you will get a syntax error doing this.
squares = [x**2 for x in range(9) if x % 2 == 0 else x + 3]
If you would like to add else, you have to move the conditionals to the
beginning of the listcomp, right after the expression, like this.
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(9)]
List comprehensions are not found in other languages, but are very
common in Python.