Basic Python Programming

by Gautham Pai

Let us start off our exploration of the first dimension for Python.

Data Types

When you start learning to program, one of the first concepts you'll encounter is "data types." Think of data types as different forms of information that you can use in a program. A data type tells the computer what kind of value is being stored or used. For instance, a number is a different kind of data than a word, and the computer needs to know which is which.

Just like in real life where we have various forms of things — numbers, words, lists, and more, programming languages need to know what kind of information they're dealing with to handle it properly. This helps the computer understand how to process and store the data efficiently.

Some Examples of Data Types

  1. Integers: Imagine you're counting the number of apples you have. You might say, "I have 5 apples." Here, "5" is an integer. It's a whole number that you can count. In programming, we use integers when we need to represent things like age (20 years old), the number of items (3 books), or scores (100 points).

  2. Floats: Now, let's say you're measuring the amount of water in a bottle. You might say, "The bottle has 1.5 liters of water." This is a float because it includes a decimal point. In real life, we use decimals for things like measuring height (5.9 feet), temperature (98.6 degrees), or money ($10.50).

  3. Strings: When you write a letter, send a text message, or speak to someone, you're using words and sentences. In programming, these words and sentences are represented as strings. For example, your name "John Doe" or a phrase "Hello, world!" are strings. Just like in a storybook where you see sentences, strings in a program are pieces of text that can include letters, numbers, and symbols.

  4. Booleans: Think about answering a simple yes-or-no question. For example, "Is the sky blue?" The answer can only be True or False. In programming, booleans are used to make decisions. If you ask your computer, "Is the temperature above 30 degrees?" it can respond with True (yes) or False (no). It's like flipping a light switch—it's either on (True) or off (False).

  5. Lists: Imagine you're making a shopping list. You write down things you need to buy: ["milk", "bread", "eggs"]. This is a list—a collection of items grouped together. In programming, lists are used when you want to keep multiple pieces of data in one place. It’s like a grocery list where you keep all the items you need to buy.

A Simple Illustration

Let's use a simple scenario that combines these data types:

  • You're planning a birthday party. You have:
    • Number of guests: 15 (an integer)
    • Cost per guest: $12.50 (a float)
    • Birthday message: "Happy Birthday, Alex!" (a string)
    • Is it a surprise party?: Yes (a boolean, which would be True)
    • Items to buy: ["cake", "balloons", "snacks"] (a list)

Each of these represents a different data type. Just like in your party planning, in programming, knowing what kind of data you’re dealing with helps you organize and manage it effectively.

Categories of Data Types

Data types can be divided into two main categories: primitives and composites.

Categories of Data Types

Primitives are the simplest types of data. They are used to represent the smallest parts of the data (single values) and include:

  • Numbers: Integers (e.g., 5) and floats (e.g., 3.14).
  • Strings: Textual data (e.g., "Hello, world!").
  • Booleans: True or false values (True or False).
  • Empty Value: Represents the absence of a value (e.g., None in Python).

Categories of Primitive Data Types

Composites are more complex and can hold multiple values. They come in two types:

  • Sequential composites: These maintain an order of elements.
  • Non-sequential composites: These do not preserve any specific order.

Categories of Composite Data Types

Together, primitives and composites form the core of how we organize and manage data in programming.

Why Do Data Types Matter?

Imagine you’re trying to do math with a word like "apple." It doesn't make sense, right? You can't add or subtract "apple" from a number like 5. But if you have numbers, like 5 and 3, you can easily add them together to get 8. Data types help the computer know what kinds of operations make sense. With the right data type, the computer knows when it can perform math, compare values, or even combine them to form sentences.

Exploring Primitive Data Types in Python

Now that we've discussed the different data types, let's see them in action using Python. Let us start with the primitive data types.

To do this, we'll use the Python interpreter, which is a tool that lets you type Python code and see immediate results. This is called a REPL (Read-Eval-Print Loop) environment, and it's perfect for quickly trying out code and learning how things work.

Step 1: Start the Python Interpreter

  1. Open a terminal (or Command Prompt on Windows) and type python or python3 and press Enter.
  2. You'll see a prompt that looks something like this: >>>. This means you're in the Python REPL environment, ready to start typing Python code.

