Showing posts with label python3. Show all posts
Showing posts with label python3. Show all posts

Problem Solving With Python: Program 6

The problem statement:

We are tasked with prompting a user to enter a specific type of value, validating the value and print a message appropriate to the value provided. The following are a set of requirements for this task:

  1. Prompt the user to only enter a non-negative integer. For example, the following are examples of non-negative integers. 0, 1, 2, 3, 4, ...
  2. If the user successfully enters a non-negative integer:
    1. Display a success message
    2. Terminate the program.
  3. If the user fails to enter a non-negative integer then repeat the program from step one.

 The following is the expected approximate output of program 6 when an incorrect value type is provided:

Please enter a non-negative integer >> hello
Error: 'hello' is not a non-negative integer.
Please enter a non-negative integer >>


The following is the expected approximate output of program 6 when a correct value type is provided:

Please enter a non-negative integer >> 22
Success: '22' is a non-negative integer.
Goodbye!

The Solution:

def request_a_positive_integer_from_user():
    prompt_message = "Please enter a non-negative integer >> "
    while True:
        user_value = input(prompt_message)
        if user_value.isdigit():
            success_message = f"Success: '{user_value}' is a non-negative integer."
            print(success_message)
            print("Goodbye!")
            break
        else:
            error_message = f"Error: '{user_value}' is not a non-negative integer."
            print(error_message)


def request_a_positive_integer_from_user_alternate():
    prompt_message = "Please enter a non-negative integer >> "
    require_input_value = True
    while require_input_value:
        user_value = input(prompt_message)
        if user_value.isdigit():
            success_message = f"Success: '{user_value}' is a non-negative integer."
            print(success_message)
            print("Goodbye!")
            require_input_value = False
        else:
            error_message = f"Error: '{user_value}' is not a non-negative integer."
            print(error_message)


if __name__ == '__main__':
    request_a_positive_integer_from_user()
    # request_a_positive_integer_from_user_alternate()
In the previous example we saw how to use a while loop to compute powers of two less than 1,000. This solution will also use a while loop in order to satisfy the requirement (requirement 3) that the user be repeatedly prompted to enter a non-negative integer in the event that a different type of value is entered. We accomplish this by using a while loop with a static or fixed conditional statement of True. Recall that a while loop will not terminate until its conditional statement evaluates to False. Since we did not use a variable in the while loop's conditional statement we have no way to programmatically signal to the while loop to terminate. Instead we use a break statement to perform the while loop termination.

What is a break statement?
A break statement is used to signal to the Python interpreter to terminate the current loop; it can also be used with a for loop. We could have instead used an additional variable to signal to the loop to terminate (instead of signaling to the Python interpreter to terminate). The use of the break statement allowed us to use one less variable thus making the solution a little bit more concise. See the alternate solution, request_a_positive_integer_from_user_alternate(), that utilizes a variable instead of a break statement.

When to use a break statement vs a variable?
The choice is really yours... For a simple solution as this one the break statement suffices. But if the logic in the while loop were more involved and required significantly more lines then we would have opted for a more descriptive approach so that the code is easier to read and follow the logic flow.

How do we prompt the user for a value?

The Python language has a built in function called input(...). When this function is invoked (or called) the execution of our solution is paused at this line (or point) of invocation. The function displays to the user our custom message and waits for the user to either press the Enter key or input a value followed by the press of the Enter key. Control is given back to our solution once the user presses the Enter and our solution logic continues to execute. At this point we are required to validate the user input and take appropriate action.

How do we validate the user input?
Given a string, Python has a builtin function that can tell us if the entire string is a sequence of characters that can be converted to a non-negative integer; True is returned if this possible else False is returned by the isdigit() function.

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 5

The problem statement:

We are tasked with displaying all the powers of 2 less than 1,000 along with a message describing the output.

The following is the expected approximate output of program 5:

  • 1
  • 2
  • 4
  • 8
  • 16
  • 32
  • 64
  • 128
  • 156
  • 512
  • These are all the powers of 2 less than 1000


The Solution:

def powers_of_two_less_than_one_thousand():
    power = 1
    while power < 1000:
        print(power)
        power *= 2
    print("These are all the powers of 2 less than 1000")


