Exercise 1
We have learned how parse data based on a given condition. Using what you have learned
so far (in this lesson and previous ones), write a short program that utilizes conditionals
(if/elif/else) to separate the pair and odd years on this list:
year = [1946, 1949, 1950, 1969, 1981, 1985, 1999, 2012]
Solution
year = [1946, 1949, 1950, 1969, 1981, 1985, 1999, 2012]
for y in year:
if y % 2 == 0:
print("This year is an even number: ", y)
else:
print("This year is an odd number: ", y)
Exercise 2.1
We can also use conditionals to parse strings within a list based on a given characteristic.
In the following exercise, write code that can be used to separate names that start with a vowel
from those that start with a consonant.
names = ["Todd", "Trixie", "Samuel", "Zoe", "Sheila", "Daniel", "Amy", "Adam"]
Solution
names = ["Todd","Trixie","Samuel","Zoe","Sheila","Daniel","Amy","Adam"]
for n in names:
if n[0] in "AEIOU":
print("This name starts with a vowel: ", n)
else:
print("This name starts with a consonant: ", n)
Exercise 2.2
Conditional can be used within conditionals using the proper indentation. In the following exercise,
use two sets of conditionals to identify the: a) names that start and end with a vowel, and b) names
that start with a consonant and end with a vowel.
Solution
other_names = ["Amaranta","Brent","Marie","Andrew","Doug"]
for n in other_names:
if n[0] in "AEIOU":
if n[len(n)-1] in "aeiou":
print("This name starts and ends with a vowel: ", n)
else:
if n[len(n)-1] in "aeiou":
print("This name starts with a consonant and ends with a vowel: ", n)
Exercise 2.3
Find an alternative of writing the first conditional by using the boolean operator: and
Solution
other_names = ["Amaranta","Brent","Marie","Andrew","Doug"]
for n in other_names:
if n[0] in "AEIOU" and n[len(n)-1] in "aeiou":
print("This name starts and ends with a vowel: ", n)
Exercise 1
We have learned how parse data based on a given condition. Using what you have learned
so far (in this lesson and previous ones), write a short program that utilizes conditionals
(if/elif/else) to separate the pair and odd years on this list:
year = [1946, 1949, 1950, 1969, 1981, 1985, 1999, 2012]
Solution
Exercise 2.1
We can also use conditionals to parse strings within a list based on a given characteristic.
In the following exercise, write code that can be used to separate names that start with a vowel
from those that start with a consonant.
names = ["Todd", "Trixie", "Samuel", "Zoe", "Sheila", "Daniel", "Amy", "Adam"]
Solution
Exercise 2.2
Conditional can be used within conditionals using the proper indentation. In the following exercise,
use two sets of conditionals to identify the: a) names that start and end with a vowel, and b) names
that start with a consonant and end with a vowel.
Solution
Exercise 2.3
Find an alternative of writing the first conditional by using the boolean operator: and
Solution