Main Menu: PYTHON PROGRAMMING
Making Statements and Running in Loops
Now that you've wrapped your head around data-types and learned basic operations for manipulating data, it's time to develop simple programs an execute them with the help if Python's IDLE Editor. In this third chapter, you will be introduced to the concept of Objects in Python, and understand the difference between Mutable and Immutable Objects. You will learn to develop programs using Python's IDLE Editor, and also save and execute them from inside IDLE Editor. Learn all about conditional statements, iteration statements, and jump statements, and build programs with greater control and functionality. By the end of this chapter, you will have developed a simple, but efficient, Calculator Application that you will love to play around with!
3.1: An Introduction: Mutable and Immutable Objects
You may have heard this many times over, or read it while Googling about Python: Python is an Object-Oriented Programming Language, and you might have wondered what it means. I'll be honest, object-oriented programming, or OOP, sounded scary and difficult to me the first time I heard the term. I won't lie, it sometimes is. So I think it's best to introduce you to objects in Python, now that you have a good understanding of variables and data-types.

An object in Python is any variable assigned a particular data-type or data-structure, which can be defined with the help of attributes and functions. Each object belong to a class which acts as an outline for the object. To understand this, let's take a real-word analogy.

Consider a smart-phone called Solar. It is an object that has attributes like a touch-screen, buttons, speaker, microphone, charging port, and SIM card slot, and can perform functions such as play videos, take images, make calls, record audio, play games, and what not. Solar is an object belonging to the class smart-phone.

Similarly, all variables created in Python are objects that belong to either a pre-defined class, or a user-defined class. For example, let's create two variables integerVariable and stringVariable that hold an integer value and character string, respectively. Here is how you can check the class of a variable:


