Python Programming If Statement Tutorial with Stone River eLearning

If you will ask a programmer about one flow control statement that he uses the most and is the most comfortable with, more often than not the answer would be ‘If Statement’.  The ‘if statement’ finds great application in codes ranging from printing a simple series to big applications used in our day to day life. The ‘if statement’ is also used alongside other flow control statements to ensure that the operation inside them are carried precisely the way they are intended to be.

The ‘if statement’ can be executed along with the else keyword with the latter used for operational statements that do not satisfy the condition inside the ‘if statement’. However; in this blog posts, we are going to concentrate only on the ‘if statement’ and leave the ‘else’ and the ‘elseif’ part to the upcoming blog posts on these basic Python tutorials for Beginners.

When should we execute the ‘if statements’ in Python?

While working on Python and writing the code for different applications, we will come across situations where a different operation must be performed for different cases. For instance, certain application or banking procedures do not allow users under the age of 18. Therefore, after the user enters his/her age in the bank’s system, message saying “you can use our services”; if the age is above 18, similarly, otherwise a message saying “You are not old enough to use this service”, must appear on the website.  Achieving success with such a problem without the “if” flow control statement can be slow, time consuming and frustrating, both for the user and the programmer.

Eg:

x=2

y=3

z=5

if x > y:

print(x,’is greater than’,y)

if x<y:

print(x,’is smaller than’,y)

if x==y:

print(x,’is equal to’,y)

Those of you who already have experience with programming might feel that why are we writing these if statements again and again when we can simply write the else keyword. Well off course we can use the while keyword but since this video and blog post is about the ‘if’ keyword you might have to wait a little before we jump towards the end of the road.

Note:

  • As described in the blog post by the tutor, you cannot use the “=” sign to compare the values of two variables. The comparison operator in computer programming is denoted by the “==” sign while the “=” is used for assignment operator.
  • Unlike in the case of languages such as C, C++ or Java, Python’s internal processing of code is so strong that you do not have to write multiple conditions with a ‘AND’ or ‘OR’ separator. You can simply write all the conditions in the same line and Python will process the answer for you.

Eg:

If z>x>y:

print(z,’is greater than’,y,’which is greater than’,x)

GET YOUR FREE PYTHON EBOOK!

(Visited 120 times, 1 visits today)