CommonLounge Archive

Python: If Statements and Comments

August 04, 2018

In the last tutorial, you learnt about Python: Variables, Lists and Dictionaries. In this tutorial, you’ll learn about if-statements, using which you can do certain things only if certain conditions are met. For this, you’ll first see how to compare things in Python as well as the Boolean data type (True and False). Finally, you’ll also see comments, which are useful for making your code more readable and easy to follow.

Compare things

A big part of programming involves comparing things. What’s the easiest thing to compare? Numbers, of course. Let’s see how that works:

>>> 5 > 2
True
>>> 3 < 1
False
>>> 5 > 2 * 2
True
>>> 1 == 1
True
>>> 5 != 2
True

We gave Python some numbers to compare. As you can see, not only can Python compare numbers, but it can also compare method results. Nice, huh?

Do you wonder why we put two equal signs == next to each other to compare if numbers are equal? We use a single = for assigning values to variables. You always, always need to put two of them – ==– if you want to check if things are equal to each other. We can also state that things are unequal to each other. For that, we use the symbol !=, as shown in the example above.

Give Python two more tasks:

>>> 6 >= 12 / 2
True
>>> 3 <= 2
False

We’ve seen > and <, but what do >= and <= mean? Read them like this:

  • x > y means: x is greater than y
  • x < y means: x is less than y
  • x <= y means: x is less than or equal to y
  • x >= y means: x is greater than or equal to y

Awesome! Wanna do one more? Try this:

>>> 6 > 2 and 2 < 3
True
>>> 3 > 2 and 2 < 1
False
>>> 3 > 2 or 2 < 1
True

You can give Python as many numbers to compare as you want, and it will give you an answer! Pretty smart, right?

  • and – if you use the and operator, both comparisons have to be True in order for the whole command to be True
  • or – if you use the or operator, only one of the comparisons has to be True in order for the whole command to be True

Have you heard of the expression “comparing apples to oranges”? Let’s try the Python equivalent:

>>> 1 > 'django'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: '>' not supported between instances of 'int' and 'str'

Here you see that just like in the expression, Python is not able to compare a number (int) and a string (str). Instead, it shows a TypeError and tells us the two types can’t be compared together.

Boolean

Incidentally, you just learned about a new type of object in Python. It’s called Boolean.

There are only two Boolean objects:

  • True
  • False

But for Python to understand this, you need to always write it as True (first letter uppercase, with the rest of the letters lowercased). true, TRUE, and tRUE won’t work – only True is correct. (The same applies to False as well, of course.)

Booleans can be variables, too! See here:

>>> a = True
>>> a
True

You can also do it this way:

>>> a = 2 > 5
>>> a
False

Practice and have fun with Booleans by trying to run the following commands:

  • True and True
  • False and True
  • True or 1 == 1
  • 1 != 2

Congrats! Booleans are one of the coolest features in programming, and you just learned how to use them!

Save it!

So far we’ve been writing all our python code in the interpreter, which limits us to entering one line of code at a time. Normal programs are saved in files and executed by our programming language interpreter or compiler. So far we’ve been running our programs one line at a time in the Python interpreter. We’re going to need more than one line of code for the next few tasks, so we’ll quickly need to:

  • Exit the Python interpreter
  • Open up our code editor of choice
  • Save some code into a new python file
  • Run it!

To exit from the Python interpreter that we’ve been using, simply type the exit() function

>>> exit()
$

This will put you back into the command prompt.

Earlier, we picked out a code editor from the Code Editor section. We’ll need to open the editor now and write some code into a new file:

print 'Hello, Commonlounge!'

Obviously, you’re a pretty seasoned Python developer now, so feel free to write some code that you’ve learned today.

Now we need to save the file and give it a descriptive name. Let’s call the file python_intro.py and save it to your desktop. We can name the file anything we want, but the important part here is to make sure the file ends in .py. The .py extension tells our operating system that this is a Python executable file and Python can run it.