Step 2: Try Out These Code Examples

Now, let's explore different data types in Python. We'll categorize them into numeric types, strings, booleans, and the special "none" type. Open your Python interpreter (REPL) and type each line, pressing Enter after each one.

Numeric Data Types

These include whole numbers (integers) and decimal numbers (floats).

Here is an example of a number:

10

There are many categories of numeric data types. Here are the main ones:

Integers:

type(10)

Python will display the data type of the value you entered using the type() function, which tells us what kind of data we're dealing with. This will show <class 'int'>, indicating that 10 is an integer, a whole number.

type(-10)

This will also show <class 'int'>. Both positive and negative whole numbers are considered integers.

Floats:

type(3.99)

This will show <class 'float'>, indicating that 3.99 is a float, a number with a decimal point.

type(-1.2)

This will show <class 'float'> as well. Floats can also be negative.

How are numbers stored in memory?

Remember that computers only understand 0's and 1's. How do we store a number like 5 or 20 in the RAM?

When numbers are stored in a computer's memory (RAM), they are converted into a sequence of 0s and 1s. Binary is a system that uses only two digits, 0 and 1, to represent information.

For example, the number 10 in decimal is 1010 in binary:

Ten in Binary

20 is 10100:

Twenty in Binary

When you store a number in memory, the computer converts it into a series of 0s and 1s and stores this binary representation in memory. Depending on the programming language, we may also pad this with some bits to convert it into a "byte" like this: 00001010.

Bits to Bytes

This process happens automatically, so you don't need to worry about converting numbers to binary manually—Python and other programming languages handle this for you.

Number in RAM

Strings

Strings are sequences of characters enclosed in quotes, used to represent text.

Here are some examples of strings:

'John'
"George"

Strings can be enclosed in either single (' ') or double (" ") quotes. If your string contains an apostrophe, you can either use double quotes around the string ("don't") or use the backslash (\) to escape the apostrophe ('don\'t').

"don't"
'don\'t'

To confirm that these are strings, let us use the type function:

type("John")

This will show <class 'str'>, indicating that "John" is a string. Strings can contain letters, numbers, and symbols, as long as they are enclosed in quotes.

Triple Quoted Strings: Triple quotes (''' ''' or """ """) allow you to create multi-line strings. This is useful when you need to write long text or include line breaks within a string.

'''Hello
World!
'''
"""
Don't worry
Be happy
"""

ASCII and UTF-8

In the previous section, we learnt how numbers are stored in the RAM. How are strings stored in memory? After all, strings are made up of characters like letters, symbols, and even emojis. Unlike numbers, characters don’t have a natural binary representation. This is where encoding like ASCII comes into play. ASCII helps convert each character in a string into a unique number, which can then be easily stored as binary in the computer's memory. For example, the character A is represented by the number 65 in ASCII, which in binary is 1000001. By converting each character into a number, ASCII and other encoding systems allow the computer to store and manipulate text efficiently.

  • ASCII encoding: In simple terms, "encoding" is how we convert characters into a format that computers can understand and work with. ASCII does this by assigning a unique number to each character. For example, the letter A is represented by the number 65 in ASCII. However, ASCII is limited because it only covers English characters and a few symbols. It doesn't have codes for characters from other languages or special symbols like (Rupee symbol) or emojis.

  • UTF-8: This is where UTF-8 comes in. UTF-8 is a more advanced and flexible encoding system that can represent a much wider range of characters, including those from different languages like Chinese, Arabic, Hindi, and even emojis (😊). It does this by using different numbers of bytes to represent characters, so it's not limited like ASCII.

Using UTF-8 characters in strings:

"₹500"
"I am happy 😄"
type("😊")

This shows Python's flexibility in handling different types of text data.

Booleans

Booleans represent truth values, either True or False.

Here are examples of booleans:

True
False

To confirm their type, let us use the type function:

type(True)

This will show <class 'bool'>, indicating that True is a boolean value.

type(False)

This will also show <class 'bool'>. Booleans are used to represent the two truth values in programming: true and false.

None Value

The None value represents the absence of a value.

