Comparison operators do what they sound like they do; compare things. It's like your girlfriend. She compares you to her ex-boyfriends all the time. And worse still, she probably compares you to guys she sees walking down the street. Let's face it; you're a loser and she is looking for a real man. But don't worry. When you finish learning the Python I'm teaching you, you can build a hot chick like the one in Weird Science that digs my...I mean your...nerdiness. By the way...nerdiness is not in my spell checker. But nerd is oddly enough... #!/usr/local/bin/python beers = 99 if beers == 100: print "Did I die? This doesn't look like Heaven...but all that beer tells me it must be." elif beers >100: print "When I get done with all this beer, yer gonna look pretty."
else: print "There aren't enough beers here to make you look good. Fortunately for you I am desperate." The above program assigns the value 100 to the variable beers. I know, it sounds delicious, but try to pay attention. Next, the program enters into an If statement that states if the value of beers is equal to (==) 100, print some text. If not, then if the value of beers is greater than 100, print some other text. Finally, if beers is equal to anything else, print a different text. Let's say that we set the value of beers to 99; here is what would print out: There aren't enough beers here to make you look good. Fortunately for you I am desperate. Here is another program showcasing some of the other comparison operators: #!/usr/local/bin/python beers = 98 if beers >= 100: print "Did I die? This doesn't look like Heaven...but all that beer tells me it must be." elif beers <=98: print "When I get done with all this beer, yer gonna look pretty."
else: print "There aren't enough beers here to make you look good. Fortunately for you I am desparate." This program works pretty similar to our previous one. Only here we use the equal to or greater than (>=) and the less than or equal to (<=) operators. You will not that we assigned the value of 98 to our variable beers. I did this to showcase what can happen if you don't pay close attention to your operators. Since our operators are assigned as >=100 and <=98, it leaves a space for a loop hole, the number 99. Fortunately we put in an else clause to handle any values not covered by our greater than/less than/equal to operators. If you run the program, it will print out: There aren't enough beers here to make you look good. Fortunately for you I am desperate. And lastly, if we are really finicky, we can use the not equal to (!=) operator: #!/usr/local/bin/python beers = 100 if beers != 100: print "Did I die? This doesn't look like Heaven...but all that beer tells me it must be." else: print "There aren't enough beers here to make you look good. Fortunately for you I am desparate."
In the above example, it would only execute the Else clause if the value of beers was equal to 100.
blog comments powered by Disqus |
|
|
|
|
|
|
|