You control what your program (and the computer) does by making decisions, which often involves making comparisons. You use operators to make comparisons. These operators are often referred to as relational operators or comparison operators because by comparing items the computer is determining how two items are related.
if conditional statement (making decisions with if)
The if conditional statement makes use of all the usual comparison operators (such a >, <, >=, <=, ==, !=, and so on) that you would expect to find in any other programming language. Python comes with a few “super” operators of its own, two of which are in and not in. In and not in are the membership operators in Python; they are utilized to test whether a value or variable is found in a sequence (e.g., string, list, tuple, set, and dictionary).
Example 1:
import datetime as dt
this_second = dt.datetime.today().second
print(dt.datetime.today())
print(this_second)
# use == to test for equality between two items. Execute code if condition is true.
if this_second % 2 == 0: # % returns remainder when a number on left is divided by the number on right.
print('This second is an even number') # Execute this line if condition is true.
else:
print('This second is an odd number') # Notice how this line is indented.
print(‘Done!’)
First, we import the datetime module and assign it the name ‘dt’ which is easier to type. We then invoke the method called today which comes with the datetime submodule (meaning it is part of the datetime/dt module). You can tell that today is being invoked due to the standard postfix parentheses: (). When today is invoked, it returns a “time object” (of type datetime.datetime, which contains many pieces of information about the current time). These are the current time’s attributes, which can be accessed via the customary dot-notation syntax. In this program, we are interested in the second attribute, which we can access by appending .second to the method invocation. The resulting value is then assigned to the this_second variable. You can think of this line of code as saying: create an object that represents today’s time, then extract the value of the second attribute before assigning it to a variable.
NOTE: If the condition proves true, the do this line is executed as are any other lines indented equally to that one. The first un-indented line under the if is executed no matter what.
Example 2:
weather == "cold"
if weather == "cold":
print("Wear Coat")
else:
print("Don’t wear coat")
When if … else isn’t enough to handle all the possibilities, there is elif (else if). An if statement can include any number of elif conditions. You can include or not include a final else statement that executes only if the if and all the previous elif statements prove false.
Example 3:
import random
weather = [ 'cold', 'sunny', 'rainy' ]
current_weather = random.choice(weather)
print(current_weather)
if current_weather == "cold":
print("Wear a coat.")
elif current_weather == "sunny":
print("Don’t wear a coat.")
elif current_weather == "rainy":
print("Bring your umbrella.")
First, we import the random module that allows us to generate random objects from a supplied list of items. We then create a list of possible weather conditions and then assign this list to a variable called weather. Next, we use the choice function from random which allows us to pick a random weather condition from within our list object. We proceed to display the weather condition using print function. The next lines use the if and elif statements to check the weather condition and display the message associated with that condition. For instance, if the weather is cold, the message that is displayed is ‘Wear a coat.’
For loop
The for loop is perfect for controlling looping when you know ahead of time how many iterations/loops you need.
Example 1 – This for loop, below, takes a list of numbers and iterates/loops once for each number in the list, displaying the current number on the screen. As it does so, the for loop assigns each number in turn to a loop iteration variable, which is given the name i in this code. Note the indentation and colon. Like the if statements, the code associated with a for statement needs to be indented:
for i in [1, 2, 3, 4]:
print(i)
Example 2 – This for loop, below, iterates over a string, with each character in the string being processed during the iteration. This works because every string in Python is a sequence. A sequence is an ordered collection of objects, and every sequence in Python can be iterated over by the interpreter.
for char in ‘Hello!’
print(char)
Python is smart enough to work out that this string should be iterated over one character at a time and also knows when the string ends.
Example 3 – Iterating over a specific number of times. You can be more exact and specify the number of iterations. This can be achieved using the built-in function called range. Range accepts arguments that dictate how many times the for loop runs. One can specify the start, step, and end of the for loop.
for k in range(4):
print(‘Testing the for loop!’)
Bailing out of a loop
Typically, you want a loop to go through an entire list or range of items, but you can also force a loop to stop early if some condition is met. Use the break statement inside an if statement to force the loop to stop early. Suppose that someone completed an exam and we want to loop through the answers. But we have a rule that says if an answer is empty, we mark it Incomplete and ignore the rest of the items in the list. In the following, all items are answered (no blanks).
answers = ["A", "C", "B", "D"]
for answer in answers:
if answer == "":
print("No answer was provided")
break
print(answer)
print("Loop is done")
The logic is, as long as some answer is provided, the if portion of the code is not executed and the loop runs to completion. However, if the loop encounters a blank answer, it prints Incomplete and also “breaks” the loop, jumping down to the first statement outside the loop (the final un-indented statement), which prints Loop is done.
Looping with continue
You can also use a continue statement in a loop, which is kind of the opposite of break. Whereas break makes code execution jump past the end of the loop and stop looping, continue makes it jump back to the top of the loop and continue with the next item (that is, after the item that triggered the continue). So here is the same code as the preceding example, but instead of executing a break when execution hits a blank answer, it continues with the next item in the list:
answers = ["A", "C", "", "D"]
for answer in answers:
if answer == "":
print("No answer was provided")
continue
print(answer)
print("Loop is done")
The output of that code is as follows. It doesn’t print the blank answer, it prints ‘No answer was provided’, and then it goes back and continues looping through the rest of the items.
Looping with while
The while loop is an alternative to the for loop. The while loop is more appropriate whenever you don’t know in advance the number of iterations/loops required. With for, you often get a specific number of loops, one for each item in a range or one for each item in a list. On the other hand, in a while loop, the loop/iterations keep going as long as the given condition remains true. For this reason, in order to avoid an infinite loop (code keeps going and going unless forced to stop or stops due to an error), you need to make sure that you have in place a statement that makes the loop to eventually stop.
Below is an example where the while condition runs for a finite number of times due to three things: We create a variable named number and give it a starting value (1). We say to run the loop while number variable is less than 7. Inside the loop, we multiple the number by itself and then increase the number by 1 (counter += 1). Increasing by 1 repeatedly eventually increases number value to more than 7, which ends the loop as the condition becomes false.
number = 1
while number < 7:
print(number *number)
number += 1