Here is how we create it:

None

What is the type of None?

type(None)

This will show <class 'NoneType'>, indicating that None is a special type in Python used to represent the concept of "nothing" or "no value."

So here is a summary of the data types we have seen so far:

  • Numeric Data Types
    • Integers: Whole numbers like 10 and -10 (<class 'int'>).
    • Floats: Decimal numbers like 3.99 and -1.2 (<class 'float'>).
  • Strings: Textual data like "John" (<class 'str'>).
  • Booleans: True/False values like True and False (<class 'bool'>).
  • None Value: Represents the absence of a value (None) (<class 'NoneType'>).

Variables

Remember how we learnt that, a computer takes a stream of 0's and 1's, processes it and sends back another stream of 0's and 1's? We bring some data (in the form of 0's and 1's) into memory, we process it and then we send it out.

Let's break this down with a simple example:

  1. Input: This is when we bring data into the computer's memory (RAM) from input devices like a keyboard, mouse, or even sensors.
  2. Process: Once the data is in memory, we perform operations on it—calculating, modifying, or making decisions.
  3. Output: Finally, we send the processed data to an output device, like a screen or a printer, so it can be used or viewed.

What we do in a program written in a programming language is no different. We are defining how data is brought into memory, how we process it and what to do with the result.

Now, here's where variables come in. When we bring data into memory during the Input step, we need a way to refer to and work with this data while it's in RAM. This is what variables are for—they give us a label to access and manipulate the data stored in memory.

Variables act as labels for the data in memory. They make it easy to access, modify, and use the data throughout your program. In other words, variables are like the "names" for the data temporarily stored in RAM, allowing us to interact with it efficiently.

Working with Variables in Python

In programming, you can assign any value to a variable, making it easy to work with data throughout your code. Here are some examples to try in the Python interpreter:

All values can be assigned to variables:

Assigning Numbers:

price = 10
price

What does the statement price = 10 do?

We are telling the system to store a value 10 in the RAM (we may alternatively refer to RAM as memory). Note that the value 10 is stored in its binary form: 1010 in memory.

RAM addresses are very long and hard to remember, so we would like to refer to the location where this value is stored with a name, price because that's more memorable for us. We refer to such names as "variable names" or simply "variables". We say, price is a "variable".

Now how does our system know what this sequence of 0's and 1's means? Is it a int, or str or something else? This interpretation is given by the "data type". We say that the value that price is referring to is of type int.

So, to summarize, what are we saying in the statement above?

We are saying, "Create a value 10 of type int in memory and let price be the variable that we use to refer to the location where this number is stored".

Or, in simple terms we say, we have assigned the value 10 to the variable price. When you type price and press Enter, Python will show 10.

Note that = has a different meaning in programming languages. The = symbol in most programming languages means "assignment".

Assigning Strings:

name = "John"

What we saying in the statement above?

We are saying, "Create a value "John" of type string (simply, a sequence of alphabets or numerical characters) in memory and let name be the variable that we use to refer to the location where this string is stored".

Or in simple terms, name is assigned the string "John".

Assigning Boolean Values:

raining = True
is_sunny = False

Here, raining is assigned the boolean value True, and is_sunny is assigned False.

Checking Variable Types

What happens when you ask type(variable_name)?

place = "London"
type(place)

This will show <class 'str'>, indicating that the value that the variable place is referring to is a string.

price = 3.99
type(price)

This shows <class 'float'> because the value referred to by price is a floating-point number.

is_sunny = False
type(is_sunny)

This will show <class 'bool'>, indicating that the value is a boolean.

Be careful not to put the variable names in quotes!

type("price")

This shows <class 'str'> because "price" in quotes is a string, not the variable name.

Operators

Imagine we are trying to add 2 numbers. We can write some code like this:

a = 10
b = 20
c = a + b

Let us analyse this step by step. The first statement is:

a = 10

This statement is saying, "Create the value 10 in memory of type int and let a be the variable that we use to refer to the location where this number 10 is stored". Or, in simple terms, a is assigned the value 10.

Let us now see the next statement:

b = 20

The above statement is saying, b is assigned the value 20.

The next statement is:

