Python – Week 4 – Conditional Programming and Loops – Part 1

Note on Vi Editor

As I mentioned earlier, I am learning Python on Linux, so I though about trying the vi editor as well. Learning vim can be endless but if want to learn its basic usage such as typing and saving the code, then we only have to learn a couple of things.

From console, type vi filename. An editor will open in the console itself. However, you won’t be able to type at that moment. To enter text, you need to initiate the insert mode by pressing the key i. Now, you can enter text normally like you do it in every other editor.

Once you have finished writing code, press the escape key and type :wq to save the code and exit at the same time.

if Statement

The if statement checks if a specific condition is True or False. Consider the following example:

number = 1
if number == 1:
        print('The number is one.')
        print('The number is not one.')

After assigning the value 1 to number, the if statement checks whether the given condition holds True. Otherwise, the else statement will be executed. If you need to give multiple conditions, then else – elif is used, as explained in the following code example:

number = 1
if number == 0:
        print("The number is zero.")
elif number == 1:
        print("The number is one.")
        print("The number is neither zero nor one.")

for Loop

The for loop is used for looping over a sequence. Let’s assign different values from a list to number.

for number in [0, 1, 2, 3, 4, 5]:

Unlike other programming languages, we haven’t assigned any value to number variable outside the for loop. Let’s look at another example for better understanding.

names = ["Tushar Kumar", "Kavya Nair"]
for serial in range(len(names)):
        print(serial, names[serial])

In the above example, we have created a list and assigned two values – Tushar Kumar and Kavya Nair to it. Executing the len function will return 2 as we have declared 2 names in the list. However, range is [0, 2) which actually means a sequence (0, 1).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s