利用者:Kilon/Python book of magic/06.If
"What if?"
Humans are amazing beings, capable for extraordinary good an evil, but what is most extraordinary is their ability to improve and adjust. There is not doubt that Knowledge is the ultimate power, the most arcane form of magic, without it we can not go forward, without it none of the amazing feats and accomplishments or even disasters of our civilization would have occurred. And what gives birth to knowledge is the ability to ask questions and seek answers. Every atom of knowledge has been conquered by asking the ultimate question.
WHAT IF?
It stands to reason that we want to infuse this capability to code as well, that we want to build applications that are intelligent, that can take action according to decisions of the user and the programm itself. We want a program that is intelligent. We want a program that asks
WHAT IF?
Boolean Type
In order to be able to answer any question we must be able to compare things, Comparison is an essential part of knowledge and decision making, without it we cant move forward. So its comes as no surprise that python has its own data type that can store result of comparison. And what most important comparison there is than whether a statement is True or False?
Assigning a boolean type is straight forward
a = True
b = False
Boolean is an extremely basic type, it can only take a value True or False, nothing else. All this is good but how do we compare different data?
#two assignments used to explain the four different comparisons of numbers
a = 1
b = 5
a > b
a < b
a == b
a != b
Apart from the first 2 lines that are assignments, the rest means the following:
- Is a more than b? 1 is less than 5. Returns False
- Is a less than b? 1 is less than 5. Returns True
- Is a equal to b? 1 is not equal to 5. Returns False
- Is a not equal to b? 1 is not equal to 5. Return True
There are some more comparisons possible between numbers <= (less or equal) as well as >= (greater or equal).
If statement
Because python is such an easy programming language all it takes to ask a "what if" question is a if statement like the following:
a = 1
b = 5
if a < b:
print("Yes a is less than b")
if a > b:
print("No a is more than b")
if a == b:
print("Aaaah a is equal to b")
This will give use the desired result, an alternative version is this
a = 1
b = 5
if a < b:
print("Yes a is less than b")
elif a > b:
print("No a is more than b")
elif a == b:
print("Aaaah a is equal to b")
elif is not different from if other than the fact it needs at least one if to exist before it. Its just a way to make our code more readable and easier to understand, elif help us understand that comparisons are around a specific data set, and there is a relation between them. Observe that the equal comparison is == and not =. This extremely important to remember. = is used ONLY for assignment and == ONLY for comparison. Another way of doing this is this.
if (a == 5) < (b == a):
print("Yes a is less than b")
elif a > b:
print("No a is more than b")
else:
print("Aaaah a is equal to b")
Observe that we did the assignment inside the if statement this is completely legit, and that is why it is crucial to use == for equal comparison. Also we replaced the equal comparison with an else, this is also legit cause we already examine all the other possibilities in the previous 2 ifs so else can be only equal.
Another way
a = 1
b = 5
if a < b:
print("Yes a is less than b")
elif not a < b:
print("No a is more than b")
elif a == b:
print("Aaaah a is equal to b")
not command reverses the boolean type. For example not True is False and not False is True. So in this case instead of a > b, we did, not a < b. The problem is that in this case we capture the possibility of a being equal to b, because in that case of a being equal to be means that a is not less than b. So in this case that a may be equal to b both last 2 prints will be executed. To correct it do the following.
a = 1
b = 5
if a < b:
print("Yes a is less than b")
elif not a < b and (not a == b):
print("No a is more than b")
elif a == b:
print("Aaaah a is equal to b")
and command takes 2 booleans and unites them in one boolean, the boolean is True if both booleans are true any other combination will result into False.
So in this case a <b is examined first then its boolean is reversed by "not" then a==b then not reverses the boolean of a==b and then and unites the 2 booleans into one. Remember always substatements inside ifs are executed only when if is true. In this case a =1 and b =5 so the following happens.
- 1 < 5 -> True
- not True -> False
- 1 == 5 ->False
- not False -> True
- False and True -> False
- If statement returns False so print("No a is more than b") is not executed.
If we want one of them to be true we can use "or" command instead. We use also parentheses because parentheses dictates the order of execution so in this case first "not a == b" comparison is executed and then the "and" comparison. You can use parentheses also with mathematical operations again to dictate in what order the execution/operation will be performed. For example ((((1*2)*3)/4)+5)
Lastly but not least we can encapsulate if statements inside other ifs like this
a = 1
b = 5
if a < b:
if not a < b:
if not a == b:
print("Yes a is less than b")
we use always spaces to indicate that python statements/commands are associated with other substatements. So its possible this way to sub statement inside statements and of course sub sub statements and sub sub sub statements etc.In this case print("Yes a is less than b") will execute only if all associated ifs return True.
Another thing we can do with ifs is to examine whether something is part of something else. For example:
alist = ["john", "mary", "david"]
name= "john"
if name in alist:
print("Yes the value of variable name is also inside the alist")
Here we examine whether the string "john" exist also inside our list, alist, with the in command.
Dont worry if that stretches your brain abit more, you cant expect the magic to energize inside because you just read something, do your own test, experiment with this code and dont worry as long you have a vague understanding its more than enough because we are going to use all these concepts again and again and again, till they become second nature to you
Now what you waiting for? Go make an intelligent python program, maybe use some user input as well with the input function make your own Borg Cube that can asks question and replies with intelligence. I guarantee you will have loads and loads of fun.
And if you hesitate to start your own Borg cube here is a sample to get you going
print("We are the Borg resistance is futile !!!")
being = input("What species are you? ")
if not (being == "human" or being =="HUMAN" or being == "Human"):
print("We have assimilated your species")
else:
print("we have not assimilated humans yet")
name = input("Whats your name? ")
if name == "oprah" or name == "OPRAH" or name == "Oprah":
print("We hate Oprah, aaaaahhhhh")
print(" Box cube goes to warp speed and abandons the galaxy")
else:
print("%s prepare for assimilation" % name)
Exercise: Improving upon the above example
As you can see, when comparing strings for equality, case sensitivity once again matters. Typing out the different conditions quickly can become tedious, so let's make our life easier by simply converting the the string to lowercase beforehand. Luckily, the string type provides the utility function lower() for this:
"sPaMsPAmSPAm".lower()
evaluates to:
'spamspamspam'
(Note that we can enclose strings either in double or single quotes - it makes no difference that is relevant for now, but the python interpreter will put strings in single quotes)
Thus, this will work for any combination of upper and lower case input:
if not (being.lower() == "human"):
print("We have assimilated your species")
else:
print("we have not assimilated humans yet")
Of course, it would be a bit presumptuous even for the Borg to claim that they have assimilated all possible species. Let assimilated_species be a list of species known to have been assimilated by the Borg:
assimilated_species = ["Arturis", "Ferengi", "Talaxian", "Kazon"]
(Completing this list is left as an exercise for the reader)
Remember the in keyword from earlier? We can use it to check whether a given element is contained in a collection (such as our list here):
if being.lower() in assimilated_species:
print("We have assimilated your species")
else:
print("we have not assimilated %s yet" % being)
(Python will use the equality criterion to determine this, thus string case sensitivity matters once more)
So, pay attention: your list of assimilated_species should all be lower-case! Or you use listcomprehension (in boldface) to change on the fly all your elements of assimilated_species too to lower-case:
if being.lower() in [el.lower() for el in assimilated_species]:
UNLEASH THE MAGIC!!!!!