c = a + b

+ indicates numeric addition. We are asking the system to add the 2 numbers referred to by the variables a and b and to store the result of operation in another location. This location will be referred to using the variable c. Note again that = is not indicating a mathematical "equality" operation. = symbol in most programming languages means "assignment". We are asking the system to assign the value computed by the operation a + b to the variable c.

In the above statement, + is called an operator, and a and b are its operands. Since a and b are referring to numbers, the system understands that + is supposed to "add" the 2 numbers.

Note the sequence of operations when we say c = a + b:

  • To begin with a and b are in the RAM
  • The addition operation takes place in the CPU, so for this, the values of a and b have to be loaded from the CPU to the RAM
  • The addition operation then takes place in the CPU and results in the creation of the sum of a and b in the CPU
  • This result is then loaded back into the RAM from the CPU

How Variables And Operators Fit Into The Input -> Process -> Output Flow

  • Input: Imagine you're writing a program to track the temperature. You might receive an input value, like 25 degrees Celsius, from a sensor. To work with this temperature data, you store it in a variable: temperature = 25.
  • Process: Next, you might want to convert this temperature from Celsius to Fahrenheit. To do this, you perform some calculations using the variable. For example:
    temperature_in_fahrenheit = (temperature * 9/5) + 32
    
    Here, temperature is used in the processing step to perform the calculation.
  • Output: Finally, you can display the converted temperature on the screen:
    print("Temperature in Fahrenheit:", temperature_in_fahrenheit)
    

Don't worry if you don't understand this program entirely. We will understand it soon!

By using variables like temperature and temperature_in_fahrenheit, you can easily refer to the data stored in memory, define how to process it and what to do with the result.

Expressions and Statements

When we combine variables, values and operators, we get expressions.

Here are some examples of expressions:

a + b
a + 10
a + b + 10

Expressions by themselves don't change the value of anything. When we say:

a + b

neither the value of a changes, nor the value of b changes.

However if we say:

c = a + b

the value referred to by c has changed after the execution of this. These are referred to as statements.

Here are some examples of statements:

c = a + b
x = x + y
z = z - 10
c = 2 * 3.14 * r
pi = 22 / 7

Statements don't need to be only mathematical in nature. We can also ask the system to do things like print a string in the console (or your screen). Here we are asking the system to print the string "Hello, World!" to the console:

print('Hello, World!')

print in the above statement is called a function. We will learn more about functions and function calls in a later lesson.

Trivia about "Hello, World!"

"Hello, World!" is one of the first things we learn to "say" in a programming language. Here is how we can do it in various programming languages!

A sequence of statements

Here is a way to tell the system to add 2 numbers, a and b and then print their result to the screen:

a = 10
b = 20
c = a + b
print(c)

A program written in a programming language contains a sequence of statements like above.

Do the order of the statements matter?

Yes! In most languages, the statements get executed from top to bottom.

Let us take up some examples to understand this.

a = 10
b = 20
a = a + b
b = a + b

After this sequence of statements are executed, what is the value of a and b?

Let us understand it step by step.

Use a pen and paper to follow the code and our description so that you understand it better:

  • We first create a value 10 and call it a
  • We then create the value 20 and call it b
  • We then add the value of a and b and store it in the location a - so a gets the value 30.
  • We then add the current value of a and b and store it in the location b - so b gets the value 50.

So the final value of a is 30 and the final value of b is 50.

Now what if we wrote the statements in this order:

a = 10
b = 20
b = a + b
a = a + b

What is the value of a and b after these statements are executed?

Let us understand it step by step:

  • We first create a value 10 and call it a
  • We then create the value 20 and call it b
  • We then add the value of a and b and store it in the location b - so b gets the value 30.
  • We then add the current value of a and b and store it in the location a - so a gets the value 40.

So the final value of a is 40 and the final value of b is 30.

Clearly, the order of statements matter.

A program is made up of a sequence of statements. As the statements execute, they make changes to some locations. The changes made by a certain statement affects the next statement.

Conditionals

Sometimes, we may want to skip a few statements based on a condition:

1. i = 10
2. if i < 5:
3.   print('i is less than 5')
4. print('Done!')

