100 days of code: Day 12 - conditionals

Last modified on 2020-06-20

Source: 100-days-of-code

Conditionals are statements that can be evaluated as either True or False. I can use these Boolean values in my programs to determine whether or not a block of code should be executed. I made a program - conditional_tests.py - that makes a series of statements about a list of Mars rovers and checks to see if they are True or False …

rovers = ['Sojourner', 'Spirit', 'Opportunity', 'Curiosity', 'Perseverance', 
            'Rosalind Franklin']

print("Mars rovers are vehicles that travel across the surface of Mars.\n")

# Test for equality and inequality with strings.
print(rovers[1] + " is the longest name of all the Mars rovers.")
print(rovers[0] == rovers[1])
print(rovers[3] + " is a shorter name for a rover than " + rovers[4] + ".")
print(rovers[3] != rovers[4])

# Numerical tests
list = len(rovers)
print("Are there 10 rovers on the list?")
print(list == 10)
print("More than 10 rovers?")
print(list > 10)
print("9 or less rovers?")
print(list <= 9)
print("5 or more rovers?")
print(list >= 5)
print("But its not actually 5, is it?")
print(list != 5)
print("6 rovers?")
print(list == 6)

# Test whether an item is in the list
rover = 'huoxing-1'
print(f"Is the upcoming Chinese rover {rover.title()} on the list?")
print(rover in rovers)

# Test whether an item is not in the list
rover = 'Zephyr'
print(f"Is the proposed rover {rover} not on the list (because its only a proposal)?")
print(rover not in rovers)

# Test using the and keyword and the or keyword
rover = rovers[0]
rover1 = rovers[1]
print(f"Is {rover} and {rover1} on the list?")
print(rover in rovers and rover1 in rovers)

rover = rovers[-2]
rover1 = 'Viking 1'
print(f"Is either {rover1} or {rover} on the list?")
print(rover in rovers or rover1 in rovers)

# Show the list
print("Why is this list of Mars rovers so secret?! Just show me the list "
        + "already.")
for rover in rovers:
    print("* " + rover)

Run …

$ ./conditional_tests.py 
Mars rovers are vehicles that travel across the surface of Mars.

Spirit is the longest name of all the Mars rovers.
False
Curiosity is a shorter name for a rover than Perseverance.
True
Are there 10 rovers on the list?
False
More than 10 rovers?
False
9 or less rovers?
True
5 or more rovers?
True
But its not actually 5, is it?
True
6 rovers?
True
Is the upcoming Chinese rover Huoxing-1 on the list?
False
Is the proposed rover Zephyr not on the list (because its only a proposal)?
True
Is Sojourner and Spirit on the list?
True
Is either Viking 1 or Perseverance on the list?
True
Why is this list of Mars rovers so secret?! Just show me the list already.
* Sojourner
* Spirit
* Opportunity
* Curiosity
* Perseverance
* Rosalind Franklin

Happy hacking!