>>> integerVariable = 54
>>> stringVariable = 'Gladys'
>>> print(Class of Integer Variable:', type(integerVariable))
Class of Integer Variable: <class 'int'>
>>> print(Class of String Variable:', type(stringVariable))
Class of String Variable: <class 'str'>            
            

Here, we see that the variable integerVariable in an object that belongs to the class int, while stringVariable belongs to class str.

We will dive deep into classes in later chapters, starting from Chapter 5, but for now, I'd like you to remember this much: Everything you create in Python is an object which belongs to a class.

In Python, objects can be of two-types: Mutable and Immutable.

Immutable Objects are those objects which cannot be edited without changing the memory location that they point to. For example, we saw in section 2.1, how changing the value of an integer variable changes the memory location which that the variable points to. Thus, integers, along with floating point variables, Fractions, Decimals, complex variables, Booleans, and strings, are immutable objects.

In that manner, Mutable Objects are objects which can be edited without changing the memory location they point to. Data-structures like Lists, Dictionaries, and Sets are mutable objects.

Tuples are the only data-structures that are immutable in nature.

Don't let this talk about data-structures bother you too much for now. We'll explore them in much detail in Chapter 4 and build some cool Python programs using them at the end of Chapter 5!
3.2: Selection Statements in Python: 'if-else' and 'if-elif-else'
Often, while developing programs professionally, you might want your code to carry out one among two or more actions, based on the value or state of certain objects. At such times, it becomes necessary to develop code that can check if the required conditions are being met. The if-else statement in Python allows you to check for pre-determined conditions before executing a block of code.

An if-else statement in Python follows the syntax shown in the box below:


if (condition 1 [and / or conditon 2] [and / or conditon 3] [...]):
    // Execute a block of code
    // All code inside this block must be indented by a single 'tab'
else:
    // Execute a different block of code
    // All code inside this block must be indented by a single 'tab'                
            

The if-else statement starts with an if clause that checks if a condition, or set of conditions, is met. If the condition check returns a Boolean value True, then the block of code immediately following the if statement is executed. After the block of code completes executing, the program resumes processing from after the block of code following the else statement.

If the conditions in the if statement return a Boolean value False, then the program executes the block of code immediately following the else statement. After the block of code completes executing, the program resumes processing from after the block of code following the else statement.

Suppose you want to develop a program that displays a message only when the user enters the correct password. Let's create this program using the IDLE Editor.

First, create a new folder Python Programming in your D drive. After that, go to your Windows search bar and open IDLE (Python 3.7), and go to File > New File. A new file will open in the IDLE Editor. Let's start writing our code in the editor:


# Greet the user of the program using the print() function
print('Welcome to The IF-ELSE Cave of Eternal Truth.')
# Ask the user to enter the password and save the entered password as a string variable
password = input('Enter password to view the eternal truth: ')
if (password == 'babooshka'):
    print("Behold the Eternal Truth: Pizza is better than burger!")
else:
    print("You are forever cursed to feed on nothing but lettuce... Hahahahahahahahahahahahahahahaha!")
            

After typing out the code in the IDLE Editor, save the code in D:/Python Programming. Once the code is saved, press F5 or go to Run > Run Module. You should see the folloing output on your screen:


Welcome to The IF-ELSE Cave of Eternal Truth.
Enter password to view the eternal truth: _                
            

Type in the password babooshka and hit "enter". The rest of the code will execute.


Welcome to The IF-ELSE Cave of Eternal Truth.
Enter password to view the eternal truth: babooshka
Behold the Eternal Truth: Pizza is better than burger!
>>>                     
            

Since you entered the right password, the condition for equality (password == 'babooshka') returned a Boolean value True, and so the block of code following the if statement is executed. What happens if you run the program again and this time enter the wrong password?


Welcome to The IF-ELSE Cave of Eternal Truth.
Enter password to view the eternal truth: sheeshkebab
You are forever cursed to feed on nothing but lettuce... Hahahahahahahahahahahahahahahaha!
>>>                  
            

You will see that this time, since the condition for equality in the if statement is not fulfilled, the program execution enters the block of code following the else statement, and prints a different output than before.

This is simple stuff, however, in most real-world programs, you will see a different form of if-else statement, called the if-elif-else statement.

Often, you might come across multiple possible conditions, each of which should cause a different block of code to get executed. Say, you want to build a simple calculator application that takes in two numbers and asks you to choose one out of four operations that you would like to perform on these numbers. Each of the four choices must trigger a different operation and return the result of the operation. In such a case, we would use the if-elif-else loop.

Once again, if your IDLE Python 3.7 shell is still open, go to File > New File and type in the following program:


# Welcome the User
print("""Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!""")

# Print a blank line
print()

# Prompt the User to enter the two numbers of their choice and store it as a
# floating point variable
firstNumber = float(input("Please enter the first number: "))
secondNumber = float(input("Please enter the second number: "))

# Now, list down the four operations that the User can choose from
print("""Choose the code for the operation you'd like to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division""")

# Accepts the User's choice and store it as an integer variable
choice = int(input())

# Use an 'if-elif-else' statement block to check the choice entered and carry
# out an operation accordingly
if (choice == 1):
    # This block of code executes if choice = 1
    result = firstNumber + secondNumber
    print(firstNumber, "+", secondNumber, "=", result)
elif (choice == 2):
    # This block of code executes if choice = 2
    result = firstNumber - secondNumber
    print(firstNumber, "-", secondNumber, "=", result)
elif (choice == 3):
    # This block of code executes if choice = 3
    result = firstNumber * secondNumber
    print(firstNumber, "*", secondNumber, "=", result)
elif (choice == 4):
    # This block of code executes if choice = 4
    result = firstNumber / secondNumber
    print(firstNumber, "/", secondNumber, "=", result)
else:
    # This block executes if none of the above conditions are met
    print("Wrong choice selected. No operation carried out.")
    
# Display a 'goodbye' message after a blank line
print("Thank you and see you soon!")
            

Save the code as simpleCalculator.py and then press F5 on your keyboard or go to Run > Run Module. You should get the following output:


Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!

Please enter the first number: 12
Please enter the second number: 7
Choose the code for the operation you'd like to perform:
1. Addition
2. Subtraction
3. Multiplication
4. Division
3
12.0 * 7.0 = 84.0

Thank you and see you soon!
>>>             
            

In the above application simpleCalculator.py, after the User enters their choice, the program control moves to the first if of the if-elif-else statement. Like in a regular if-else statement, the program checks for the condition in the first if statement. If the condition is met, then the block of code following the if statement is executed. After the block of code completes execution, the program exits the entire if-elif-else statement and continues executing from after the statement. If the condition is not met, then the program control moves to the elif statement.

If the program reaches the elif statement, it checks the condition given in that statement, and executes the block of code following it. After the block of code completes execution, the program exits the entire if-elif-else statement and continues executing from after the statement. Like with the if statement before it, if the condition in the elif statement is not met, then the program control moves to the next elif statement.

In the same way, the program checks for the conditions in the rest of the elif statements, and goes on to the next elif if one fails. This goes on until the program fails to find matching matching conditions in any of the if-elif statements, and then reaches the else statement. The program then executes the block of code following the else statement irrespective of the conditions.

How about you run the program once again? This time try different choice and check the output for yourself? If you closed the file simpleCalculator.py where the program was written, just go back to the folder where you saved the file, right-click on the file, and select Edit with IDLE 3.7. The file will open in the IDLE Editor.

Before we move on to the next section, I'd like to introduce you to the simplest form of the if statement:


print('The simple IF statement, in all its glory!')
activator = input('Type "Show Me" to reveal the truth of life: ')
# Notice the indented block of code.
if activator == "Show Me":
    print("You're beautiful.")
    print("Never forget that.")               
            

Save this code as simpleIf.py and save it in your D:/Python Programming folder. Run it like you've run your previous programs. Here's your output:


The simple IF statement, in all its glory!
Type "Show Me" to reveal the truth of life: Show Me
You're beautiful.
Never forget that.
>>>                 
            
3.3: Iteration Statements in Python: 'for' and 'while' loops
Up until now, we've created programs and written code that is purely sequential and unidirectional in nature - meaning these programs execute code written from start to finish without returning to a previous line or point in the code. The same line of code has never been repeated except when explicitly written. Once completed, the program has to be re-executed.

However, let's say you want to write a piece of code that repeats the same set of operations more than once, over a pre-decided and / or finite number of iterations, for example, 10 iterations. Writing the same few lines of code 10 times over would take too much time (yes, you do have the option of copy and paste), and leave you with a code file that might unnecessarily span hundreds of lines, with the same thing written all over it. That's not only amateurish but also technically ugly.

That's where the for loop comes to the rescue. Here's how it looks:


// A bunch of code that you've written for your program before the 'for' loop...
// Some more code you've written before the 'for' loop...
for (element in iterable object):
    // Execute a block of code within the 'for' loop
    // All code inside this block must be indented by a single 'tab'
// More code after the 'for' loop ends...
// The for loop ends when the iterable objects runs out of elements, or the loop is explicitly terminated
            

The for loop repeats execution of a block of code for the number of elements available inside an iterable object, such as ranges, strings, lists, and tuples.

Here's an example, which asks you to input any three-digit integer number and a two-digit number, and then prints all multiples of the two-digit number less than the three-digit number entered.


# Let Multipie introduce herself and print a blank line after her introduction!
print("""Hey there! My name is Multipie. I\'ll help you count multiples of any
number you wish, up till any number you'd like me to!""" + '\n')

# Enter the single-digit number whose multiples you'd like to find
twoDigitNumber = int(input("Please enter the two-digit number whose multiples you'd like to find: "))
# Enter any integer three-digit number and save it in a variable
threeDigitNumber = int(input("Please enter the limit up till which you'd like to find multiples: "))

# Use a 'for' loop for calculating and printing the multiples
for count in range(1, threeDigitNumber):
    result = twoDigitNumber * count
    print(str(twoDigitNumber) + ' * ' + str(count) + ' = ' + str(result))

# Print a goodbye message
print('\n' + "I hope that helps you! Thank you and see you soon!")
            

Type the above code in an IDLE Editor file and save it as multipie.py in the folder we created, D:/Python Programming.

Run the program just like you ran the previous one. Let's check the output:


Hey there! My name is Multipie. I'll help you count multiples of any
number you wish, up till any number you'd like me to!

Please enter the two-digit number whose multiples you'd like to find: 22
Please enter the limit up till which you'd like to find multiples: 300
22 * 1 = 22
22 * 2 = 44
22 * 3 = 66
22 * 4 = 88
22 * 5 = 110
22 * 6 = 132
22 * 7 = 154
22 * 8 = 176
22 * 9 = 198
22 * 10 = 220
22 * 11 = 242
22 * 12 = 264
22 * 13 = 286
22 * 14 = 308
22 * 15 = 330
22 * 16 = 352
....
....
22 * 288 = 6336
22 * 289 = 6358
22 * 290 = 6380
22 * 291 = 6402
22 * 292 = 6424
22 * 293 = 6446
22 * 294 = 6468
22 * 295 = 6490
22 * 296 = 6512
22 * 297 = 6534
22 * 298 = 6556
22 * 299 = 6578

I hope that helps you! Thank you and see you soon!
>>>
            

In the above program, we see a very straightforward application of the for loop. The for statement uses the range() function to create an iteratable object that holds the 300 - 1 elements from 1 to 299. In the first iteration of the for loop, the variable count in the for statement takes the value '1'.

The program then enters the block of code following the for statement. The program calculates the product of the two-digit number and the iteration number stored in count and stores it in a variable result. The result is then printed and the first iteration of the for loop ends. The program then returns to the for statement to check the condition for the next iteration.

Since the iterable object still contains elements (2 to 299), the loop goes ahead with the next (second) iteration. Once again, the product of the two-digit number and the iteration number stored in count is calculated and printed like in the previous iteration. After the block is executed, the program returns to the for statement, once again to check the condition for continuing. This process goes on as long as the iterable object has elements available. Once the object runs out of the elements, the for loop comes to an end.

So, the for loop allows us to repeat the same block of code over a finite number of iterations. What if you did not know the number of iterations over which you'd like to run a loop, or instead, what if you wanted to run a loop until a certain condition is met? In such cases, you'd use a while loop. Here's how the loop is structured:


// A bunch of code that you've written for your program before the 'while' loop...
// Some more code you've written before the 'while' loop...
while (condition 1 [and / or condition 2] [and / or condition 3] [...]):
    // Execute a block of code within the 'while' loop
    // All code inside this block must be indented by a single 'tab'
// More code after the 'while' loop ends...
// The 'while' loop ends when the condition check fails, or the loop is explicitly terminated                 
            

How about we learn about while loops by modifying our previous program simpleCalculator.py? Reopen the program by right-clicking on the file in your Python Programming folder, and selecting Edit with IDLE 3.7. Here's the new code:


# Welcome the User
print("""Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!""")

# Print a blank line
print()

# Create a variable for the 'while' loop condition check
continueExecution = 'Y'

# The 'while' loop begins here...
while (continueExecution == 'Y'):
    # Prompt the User to enter the two numbers of their choice and store it as a
    # floating point variable
    firstNumber = float(input("Please enter the first number: "))
    secondNumber = float(input("Please enter the second number: "))

    # Now, list down the four operations that the User can choose from
    print("""Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division""")

    # Accepts the User's choice and store it as an integer variable
    choice = int(input())

    # Use an 'if-elif-else' statement block to check the choice entered and carry
    # out an operation accordingly
    if (choice == 1):
        # This block executes if choice = 1
        result = firstNumber + secondNumber
        print(firstNumber, "+", secondNumber, "=", result)
    elif (choice == 2):
        # This block executes if choice = 2
        result = firstNumber - secondNumber
        print(firstNumber, "-", secondNumber, "=", result)
    elif (choice == 3):
        # This block executes if choice = 3
        result = firstNumber * secondNumber
        print(firstNumber, "*", secondNumber, "=", result)
    elif (choice == 4):
        # This block executes if choice = 4
        result = firstNumber / secondNumber
        print(firstNumber, "/", secondNumber, "=", result)
    else:
        # This block executes if none of the above conditions are met
        print("Wrong choice selected. No operation carried out.")

    # As the User if they want to continue using the calculator
    print("Would you like to carry out another calculation?")
    print("Type 'Y' for 'yes' and 'N' for 'N'.")
    continueExecution = input()

    # Print a blank line before going back to the beginning of the loop
    print()

# Print a goodbye message for the User
print("Thank you and see you soon!")
            

In this modification of the simpleCalculator.py program, we have written the if-elif-else statement inside a while loop. Before the while loop begins, we initialise a string variable continueExecution with the value 'Y'. The while loop continues its execution as long as the value of continueExecution remains 'Y'. Here is the output for the above code:


Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!

Please enter the first number: 1
Please enter the second number: 2
Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division
2
1.0 - 2.0 = -1.0
Would you like to carry out another calculation?
Type 'Y' for 'yes' and 'N' for 'N'.
Y

Please enter the first number: 2
Please enter the second number: 5
Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division
4
2.0 / 5.0 = 0.4
Would you like to carry out another calculation?
Type 'Y' for 'yes' and 'N' for 'N'.
N

Thank you and see you soon!
>>>                
            

When the program reaches the while statement, it checks for the condition given. If the condition check returns a Boolean True value, then the code inside the while loop will be executed. If the program enters the while loop, it accepts two numbers from the User, and the choice of operation to be carried out, and then prints the result of the operation. After that, the the program asks the user for their input whether they'd like to make another calculation. The User may enter 'Y' for 'Yes', or 'N' for 'No'. This input is stored as the new value for variable continueExecution.

The program then returns to the while statement, and once again checks the value of continueExecution. Once again, iff the condition check returns a Boolean True value, then the code inside the while loop will be executed. If the program enters the while loop, it accepts two numbers from the User, and the choice of operation to be carried out, and then prints the result of the operation. After that, the the program asks the user for their input whether they'd like to make another calculation. The User may enter 'Y' for 'Yes', or 'N' for 'No'. This input is stored as the new value for variable continueExecution.

This process goes on as long as the value of continueExecution is 'Y'. When the value changes and the condition check in the while statement returns a Boolean False value, the the while loop is terminated, and the program continues execution from after the while loop.
3.4: Jump Statements in Python: 'break' and 'continue'
So you've learned to build programs that repeat execution of blocks of code and can change the course of execution depending on the state of variables or values of variables. But what if you wanted to develop a piece of code that can break out of a loop or skip an iteration of a loop midway, depending on a condition that you set? Python provides us with two brilliant statements that helps us do this: the break statement, and the continue statement.

The break statement allows you to terminate a loop or a conditional statement before the condition for termination is met, or before the loop completes the total number of available iterations. The statement can be placed anywhere inside the loop based on the developer's requirement. For example, take the program simpleCalculator.py. Say, instead of depending on the conditional statement in the while statement, you'd like to exit the loop as soon as the User enters the character 'N'. Here's the code for how you'd do it:


# Welcome the User
print("""Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!""")

# Print a blank line
print()

# The 'while' loop begins here. We have created an infinite loop, because
# 'Boolean True' will always be True...
while (True):
    # Prompt the User to enter the two numbers of their choice and store it as a
    # floating point variable
    firstNumber = float(input("Please enter the first number: "))
    secondNumber = float(input("Please enter the second number: "))

    # Now, list down the four operations that the User can choose from
    print("""Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division""")

    # Accepts the User's choice and store it as an integer variable
    choice = int(input())

    # Use an 'if-elif-else' statement block to check the choice entered and carry
    # out an operation accordingly
    if (choice == 1):
        # This block executes if choice = 1
        result = firstNumber + secondNumber
        print(firstNumber, "+", secondNumber, "=", result)
    elif (choice == 2):
        # This block executes if choice = 2
        result = firstNumber - secondNumber
        print(firstNumber, "-", secondNumber, "=", result)
    elif (choice == 3):
        # This block executes if choice = 3
        result = firstNumber * secondNumber
        print(firstNumber, "*", secondNumber, "=", result)
    elif (choice == 4):
        # This block executes if choice = 4
        result = firstNumber / secondNumber
        print(firstNumber, "/", secondNumber, "=", result)
    else:
        # This block executes if none of the above conditions are met
        print("Wrong choice selected. No operation carried out.")

    # As the User if they want to continue using the calculator
    print("Would you like to carry out another calculation?")
    print("Type 'Y' for 'yes' and 'N' for 'N'.")
    continueExecution = input()
    if continueExecution == 'N':
        print("\n" + "You have chosen to leave the program...")
        break

    # Print a blank line before going back to the beginning of the loop
    print()

# Print a goodbye message for the User
print("Thank you and see you soon!")
            

In this version of the simpleCalculator program, we create an infinite while loop that does not use an object for condition checking in the while statement. Instead, we use the Boolean True value itself, which is not assigned to any variable and thus cannot be changed. This means the while statement will always read a Boolean True value and the loop will run forever, unless terminated expicitly from within. Have a look at the output:


Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!

Please enter the first number: 4
Please enter the second number: 7
Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division
4
4.0 / 7.0 = 0.5714285714285714
Would you like to carry out another calculation?
Type 'Y' for 'yes' and 'N' for 'N'.
Y

Please enter the first number: 22
Please enter the second number: 7
Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division
4
22.0 / 7.0 = 3.142857142857143
Would you like to carry out another calculation?
Type 'Y' for 'yes' and 'N' for 'N'.
N

You have chosen to leave the program...
Thank you and see you soon!
>>> 
            

In this program, we did not initialize any variable for use in the while statement. When the program reaches the while statement, it reads the Boolean True value and continues to execute the block of code within it. Once inside the block of code, the program accepts two numbers from the User and prints the results of the operation of their choice. It then asks the User if they would like to carry out another calculation. The User either enters 'Y' for 'Yes', or 'N' for 'No', which is stored in a variable continueExecution that can only be used inside the loop. The program then encounters a simple if statement: if the User enters 'N', the program breaks out of the while loop. If the User enters 'Y', the program skips the if statement and returns to the start of the while statement at the start of the loop.

Here, once again the program enters the while loop for another iteration as the value of Boolean True is always True. The program repeats the process until the User enters 'N' for 'No' and the program breaks out of the loop. When the program encounters the break statement, it does not return to the while statement at the start of the loop for condition check. The program instead jumps out of the loop and continues execution from outside the while loop.

Apart from breaking out of loops, there might be instances where you'd like to skip a particular iteration and jump to the next one, based on certain conditions. That's when you use the continue statement.

Take for example, you want to develop a version of the simpleCalculator.py program in which you can provide the User with an option to change the numbers entered before they go forward with choosing an operation for calculation:


# Welcome the User
print("""Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!""")

# Print a blank line
print()

# The 'while' loop begins here. We have created an infinite loop, because
# 'Boolean True' will always be True...
while (True):
    # Prompt the User to enter the two numbers of their choice and store it as a
    # floating point variable
    firstNumber = float(input("Please enter the first number: "))
    secondNumber = float(input("Please enter the second number: "))

    # Ask the user if they'd like to change the numbers entered...
    print("Would you like to change the numbers entered?")
    print("Type 'Y' for 'yes' and 'N' for 'no'.")
    changeNumber = input()
    if (changeNumber == 'Y'):
        continue

    # Now, list down the four operations that the User can choose from
    print("""Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division""")

    # Accepts the User's choice and store it as an integer variable
    choice = int(input())

    # Use an 'if-elif-else' statement block to check the choice entered and carry
    # out an operation accordingly
    if (choice == 1):
        # This block executes if choice = 1
        result = firstNumber + secondNumber
        print(firstNumber, "+", secondNumber, "=", result)
    elif (choice == 2):
        # This block executes if choice = 2
        result = firstNumber - secondNumber
        print(firstNumber, "-", secondNumber, "=", result)
    elif (choice == 3):
        # This block executes if choice = 3
        result = firstNumber * secondNumber
        print(firstNumber, "*", secondNumber, "=", result)
    elif (choice == 4):
        # This block executes if choice = 4
        result = firstNumber / secondNumber
        print(firstNumber, "/", secondNumber, "=", result)
    else:
        # This block executes if none of the above conditions are met
        print("Wrong choice selected. No operation carried out.")

    # As the User if they want to continue using the calculator
    print("Would you like to carry out another calculation?")
    print("Type 'Y' for 'yes' and 'N' for 'no'.")
    continueExecution = input()
    if continueExecution == 'N':
        print("\n" + "You have chosen to leave the program...")
        break

    # Print a blank line before going back to the beginning of the loop
    print()

# Print a goodbye message for the User
print("Thank you and see you soon!")
            

You can edit the Python program file simpleCalculator.py, or save the code in a new file simpleCalculatorFinal.py. In the above example, we ask the User if they'd like to change the numbers entered. The User either enters 'Y' for 'Yes' or 'N' for 'No'. Here is the output we get for running the code:


Hello! Welcome to Simple Calculator! You can use this application to
add, subtract, multiply, or divide any two numbers you choose!

Please enter the first number: 1
Please enter the second number: 2
Would you like to change the numbers entered?
Type 'Y' for 'yes' and 'N' for 'no'.
Y
Please enter the first number: 22
Please enter the second number: 9
Would you like to change the numbers entered?
Type 'Y' for 'yes' and 'N' for 'no'.
N
Choose the code for the operations you'd like to perform:
    1. Addition
    2. Subtraction
    3. Multiplication
    4. Division
4
22.0 / 9.0 = 2.4444444444444446
Would you like to carry out another calculation?
Type 'Y' for 'yes' and 'N' for 'no'.
N

You have chosen to leave the program...
Thank you and see you soon!
>>>                 
            

Like in the previous example, the program uses an infinite while loop that can only be explicitly terminated from within. After the program enters the while loop, it accepts two numbers from the User, and then asks the User if they would like to change the numbers entered. The User's input is stored as a string variable changeNumber. If the User enters 'Y', the program executes the continue statement inside the simple if statement. This causes the current iteration of the while loop to end, and the program returns to the beginning of the for loop without executing the rest of the code block.

If the user enters 'N', the condition check in the simple if statement fails, and the continue statement is not executed. The program then executes the rest of the code in the block as seen in the previous example.

That's all that there is for this chapter. In the next chapter, I'm going to get you up and running with these awesome things called data-structures, in which you can store more than one value of information, giving you greater control over how you create, store, access and manipulate data while developing programs.

Seeya!