The statement in line 2 is what we refer to as a conditional. A conditional is a way of telling the system to check something and only execute some statements if the condition holds true.

What is the condition we want the system to check?

Answer: 'if i < 5' means "Is the value of i less than 5".

What do we want the system to do if the condition is true (i.e. if the value of i is less than 5)?

Answer: We want it to execute the next statement - "print('i is less than 5')".

How does the system know which statement(s) to run if the condition is true?

Note, how in line 3, we have moved the code slightly to the right. We call this as "indentation" in a language. Doesn't this give us an impression of a hierarchy? It looks like this line is "inside" the previous line. We say the statement - print('i is less than 5') is inside the if condition.

Indentation is the empty space to the left of the code. We can say that line 3 has an indent of 2 spaces. Indentation can be done using either tabs or spaces.

Let us now summarize the above code step by step:

  • Line 1: We create a variable i with value 10.
  • Line 2: We encounter the if condition, which tells the system to check if the condition i < 5 is true. If so, we want it to execute statement in Line 3, if not, skip Line 3 and jump to Line 4. The system now checks the condition. Is the value of i less than 5? Since this is false, Line 3 is skipped.
  • We move to the next statement on Line 4 and the system prints "Done!" in the console.

Output in the console for the above code:

Done!

Here is another example:

1. i = 0
2. if i < 5:
3.   print('i is less than 5')
4.   print('The world is beautiful!')
5. print('Done!')

Let us understand this step by step:

  • Line 1: We create a variable i with value 0.
  • Line 2: We now encounter the if condition, which tells the system to check if the condition i < 5 is true. The system now checks the condition: "Is the value of i less than 5?" Since this is true, we execute Lines 3 and 4 next. Note how both Line 3 and 4 are indented with the same amount of spaces to the left. This is how we tell the system to run multiple statements when the condition is true.
  • Line 3 asks the system to print the statement "i is less than 5" to the console and Line 4 asks the system to print the statement "The world is beautiful!".
  • We move to the next statement on Line 5 and the system prints "Done!" in the console.

Output in the console for the above code:

i is less than 5
The world is beautiful!
Done!

Here are some more examples of condition checks:

  • if i != 10 - In a lot of languages != is read (and means) "not equal to". So we are saying "if the current value of i is not equal to 10 then run the indented statements".
  • if a % 2 == 0 - In a lot of languages % stands for the modulus operator. This condition says "when you divide a by 2 if the remainder is 0, then run the indented statements". In other words, "if a is an even number run the indented statements".
  • if a % 2 != 0 - This is a way of saying, "if a is an odd number, run the indented statements".

What if we want the system to do one thing if a condition is true and a different thing if the condition is false. Programming languages have something called an if-else condition for this.

Here is an example:

1. i = 5
2. if i <= 5:
3.   print('i is less than or equal to 5')
4. else:
5.   print('i is greater than 5')
6. print('Done!')

An else is a way to describe what needs to be done if the condition check fails. In the above code, we are asking the system to verify if the value of i is less than or equal to 5 and if so run Line 3, and if it is not, we ask the system to run line 5.

Let us understand the code step by step:

  • Line 1: We create a variable i with value 5.
  • Line 2: We now encounter the if condition, which tells the system to check if the condition i <= 5 is true. <= means "less than or equal to". The system now checks the condition: "Is the value of i less than or equal to 5?" Since this is true (i is 5, which matches the condition less than or equal to 5), we execute Line 3 next.
  • Line 3 asks the system to print the statement "i is less than or equal to 5" to the console.
  • Since the condition is true, the statements inside the if condition were executed. This automatically means that the statements inside the else will not execute. if and else are mutually exclusive. Either the statements in the if condition execute or the statements in the else execute but never both.
  • We move to the next statement on Line 6 and the system prints "Done!" in the console.

Output in the console for the above code:

i is less than or equal to 5
Done!

Here is another example of if/else:

1. i = 25
2. if i <= 5:
3.   print('i is less than or equal to 5')
4. else:
5.   print('i is greater than 5')
6. print('Done!')

