Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#20: Logic and Conditionals Expanded

                          << Previous Tutorial           Next Tutorial >>
On this page: Conditional statement with if ... else, equality test operator ==, commenting and uncommenting with Alt+3 and Alt+4.

Get Started

Video Summary

  • The initial script was edited 3 times, each time producing a different outcome.
  • Conditional statements can be created within Python using the if keyword. For example, after defining the variable number as equal to 7, the tutorial uses the conditional if number < 100: print 'it is less than 100' which, upon executing the program, causes Python to display the string within the conditional. However, since no other actions have been given, defining number as a number that does not meet the criteria of the conditional, such as 700, will cause Python to simply display a blank line upon the program's execution.
  • To give Python further instructions within the if conditional, else: can be added as an addendum. For example, the tutorial later uses the conditional if number*7 == 49: print 'it is 7' followed but the addendum else: print 'it wasnt 7; it was ' +str(number). If number is defined as 7, the conditions of the first argument will have been met, and Python will print 'it is 7' as told. However, if number is defined as any other numeral, the else: addendum will take over as the conditions of the first argument have not been met, and Python will print it was followed by whatever number is defined as.
  • Once again, remember to follow conditionals with a colon ":". This is easy to forget and if not included will cause Python to produce an error.

Learn More

  • Note that the double equal sign "==" is an equality test operator. You should not confuse it with "=" (single equal sign) which is an assignment operator.
  • In the video, Ed quickly un-comments and comments a whole code block. That's done through highlighting a block and pressing Alt+3 (to comment out) or Alt+4 (to uncomment). If you don't want to remember the shortcut, the commands are available under the "Format" menu.
  • A neat addition to the if ... else conditional structure is something called elif, which is a combination of "else if". if ... else is good for binary forking in control flow, but often the forking is tertiary or even larger. elif comes in handy in such cases. It comes right up in the next tutorial.

Explore