def equivalent_solution():

    power = 1
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    power = power * 2
    print(power)
    print("These are all the powers of 2 less than 1000")


if __name__ == '__main__':
    powers_of_two_less_than_one_thousand()

In previous examples we saw how to use a for loop to write concise solutions that allowed us to reuse code that is written in the body of the loop. Our solution to the stated problem will also use a loop to reuse code, but it will not be a for loop because we are not interested in iterating over a list of predefined items. Instead, we use a while loop.

What is a while loop? 

A while loop allows us to continue processing code that is within the body of the loop until a condition is met or satisfied. The looping condition for our while loop is that the variable named power is less than the value of 1000. If this condition ever fails then the while loop is terminated.

How does a while loop work? 

The body of the loop is executed until the condition becomes false. The condition that is defined is evaluated for a boolean value of True or False at the beginning of each loop. The loop terminates once the evaluation of our conditional "sees" a value of False, else the looping continues. This implies that it is possible to program a while loop that never terminates and therefore runs forever. This condition is known as an infinite loop and is usually the result of a bug in our code or reasoning. We can create create the condition of an infinite loop by forgetting to multiply by 2 on each iteration of the loop.

Unraveling the while loop. 

If you are having difficulties understanding the code in this or any while loop then it is sometimes helpful to unravel the loop. We can gain greater visibility in the looping code by examining an equivalent solution that does not use any looping mechanism. That is, solve the solution in its entirety, or partially if the result is long, by not reusing code inside a loop. For example, the solution given with a while loop is equivalent to the code found in the equivalent_solution() function, (remember that power *= 2 is shorthand for power = power * 2).

Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 4

The problem statement:

Program 3 introduced an operator that increments the value of a variable by a desired amount, namely, the += operator. Recall that the use of this operator allowed us to replace this expression variable = variable + 1 with the following concise expression variable += 1. Because this operator first computes the sum of the existing variable value with the desired constant value (e.g. 1) and then assigns the sum to the same variable this operator is called a compound assignment operator. This is not the only compound assignment operator available in python that can be used to write concise code.

Given the following Python program, the task is to refactor the code to make it more concise with the use of compound assignment operators where applicable.

Given program:

def given_code():
    variable_1 = 10
    variable_2 = 10
    variable_3 = 10
    variable_4 = 10
    variable_5 = 10
    variable_6 = 10
    variable_7 = 10

    variable_1 = variable_1 + 3
    variable_2 = variable_2 - 3
    variable_3 = variable_3 * 3
    variable_4 = variable_4 ** 3
    variable_5 = variable_5 / 3
    variable_6 = variable_6 // 3
    variable_7 = variable_7 % 3

    print("Before Compound Operation Use:")
    for variable_i in [variable_1, variable_2, variable_3, variable_4, variable_5, variable_6, variable_7]:
        print("    Variable:", variable_i)


The following is the expected approximate output of program 4:

Before Compound Operations:
  • Variable: 13
  • Variable: 7
  • Variable: 30
  • Variable: 3.3333333333333335
  • Variable: 3
  • Variable: 1
After Compound Operations:
  • Variable: 13
  • Variable: 7
  • Variable: 30
  • Variable: 1000
  • Variable: 3.3333333333333335
  • Variable: 3


The Solution:

def refactored_code():
    variable_1 = 10
    variable_2 = 10
    variable_3 = 10
    variable_4 = 10
    variable_5 = 10
    variable_6 = 10
    variable_7 = 10

    variable_1 += 3
    variable_2 -= 3
    variable_3 *= 3
    variable_4 **= 3
    variable_5 /= 3
    variable_6 //= 3
    variable_7 %= 3

    print("After Compound Operation Use:")
    for variable_i in [variable_1, variable_2, variable_3, variable_4, variable_5, variable_6]:
        print("    Variable:", variable_i)


def program_4():
    given_code()
    refactored_code()


if __name__ == '__main__':
    program_4()


Arithmetic Operators:

  • + is used for addition.
  • - is used for subtraction.
  • * is used for multiplication.
  • ** is used for exponentiation. E.g.,  2**5 = 32 is read as 2 raised to the power of 5 or 2*2*2*2*2 = 32.
  • / is used for division. E.g., 1/2 = 0.5
  • // is used for floor division. E.g., if 8/3 = 2.666... then 8//3 = 2. I.e., the decimal point (.) and everything to the right of it is dropped.
  • % is used for computing the remainder of a division operation. E.g., 8%3 = 2.


Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 3

 The problem statement: 