Let us understand the code step by step:

  • Line 1: We create a variable i with value 25.
  • Line 2: We now encounter the if condition, which tells the system to check if the condition i <= 5 is true. The system now checks the condition: "Is the value of i less than or equal to 5?" Since this is not true (i is 25, which is greater than 5), we skip Line 3.
  • Since the condition was false, the statements inside the else condition are executed and the system starts executing Line 5.
  • Line 5 asks the system to print the statement "i is greater than 5" to the console.
  • We move to the next statement on Line 6 and the system prints "Done!" in the console.

Output in the console for the above code:

i is greater than 5
Done!

Conditionals containing conditionals (if containing if)

Sometimes we may want to write a condition inside another condition. These are called nested conditionals.

Here is an example:

1. i = 5
2. if i <= 5:
3.   if i == 5:
4.     print('i is equal to 5')
5.   else:
6.     print('i is less than 5')
7. else:
8.   print('i is greater than 5')
9. print('Done!')

This is the first time we are encountering a double indent. We have seen how we indent the code when we write conditionals. The statements to run when the if condition is true or the statements to run when it is false (the else) are indented. We also know that if there are more than one statements inside the condition, we use the same amount of indent for all of them.

What happens if we want to put an if-else inside another?

The indentation rules say that the statements that need to run when a condition matches should be indented by one additional indent when compared to the current indent.

In the above code, if the condition on Line 2 is true, we want the system to run all the statements from Line 3 to 6. Note how all these statements have at least a 2 space indent. However, the Line 3 has another condition. This condition on Line 3 is "inside" the condition on Line 2. So what should we do if this condition is also true? We want the system to run the statement on Line 4. The statement on Line 4 is inside a condition (on Line 3) which is inside another condition (on Line 2). So it has 2 indents of 2 spaces each (so total of 4 spaces).

Similarly, Line 6 is inside an else (on Line 5), which is inside an if (on Line 2). So it has 2 indents.

Finally, see how the statement on Line 8 has only one indent. The reason is it is inside an else which is not inside any other condition.

Let us understand the code step by step:

  • Line 1: We create a variable i with value 5.
  • Line 2: We now encounter the if condition, which tells the system to check if the condition i <= 5 is true. Since this is true, we start executing line 3 onwards. Note that this automatically ensures Line 8 will never get executed (since the if of Line 2 and else on Line 7 are mutually exclusive).
  • Line 3 asks the system to check another condition - "Is i equal to 5"? Since this is true, we now execute Line 4. This automatically ensures that Line 6 will never get executed (since the if of Line 3 and else on Line 5 are mutually exclusive).
  • The system prints, "i is equal to 5".
  • We move to the next statement on Line 9 and the system prints "Done!" in the console.

Output in the console for the above code:

i is equal to 5
Done!
 1. i = 25
 2. if i <= 5:
 3.   if i == 5:
 4.     print('i is equal to 5')
 5.   else:
 6.     print('i is less than 5')
 7. else:
 8.   if i > 30:
 9.     print('i is greater than 30')
10.   else:
11.     print('i is less than 30 but greater than 5')
12. print('Done!')

Let us understand the code step by step:

  • Line 1: We create a variable i with value 25.
  • Line 2: We now encounter the if condition, which tells the system to check if the condition i <= 5 is true. Since this is not true, we skip all lines inside the if and jump to the else statements starting from Line 8.
  • At Line 8, the system encounters another condition check. "Is the value of i greater than 30"?
  • Since this is not true, we jump to the else statement at Line 11.
  • The system prints, "i is less than 30 but greater than 5" to the console.
  • We move to the next statement on Line 12 and the system prints "Done!" in the console.

Output in the console for the above code:

i is less than 30 but greater than 5
Done!

Combining conditionals (if-else-if-else)

When we have multiple conditions to match, we can either write nested conditionals like above or we can flatten it this way:

1. i = 25
2. if i == 5:
4.   print('i is equal to 5')
5. elif i < 5:
6.   print('i is less than 5')
7. else:
8.   print('i is greater than 5')
9. print('Done!')

elif is the keyword that Python uses to define a second condition. Other languages may have other keywords.