Note You should notice one of the coolest thing about code editors: colors! In the Python console, everything was the same color; now you should see that the print command is a different color from the string. This is called “syntax highlighting”, and it’s a really useful feature when coding. The color of things will give you hints, such as unclosed strings or a typo in a keyword name (like the def in a function, which we’ll see below). This is one of the reasons we use a code editor. :)

With the file saved, it’s time to run it! Using the skills you’ve learned in the command line section, use the terminal to change directories to the desktop.

Change directory: OS X

On a Mac, the command will look something like this:

$ cd ~/Desktop

Change directory: Linux

On Linux, it will be like this (the word “Desktop” might be translated to your local language):

$ cd ~/Desktop

Change directory: Windows Command Prompt

On Windows Command Prompt, it will be like this:

> cd %HomePath%\Desktop

Change directory: Windows Powershell

And on Windows Powershell, it will be like this:

> cd $Home\Desktop

Now use Python to execute the code in the file like this:

$ python python_intro.py
Hello, Commonlounge!

Alright! You just ran your first Python program that was saved to a file. Feel awesome?

You can now move on to an essential tool in programming:

If … elif … else

Lots of things in code should be executed only when given conditions are met. That’s why Python has something called if statements.

Replace the code in your python_intro.py file with this:

if 3 > 2:

If we were to save and run this, we’d see an error like this:

$ python python_intro.py
File "python_intro.py", line 2
         ^
SyntaxError: unexpected EOF while parsing

Python expects us to give further instructions to it which are executed if the condition 3 > 2 turns out to be true (or True for that matter). Let’s try to make Python print “It works!”. Change your code in your python_intro.py file to this:

if 3 > 2:
    print 'It works!'

Notice how we’ve indented the next line of code by 4 spaces? We need to do this so Python knows what code to run if the result is true. You can do one space, but nearly all Python programmers do 4 to make things look neat. A single tab will also count as 4 spaces.

Save it and give it another run:

$ python python_intro.py
It works!

What if a condition isn’t True?

In previous examples, code was executed only when the conditions were True. But Python also has elif and else statements:

if 5 > 2:
    print '5 is indeed greater than 2'
else:
    print '5 is not greater than 2'

When this is run it will print out:

$ python python_intro.py
5 is indeed greater than 2

If 2 were a greater number than 5, then the second command would be executed. Let’s see how elifworks:

name = 'Dave'
if name == 'Commonlounge':
    print 'Hey Commonlounge!'
elif name == 'Dave':
    print 'Hey Dave!'
else:
    print 'Hey anonymous!'

and executed:

$ python python_intro.py
Hey Dave!

See what happened there? elif lets you add extra conditions that run if the previous conditions fail.

You can add as many elif statements as you like after your initial if statement. For example:

volume = 57
if volume < 20:
    print "It's kinda quiet."
elif 20 <= volume < 40:
    print "It's nice for background music"
elif 40 <= volume < 60:
    print "Perfect, I can hear all the details"
elif 60 <= volume < 80:
    print "Nice for parties"
elif 80 <= volume < 100:
    print "A bit loud!"
else:
    print "My ears are hurting! :("

Python runs through each test in sequence and prints:

$ python python_intro.py
Perfect, I can hear all the details

Comments

Comments are lines beginning with #. You can write whatever you want after the # and Python will ignore it. Comments can make your code easier for other people to understand.

Let’s see how that looks:

# Change the volume if it's too loud or too quiet
if volume < 20 or volume > 80:
    volume = 50
    print "That's better!"

You don’t need to write a comment for every line of code, but they are useful for explaining why your code is doing something, or providing a summary when it’s doing something complex.

Summary

In the last few exercises you learned about:

  • comparing things – in Python you can compare things by using >, >=, ==, <=, < and the and, or operators
  • Boolean – a type of object that can only have one of two values: True or False
  • Saving files – storing code in files so you can execute larger programs.
  • if … elif … else – statements that allow you to execute code only when certain conditions are met.
  • comments - lines that Python won’t run which let you document your code

Time for a quiz and then the last part of this section!

Based on content from https://tutorial.djangogirls.org/en/python_introduction/


© 2016-2022. All rights reserved.