Program 2 showed us how to iterate over a list of numbers and print them to the screen. For our next program we will also need to iterate over a list of number but this time we need to count the two different types of numbers in the list as we iterate over them.

The task is to write a Python program that displays the counts of odd and even numbers in a list of positive integers (i.e. whole numbers). In order for us to begin to think about a solution we first need to know the exact definition of odd and even numbers.

Definitions: 

  • An odd number when divided by two will always have a remainder in addition to a quotient. Some examples of odd numbers in decimal form follow. 1/2 = 0.5, 3/2 = 1.5, 5/2 = 2.5, etc. (Note that 5/2 = 2.5, is read as five divided by 2 is equal to 2.5).
  • An even number is the opposite of an odd number. That is, an even number divided by 2 has a quotient but no remainder, does not leave a remainder. Some examples of an even number follow. 0/2 = 0, 2/2 = 1, 4/2 = 2, 6/2 = 3, etc. Note how no decimal is needed since the result of the division does not have a remainder.

The following is the expected approximate output of program 3. Given the list, [0, 4, 9, 5, 11, 15, 7]:

  • Even count = 2
  • Odd count = 5

The Solution: 

def count_odd_and_even_numbers_first_attempt():
    even_count = 0
    odd_count = 0

    for number in [0, 4, 9, 5, 11, 15, 7]:

        result = number / 2
        if int(result) == result:
            '''Even'''
            even_count = even_count + 1
        else:
            '''Odd'''
            odd_count = odd_count + 1

    print("Even count =", even_count)
    print("Odd count =", odd_count)


def count_odd_and_even_numbers_second_attempt():
    even_count = 0
    odd_count = 0

    for number in [0, 4, 9, 5, 11, 15, 7]:

        result = number % 2
        if result == 0:
            '''Even'''
            even_count += 1
        else:
            '''Odd'''
            odd_count += 1

    print("Even count =", even_count)
    print("Odd count =", odd_count)


def count_odd_and_even_numbers_third_attempt():
    even_count, odd_count = 0, 0

    for number in [0, 4, 9, 5, 11, 15, 7]:
        if number % 2 == 0:
            '''Even'''
            even_count += 1
        else:
            '''Odd'''
            odd_count += 1

    print("Even count =", even_count)
    print("Odd count =", odd_count)


def program_3():
    count_odd_and_even_numbers_first_attempt()
    print("--END--")
    count_odd_and_even_numbers_second_attempt()
    print("--END--")
    count_odd_and_even_numbers_third_attempt()
    print("--END--")


if __name__ == '__main__':
    program_3()

In previous problems our solutions required the use of a for loop, the mathematical operator of multiplication, and the use of the print function. This time the calculations are a little more complex. The additional complexity comes from the fact that we need to consider two possible conditions when looking at a number when determining if a number falls into the odd or even category of numbers. Once we know what category the number is in then we increment one of two variable that holds the running count of the category we detected.

We present three solutions. Each solution is intended to showcase different approaches and programing techniques. Let's start with the function count_odd_and_even_numbers_second_attempt().

The Counting Variables:  

The first thing that we do is define two variables, even_count and odd_count. They are initialized to zero, indicating we have yet to see an odd or even number since we have not iterated over the list of numbers. As we iterate over the numbers using a for loop, these two variables will hold a current count of odd and even numbers.

Is it Odd or Even? 

By the definition of an odd or even number given above we know that an odd number divided by 2 results in a value that has a remainder, otherwise it is an even number. So the first order of business is to divided the number provided by the for loop by 2 and capture the result as follow. result = number / 2. This expression is our first logic inside the for loop. Suppose the number given inside the for loop is 3. We know that 3 divided by 2 is 1.5. From this result we can see with our eyes and determine with our brain that 3 is an odd number because when we examine the value of 1.5 we observe that there is a value other than zero past the decimal point. But how do we program our thought process into a machine? The short answer is that we use built-in operations or functions that come shipped with the Python programming language. One such built-in function that we can use is the int(...) function. This function will convert inputs to the function into integers only if the input is convertible. If your input is a name like Steve then the int(...) will not be able to do the conversion. In fact, in this particular instance the entire program will crash. But it will work if our input is a number with a decimal value. For example, if our input is 1.0 then it will convert it to the whole value of 1. In a similar fashion, if our input is 2.7 then this function will convert it to the whole value of 2; dropping or truncating the decimal point and any value past the decimal point. Given the int(...) function we can compare its conversion output to its input. For example, suppose we need to determine if the number 3 is even or odd. We first perform the following computation. result = 3 / 2. The result variable will be assigned the value of 1.5 in this expression. We then give the init function the result variable which holds a value of 1.5 as follow. conversion = int(result). If we inspect the conversion variable with the print function we will see that it has a value of 1. Lastly, we compare the conversion value (1) to the result value (1.5). From the comparison we determine that the value three is odd because the conversion value of 1 does not equal the result value of 1.5.

How do we Compare Numbers? 

We use the built-in equal operator to compare two values. The symbols or characters used to represent the equal operator is ==. The equal operator works by first comparing two values and then replaces the entire expression with a boolean value. A boolean value has one of two possible states: True or False. Here are two examples of an equal operator (==) that is evaluated (or converted) to the boolean value of True and False.

  • 2.0 == 2.0 is evaluated to True
  • 3.6 == 3.2 is evaluated to False


How do we Make Decisions using Booleans? 

Inside the for loop we need to decide if the current number delivered by the loop is an odd or even number. Our program will need to branch or split into two separate logic flows such that if a given number is even we only increment the even_count variable by a value of 1. If, however, the given number is odd then we only increment the odd_count variable by a value of 1.

This branching (or splitting) of our program into two separate logic flows that depends on the given number being even or odd condition can be accomplished with the use of the concept of an if: ... else: ... block of code. This block of code works as follow. If the if statement of this block of code is followed by a boolean value of True then only the code indented immediately under the if statement is executed; the code indented under the else statement is not executed (or ignored). But if the if statement of this block of code is followed by a boolean value of False then only the code indented immediately under the else statement is executed; the code indented under the if statement is not executed (or ignored). Recall that an equal operator converts an expression like 2.0 == 2.0 to a boolean value of True or False. This equal operator together with the branching feature of the if: ... else: ... block of code can be used to solve the problem statement as shown by the code above. All that needs to be done to complete the solution is to increment the appropriate count variable.

How does the Incrementing of a Variable Work? 

The expression even_count = even_count + 1, for example, works as follow. Suppose event_count is initially assigned a value of 5. The assignment operator (=) first evaluates the expression on its right side; event_count + 1 is replaced with the value of 6 because 5 + 1 is equal to this value. Then the assignment operator assigns this new value to the variable, thus overwriting or replacing the old value of 5 with the new value of 6 as follow. event_count = 6

The Modulo Operator: 

The modulo operator, represented by the % symbol, is used just like the division operator but instead of getting the result in decimal form, 5 / 3 = 1.66 for example, the [modulo] operator gives us only the remainder of a division operation, 5 % 3 = 2 for example.

Revisiting the definition of an odd and even number we see that an odd number will always have a remainder whereas an even number will not have a remainder. We can combine this definition with the modulo (%) operator to check if a number is odd or even in a more concise way. Before we can use the modulo operator we make the observation that any even number modulo 2 will always compute a remainder of zero whereas an odd number modulo 2 gives us 1. Examples of even numbers follow. 0 % 2 = 0, 2 % 2 = 0, 4 % 2 = 0, 6 % 2 = 0, etc. Examples of odd numbers follow. 1 % 2 = 1, 3 % 2 = 1, 5 % 2 = 1, 7 % 2 = 1, 9 % 2 = 1, etc.

To use the % operator we can either assign the result (or evaluation) of the operator to a variable as shown in the count_odd_and_even_numbers_second_attempt() function like so, result = number % 2, and then check the value in an if statement or allow for the evaluation of the % operator to occur directly in the if statement without the need to use an additional variable as shown in the count_odd_and_even_numbers_third_attempt() function, like so if number % 2 == 0:.

The Increment Operator: 

Another useful operator that allows us to increment a variable is +=. As we saw in our first attempt function we incremented a variable with the following code. some_variable = some_variable + 1. We can write the equivalent of this expression instead as some_variable += 1. An actual use of this operator can be seen in the second attempt function.

Multiple Assignments: 

Note that in our third attempt function we declared and assigned initialization values of zero to both count variables but we did so on a single line. This is equivalent to declaring and assigning the count variables on separate lines. Both approaches are valid and you should pick the option that makes the most sense and is most visually pleasing to you.

Note that the third attempt function is less verbose than our first attempt and arguably more readable. It's also possible to make further refinements but we will explore other options in future tutorials.

Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 2

The Problem Statement:

Program 1 showed us how to iterate over a range of numbers with the use of a for loop and the range function. Suppose instead of a range of number we have a bunch of numbers that are contained in data structure called a list. Given a list of numbers, how do we iterate over it using a for loop?

The task, just like program 1, will be to write a Python program that displays a list of numbers from 4 to 9. Next to each number, the program will also display its square. But unlike program one where we used the range function to generate the range of numbers along with their square, we instead will use a list of number and iterate over it in three different ways.

The following is the expected approximate output of program 2. The output is repeated four times. Note that for the last example we will iterate over the number in reverse order:

    4 16
    5 25
    6 36
    7 49
    8 64
    9 81
    --END---
    4 16
    5 25
    6 36
    7 49
    8 64
    9 81
    --END---
    4 16
    5 25
    6 36
    7 49
    8 64
    9 81
    --END---
    9 81
    8 64
    7 49
    6 36
    5 25
    4 16
    --END---
    

The Solution:
    

def program_2():

    """LOOP 1"""
    for number in 4, 5, 6, 7, 8, 9:
        print(number, number * number)
    print("--END---")

    """LOOP 2"""
    for number in [4, 5, 6, 7, 8, 9]:
        print(number, number * number)
    print("--END---")

    """LOOP 3"""
    list_of_numbers = [4, 5, 6, 7, 8, 9]
    for number in list_of_numbers:
        print(number, number * number)
    print("--END---")

    """LOOP 4"""
    reverse_list_of_numbers = list_of_numbers[::-1]
    for number in reverse_list_of_numbers:
        print(number, number * number)
    print("--END---")


if __name__ == '__main__':
    program_2()



LOOP 1:

The range of values are from 4 to 9. The comma is used to separate the numbers so that the for ... in loop can distinguish between the unique numbers and consume them.

LOOP 2:

The list of values is explicitly defined by the usage of the opening and closing brackets. That is, the use of [ (opening bracket) and ] (closing bracket)

LOOP 3:

We can also assign the list of values to a variable called list_of_numbers and then use the variable in the for loop. The use of the variable will allow us to reuse the list of number in the subsequent, and last, for loop.

LOOP 4:

We reverse the list of numbers with the use of the so called slice operator. The slice operator is a shorthand notation that is used when we want it iterate over a list in a custom order. There are many ways to use the slice operator. We show only one example in this tutorial. The slice operator, [::-1], iterates over the list_of_number in a reverse order; returning a new list of numbers but in reverse order. This reverse list of numbers is captured by the reverse_list_of_numbers variables, which on the next line is used by the for loop. More on the slice operator in a future tutorial.

Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 1

The problem statement:

Program 0 provided a solution to the problem statement but it is an inefficient way to salve it. The solution required us to perform repetitious work. For that problem we only had to display the numbers from 4 to 9 along with its square. Now imagine if the problem required us to display numbers, along with their square, from 4 to 79. Our solution with be unnecessarily long and take an unacceptable amount of time to complete.

The task, just like program 0, is to write a Python program that displays a list of numbers from 4 to 9. Next to each number, the program will also display its square. But unlike program zero we are expected to write program 1 using less code such that we minimize as much as possible the repetitious work.

The following is the expected approximate output of program 1:

    4 16
    5 25
    6 36
    7 49
    8 64
    9 81

The Solution:

def program_1():
    for number in range(4, 10):
        print(number, number * number)


if __name__ == '__main__':
    program_1()

Program 1 introduces a powerful programming feature called a for loop, that allowed us to write a concise solution to this problem.

Why is it called a for loop?
It's called this because for each member in a given list of items, the code indented under a for loop will be looped over and executed a number of times that is equal to the number of items in the given list. In our solution, the number of members in the given list of items is 10 - 4 = 6. Hence, our for loop executed our indented code, or nested code, exactly six times.

What is this range(..) function?
This range function creates an object that produces a sequence of integers from the start value of 4 to the stop value of 10 minus 1. That is, given the start value of 4 and the stop value of 10 the following sequence of integers is generated for the for loop to consume. 4, 5, 6, 7, 8 and 9. Note that the last value of 10 is not included in the sequence. If for example we wanted modify the code to start at 2 and end at 10 we would call the range function as follows. 11 - 2 = 9 for loops would be executed. 

range(2, 11)

 Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.

Problem Solving With Python: Program 0

The problem statement:

The task is to write a Python program that displays a list of numbers from 4 to 9. Next to each number, the program will also display its square. The square of a number is computed by multiplying it with itself like so. 4 x 4 = 16. Here, 16 is the square of 4.

The following is the expected approximate output of program 0:

    4 16
    5 25
    6 36
    7 49
    8 64
    9 81

The Solution:

def program_0():
    number = 4
    print(number, number * number)

    number = 5
    print(number, number * number)

    number = 6
    print(number, number * number)

    number = 7
    print(number, number * number)

    number = 8
    print(number, number * number)

    number = 9
    print(number, number * number)


if __name__ == '__main__':
    program_0()

How do I setup?

Follow the steps at this link to get started. When following the instructions assume that your machine does not already have Python installed so that you follow the instructions for downloading Python and making sure you install version 3.10. Ignore the details of the program in this example and instead focus on running the program in their example.

How do I run the program?

Running the code. If you followed the steps from the setup section than you should now how to create a file and run a Python program in Python. In your python project create a module (file) called program_0.py. Type the code in this file as shown and run the program. If your setup was successful then the Python interpreter should have run your program that generates some output within PyCharm.

What is a code interpreter?

The Python Interpreter is a program that reads and execute Python code. In order for the interpreter to be able to do its job, the program that we write must follow a set of rules. Code indentation is one of these rules. Violation if this or any programming rules will result in a program that does not execute or, even worse, a program that executes incorrectly.

What is a variable?

A variable is a name for a physical location within the computer that can reference either a single piece of data like a number or a character or data structures that can hold multiple pieces of data. In our program we define the variable number that holds a single number. As the name implies, a variable can be changes by our program as it is running. Our program first defines this variable number by assigning the number 4 to it. Our program then changes the value that our variable is referencing with the use of the assignment operator.

Why use a variable at all? 

Variables will allow us to write code that is concise, descriptive and reusable. The importance of these ideas will become more evident as we write programs with increasing complexity.

What is an assignment operator?

The assignment operator, denoted by =, is used to assign a value to variables. The following is a general form of an Assignment Statement.

variable_name = expression


What are Python Keywords? 

Python keywords are reserved words that should not be used except for its explicitly defined usage. The keywords used in this program are the following.

  1. def is used to define the start of a function.
  2. if is used to test a condition. In our case it is used to test if the variable __name__ is equal to the string __main__. If it is then the next indented lines are executed by the interpreter. In our case, our function, program_0() is executed, resulting in an output that is generated by our program.

       
What is a function? 

A function is a building block of a program; they are used to define code that is reusable and can be called anywhere within your program. Note how we first write our display logic in def program_0()... then further down we call it. Suppose we wanted to display the same values again immediately below the first program output. This can be accomplished in one of two ways. We can either modify our program to display the values twice or simply call our program immediately following the first call like so.

if __name__ == '__main__':
    program_0()
    program_0()

        
Hence, code reuse!

What is a built-in function?

Python is shipped with many standard built in functions. Our program the built-in print(...) function to display our values to the monitor. We can pass any number of variables to the print function with the use of a comma. The print function will display the variables passed to it by inserting a single space between them. The print function will also add to the end a newline character so that the display system will print the next values on a new line.

Page with links to the entire series can be found here

Are you having any issues running or understanding the program? Please, add a comment explaining where you are stuck or where the tutorial is not clear so we can improve it.