Let us understand the code step by step:

  • Line 1: We create a variable i with value 5.
  • Line 2: We now encounter the if condition, which tells the system to check if the condition i == 5 is true. Since this is not true, we skip Line 4 and jump to Line 5.
  • Line 5: We encounter the second condition. "Is i less than 5"? Since this is not true, we skip Line 6 and jump to Line 7.
  • Line 6: Since none of the above conditions matched, we now start executing the statements inside the else.
  • The system prints, "i is greater than 5" to the console.
  • We move to the next statement on Line 9 and the system prints "Done!" in the console.

Output in the console for the above code:

i is greater than 5
Done!

Looping

Sometimes, we may want to execute a certain set of statements again and again until some condition is true:

1. i = 0
2. while i < 5:
3.   print(i)
4.   i = i + 1
5. print('Done!')

The statement in line 2 is the beginning of a loop. A loop is a way we are telling the system to do something repeatedly. What do we want the system to repeat? Answer: The next 2 lines (3 and 4).

How does the system know what to repeat?

Note the indentation of line 3 and 4. Note also that the indentation for line 3 and 4 is exactly the same (2 spaces each).

Till when should we run these statements repeatedly?

Answer: Loops have a condition that tells the system until when it is supposed to repeat the statements. In our current example, the condition is i < 5. We run the statements in the loop (line 3 and 4) until the condition i < 5 mentioned in line 2 no longer holds true.

Let us understand this step by step:

  • We create a variable i with value 0.
  • We now encounter the while loop, which tells the system that we want lines 3 and 4 to run repeatedly until the condition i < 5 is no longer true. The system now checks the condition. Is the value of i less than 5? If so, run the statements in the loop, if not go to the next statement after the loop (line 5).
  • Since the current value of i is 0 and 0 is less than 5, the system starts running the statements in the loop starting from line 3.
  • Line 3 asks the system to print the current value of i to the console. So we will see the value 0 appear on the screen.
  • We then move to the next statement - which increments the value of i by 1. The value of i now becomes 1.
  • Remember that we are "inside" a loop and our work is not done, so we now have to "jump back" to line 2. The system now checks the condition again. Is the value of i less than 5? The current value of i is 1, which is still less than 5. So the statements in the loop run again. The current value of i, 1, is printed to the console. The value of i is incremented by 1 and i becomes 2.
  • The process repeats and we see the values 2, 3 and 4 getting printed to the console.
  • At this point the value of i becomes 5. Is the current value of i less than 5? Note that 5 is not less than 5. So the condition check fails. The loop stops and the next statement after the loop (line 5) runs.
  • The system prints "Done!" in the console.

Output in the console for the above code:

0
1
2
3
4
Done!

Loops containing loops

1. i = 0
2. while i < 3:
3.   j = 0
4.   while j < 3:
5.     print(i + j)
6.     j = j + 1
7.   i = i + 1
8. print('Done!')

Let us understand this step by step:

  • We create a variable i with value 0.
  • We now encounter the while loop, with the condition i < 3. Is the current value of i less than 3? Since this is true, we execute lines 3 to 7.
  • Line 3: We create another variable j with value 0
  • We encounter a second while loop with the condition j < 3. Since the current value of j is less than 3, we execute lines 5 and 6. Note how Lines 5 and 6 have the double indent.
    • Line 5: The system prints the value of i + j, which at this moment is 0 + 0. So we see the system printing 0 to the console.
    • Line 6: The value of j is incremented by 1 and its current value becomes 1.
    • We now jump back to the beginning of the inner loop, i.e. to Line 4.
    • Is the current value of j less than 3. The current value of j is 1, which is less than 3, so the statements in the loop execute again.
    • The system prints the value of i + j, which happens to be 1.
    • The value of j is incremented.
    • The process repeats until the value of j becomes 3 and the condition fails.
  • Note that while the inner loop has completed, we are still in the outer loop of Line 2. We now continue with Line 7.
  • The value of i is incremented by 1 and its value becomes 1.
  • We jump back to the condition check on Line 2. Is the current value of i less than 3. Since this is true, we start executing the statements of loop again starting from Line 3.
  • The value of j is set to 0 again and the entire inner while executes a second time.
  • This process repeats until i has the value 3 and the outer loop's condition is no longer true.
  • We finally jump to the statement on Line 8 and the system prints "Done!" to the console.

