Python 101 (part 2): If Wishes Were Pythons - Time For Lunch
(Page 9 of 9 )
Python also allows you to combine multiple conditional tests with the "and", "or" and "not" logical operators. If you consider the following code snippet,
if weekday == "Thursday":
if time == "12":
if place == "Italy":
lunch = "pasta"
you'll agree that is both complex and frightening. And so, in
addition to the comparison operators we've used so liberally thus far, Python also provides the "and", "or" and "not" logical operators which allow you to group conditional expressions together. The following table should make this clearer.
Assume delta = 12, gamma = 12 and omega = 9
delta == gamma and delta > omega
True
delta == gamma and delta < omega
False
delta == gamma or delta < omega
True
delta > gamma or delta < omega
False
not delta
False
Given this knowledge, it's a simple matter to rewrite
the example above in terms of logical operators:
if weekday == "Thursday" and time == "12" and place == "Italy":
lunch = "pasta"
Simple and elegant, wot?
And that's about it for the
moment. You've learned a lot today - you now know how to manipulate strings and numbers, obtain user input from the command line, and use the "if" family of conditional statements to control the flow of your program.
In the next article, I'll be discussing some of Python's loops, together with a close look at another very useful and interesting Python data structure - the list. You make sure that you come on back for that one!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |