We will often need to determine whether two numbers are the equal, whether one is greater, lesser, etc. To do this, we use logic operations. Here are some basic logic operations.
print(2 == 3)
print(2 == 2)
We can check if a number is even by using the modulo operation:
print(53 % 2 == 0)
print(2 <= 3)
print(2 > 3)
An exclamation point with an equals means "Not Equal". It will return True if the quantities are not equal. It will return False if the quantities are equal.
print(2 != 3)
The and operation will return true if and only if both statements return true.
print((2 == 2) and (2 < 3))
The following will return False, since it is False that "2 does NOT equal 2" AND "3 equals 3". The statements are not both true.
print((2 != 2) and (3 == 3))
The or operation will return true if at least one of the statements return true.
The following will return True, since at least one of them is true.
print((2 != 2) or (3 == 3))
Sometimes we wish to take an action only if a certain statement is true. To do this, we use If statements. The following snippet of code checks whether the number 37 is even or not. If it is, we print "37 is even". Otherwise, we print "37 is odd".
if (37 % 2 == 0): print("37 is even") else: print("37 is odd")
Sometimes we wish to perform the same operations to several numbers or objects in a row. One way to do this is with for loops. The following code defines an array, and then prints each number one by one with the message "is a cool number!" after each.
import numpy as np coolNumbers=np.array([2,3,5,8,9,14]) for x in coolNumbers: print(x, " is a cool number!")
output: 2 is a cool number!
3 is a cool number!
5 is a cool number!
8 is a cool number!
9 is a cool number!
14 is a cool number!
We can combine the program from the if statement section to check if several numbers are even.
import numpy as np coolNumbers=np.array([2,3,5,8,9,14]) for x in coolNumbers: if (x % 2 == 0): print(x," is even") else: print(x," is odd")
output: 2 is even
3 is odd
5 is odd
8 is even
9 is odd
14 is even
If we wish to perform the above on every number from 1 to 7, we can use Python's range function. The range function has syntax range(start,stop,step), and returns all integers in \([start,stop)\) and counts the numbers up by step. Note that the number entered for stop is not included.
import numpy as np for x in range(1,8,1): if (x % 2 == 0): print(x," is even") else: print(x," is odd")
output: 1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
Another way to construct loops is with the While construct. Instead of going through a list, While loops continues until certain conditions are met. For example, if we want to keep counting through numbers until we get to 20, we can use the following.
n=1 while n<=8: print(n) n=n+1