Output in the console for the above code:

0
1
2
1
2
3
2
3
4
Done!

Explanation of the output:

  • The first set of 0, 1 and 2 is when the value of i is 0 and j goes from 0 to 2.
  • The next set of 1, 2 and 3 is when the value of i is 1 and j goes from 0 to 2.
  • The final set of 2, 3 and 4 is when the value of i is 2 and j goes from 0 to 2.

The outer loop executes 3 times and the inner loop executes 3 times for every outer loop execution. So the print which is inside 2 loops is executed 9 times in all.

Loops with conditionals

1. i = 0
2. while i < 10:
3.   if i % 2 == 0:
4.     print(i)
5.   i = i + 1
6. print('Done!')

Let us understand this step by step:

  • We create a variable i with value 0.
  • We now encounter the while loop, with the condition i < 10. Is the current value of i less than 10? Since this is true, we execute lines 3 to 5.
  • Line 3: We encounter a condition - "When i is divided by 2 is the remainder 0"? Since i has value 0 and when we divide i by 2 we get the remainder 0, this evaluates to true. This condition evaluates to true for all even numbers.
  • The system runs Line 3 since the condition is true and prints "0" to the console.
  • We are now done with the if condition but we are still inside the while. So we run the next statement in the while which happens to be Line 5.
  • The value of i is incremented by 1 and it becomes 1.
  • We now check the condition in Line 2 again. Is i less than 10? Since the current value of i is 1, which is less than 10, we enter the loop.
  • The condition on Line 3 fails since i has value 1 which doesn't give us a remainder 0, so we don't run the Line 4 this time. We instead skip to Line 5.
  • The value of i is incremented to 2.
  • The loop continues until the value of i becomes 10 and that is when the condition on Line 2 fails and we jump to Line 6.
  • The system prints "Done!" to the console.

Output in the console for the above code:

2
4
6
8
Done!

We could have written the above in a different way (without the conditional):

1. i = 0
2. while i < 10:
3.   print(i)
4.   i = i + 2
5. print('Done!')

The output for the above code is exactly the same as the previous one.

Braces vs. Indents

When you're learning to program, you'll notice that different programming languages have their own ways of organizing code. Two of the most common methods are braces and indents. Let's break down what these terms mean and how they affect the way you write and read code.

Braces { }

Braces are curly brackets { } used by many programming languages, like C, Java, and JavaScript, to define blocks of code. Think of braces as a way to group related lines of code together. For example, when you write a function or an "if" statement, you wrap the code inside a pair of braces to show that this code belongs together.

Here’s a simple example in JavaScript using braces:

if (isRaining) {
    console.log("Take an umbrella.");
}

In this example, the braces { } tell the computer that the line console.log("Take an umbrella."); is part of the "if" statement. Braces make it easy to see where a block of code begins and ends, which is especially helpful in larger programs.

Indents

Indents, on the other hand, are used in languages like Python to group code. Instead of using braces, Python relies on indentation (usually 2 or 4 spaces) to determine which lines of code belong together. This means that you have to be careful with the spacing of your code in Python.

Here’s the same example in Python using indents:

if is_raining:
  print("Take an umbrella.")

Here, the line print("Take an umbrella.") is indented (code is slightly written to the right with empty spaces at the beginning of the line) to show that it’s part of the "if" statement. Indentation makes the code look neat and organized, and in Python, it’s not just a matter of style—it’s required. If you don't indent correctly, your code won't work!

Which Is Better?

Neither braces nor indents are "better" than the other; they just represent different styles of organizing code. Braces can make it clearer where code blocks start and end, especially in languages that allow multiple lines in a single statement. Indentation, however, can make code look cleaner and easier to read because it visually represents the structure of the code.

As a beginner, it's important to get comfortable with both styles. Depending on the language you're learning, you'll need to use either braces or indents to organize your code. The key takeaway is that organizing code into blocks—whether with braces or indents—helps both the computer and other programmers understand the logic of your program.

Test Your Knowledge

No quiz available

Tags