Showing posts with label Python. Show all posts
Showing posts with label Python. 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.

PyGest: A Python tkinter Tutorial, Conclusion

This is the final article in our Python tkinter tutorial series. If you've been following along from the beginning, you should now have a desktop file hashing application with a fully functioning graphical user interface!  Here is our final product:


PyGest: A Python Tkinter Tutorial, Part 5

This is part five in our Python tkinter tutorial series, in which we are building a simple GUI app to process and check file hash digests. In the previous two articles (part 3 and part 4), we configured the input and output widgets for our app. In this post, we're going to build out our app's two primary buttons and hook them into the appropriate input and output fields.


PyGest: A Python Tkinter Tutorial, Part 4

This article is part four in our ongoing Python tkinter tutorial series. When we left off in part three, we had just completed configuring the inputs for our interface, which included text entry, label and button widgets. We'll now move on to the widgets necessary for conveying the application's two outputs: 1) the hash digest value of the file input supplied by the user, and 2) a message indicating whether the file hash generated by the app matches the optional hash value that may be supplied by the user.



PyGest: A Python Tkinter Tutorial, Part 3

This is part three in our Python tkinter tutorial series on building a simple GUI app to compute and check file hash values. In part two, we added a banner header to our bare bones view by inserting a tkinter label into our app's content frame. In this segment, we will build out our app's various input widgets. Recall our mockup design:


PyGest: A Python Tkinter Tutorial, Part 2

This is part two in our Python tkinter tutorial series. In part one, we defined the basic structure of our script, set up a logger, and got the root window of our GUI application up and running in the app's single view class. In the present article, we'll begin work on the main view in earnest. We will configure the tkinter root object, create and configure a single frame to hold all the app's contents, and then create our app's title banner. First, however, we should discuss how to structure the layout of a Python tkinter application, and our strategy for doing so in the present project.

PyGest: A Python Tkinter Tutorial, Part 1

This is part one in our tutorial series on building a simple Python GUI app with tkinter. You can find the introductory article to the series at the link. In this article, we'll get things up and running by filling out the basic structure for our Python script and the application itself. We'll add a top level comment, define the necessary imports, set up our main name space, define the main function, and then configure a logger to aid in sanity checking . . .

PyGest: A Python tkinter Tutorial, Introduction

In this tutorial series, we are going to build a simple file hashing application using the Python standard library's interface to the TK GUI toolkit: tkinter. One can find some resistance to using tkinter in the Python community. However, my interest in tkinter was recently rekindled after watching "Tinkering with Tkinter", a presentation by Russel Keith-Magee, in which the Django developer makes a strong case for revisiting this often overlooked and under-appreciated component of the Python standard library . . .

Python: What to do after you've finished Code Academy?

One of the most common beginner questions I see in Python programming forums is from people asking what to do once they’ve completed Code Academy’s Python training course. The possibilities are virtually limitless and may seem overwhelming at first, especially if you have little prior programming experience. It’s a bit like finding yourself in a foreign country where you know enough of the local language to just get by, but not enough to really find your way around. I certainly don’t claim to have the map, but in this post I’ll try to point out a few landmarks that might help some folks get their bearings. 

The Code Academy course covers the basics of Python syntax and data structures, and provides a quick introduction to more advanced topics like the use of list comprehensions, bitwise operators, classes, file input/output etc. Along the way, the student also completes a handful of small projects to demonstrate how this newly acquired knowledge can be put to use, for example, a pig latin translator, a Battleship game simulator and so on.

But the big question is: what next?! There is no straightforward answer to this question, as it depends on a number of highly individual variables such as your level of prior programming knowledge and experience, your interests, your goals and motivations for learning programming in general and Python in particular, not to mention the amount of time you are able to devote to study and practice, to name just a few. For the sake of simplicity, what follows is targeted to a beginner who has recently completed an introductory Python crash course such as Cody Academy’s Python Track, or Learn Python the Hard Way, has little or no prior programming experience, and can devote a modest amount of time to study and practice on a regular basis. 

As a natural language instructor, I can almost always tell when a student has not done any homework or practice over a long weekend: they are already starting to get rusty! Probably the single most important thing to do after an introductory course like Code Academy’s is to reinforce the lessons learned, and to do it on a consistent basis. This will help to shore up all that newly acquired knowledge and provide a sturdier basis to extend it and expand on it. This could be anything from reading a textbook to watching a series of lectures, or following along with another tutorial, exploring other areas of the Python universe, tinkering with your own little programming projects, or some combination of these, or even all of the above. 

You’ll likely also find that these activities are themselves mutually reinforcing: while working on your own projects, you’ll realize when you’ve hit a wall and need to consult some documentation or a textbook, or seek out a new library or framework to help achieve your goal; reading through a textbook you’ll be exposed to new ideas that you can experiment with in the interpreter or in your own little projects; working through a tutorial, you might find a piece of code that interests you and which you start to tweak on your own to see how it works and to experiment with extending it or expanding on it in some way, shape or form.  

If Code Academy was your first exposure to programming in general, it might be a good idea to consider working through a general introductory textbook (or even an introductory course!) on computer science. This will provide you with a basis in the fundamentals of the discipline as a whole, things that are more or less the same across all programming languages. 

So far as introductory textbooks go, many people, myself included, highly recommend Think Python: How to Think Like a Computer Scientist, which is freely available online.   This book is required reading for a number of well known introductory computer science courses such as MIT’s Introduction to Computer Science and Programming, and was written for the express purpose of introducing students to the field. It is highly readable, provides a review of basic syntax and covers intermediate as well as more advanced topics, along with a series of chapters on object-oriented programming and design. 

Along similar lines, if you have the time to devote to it, I highly recommend MIT’s Introduction to Computer Science class. All the lectures, recitation sections and course materials are freely available online in their entirety, and the course uses Python as its pedagogical language of choice. For more information on this course, see our previous post Teach Yourself Python in Less Than Four Months, which provides a learning plan that uses the MIT course as its guide.  

Okay, but what if you are not the type who likes to curl up with a good textbook, and don’t have the time to slog through a college level introduction to computer science course, but want to delve more deeply into Python itself? What then? In this case, you might consider working through another general introductory tutorial on Python programming, this will help consolidate the knowledge you’ve already gained and also likely expose you to more beginner and intermediate level aspects of the language and the programming process. There are tons of such resources available online. Here are a few that I've found quite helpful:
"Bah," some may say, "I'm bored of mechanically typing out tutorial code! I want to experiment, but I'm not sure where to begin!" Not to worry, there's tons of stuff out there, you just have to know where to look. For those who want to jump right in to real problem solving, your first stop should be the Programming Mega Project List. This is a list of around 100 practical programming projects that can be solved in any programming language. The difficulty level of the various projects ranges from beginner to advanced and the list broken down into basic categories such as math, algorithms, networking, text, web, and so on. Find one that interests you, tackle it and repeat.

Other people may find it rather uninteresting to solve problems for the sake of problem solving, and would rather explore Python itself. The standard library is your friend! One of the great things about programming is that it can make your life a whole lot easier. If you stick with programming, one thing you will learn rather quickly is that programmers are lazy and proud of it. If I had a dime for every time I’ve come across a talk or article on programming which proclaimed that programmers are lazy, I’d probably have like $10 by now.  I guarantee there is some absurd, repetitive task that you have to complete on a regular basis that can be automated with a relatively simple Python script. For these everyday routines, there is also very likely a standard library module that can aid you in your endeavor. Relevant xkcd:


Maybe you work in an office and have a tedious spreadsheet task you have to complete on a regular basis. Automate it with the csv module. Perhaps you’re in a band and hate writing up set lists, write a random set list generator with the random module. Maybe you like sports or finance, and are constantly looking up scores or quotes. Write a command line app to grab them from your favorite online source using urllib without having to open a browser.  If you’re a news junky, you could consider writing your own RSS headline aggregator with urllib and one of the XML modules. The possibilities are literally limitless. 

Last but not least, as a beginner Python programmer, you will most definitely want to begin checking out the many great frameworks that have been built around the language.  "A software framework is a universal, reusable software platform to develop software applications, products and solutions," says Wikipedia. At the most basic level, a software framework is a library or set of libraries that provide generic functionality for routine tasks to aid in the development of applications and programming projects. In the Python universe there are tons of frameworks to explore, such as web frameworks for the development of web applications, GUI frameworks for development of graphical user interfaces for desktop applications, and so on. Some of my favorites:
Well, that concludes our tour of some noteworthy landmarks in the Python programming space. As always, feel free to provide your own favorite resources or suggestions in the comments.

Unit Testing and Test-Driven Development in Python

There are both advantages and disadvantages to being self-taught in any given discipline. In certain cases, the advantages and disadvantages can overlap or even coincide. For example, when you are self-taught, you are not confined by institutional structures and courses of study. On the one hand, this allows for a distinct measure of freedom to pursue one’s own interests in the field, which would not necessarily be afforded to a person following a traditional disciplinary curriculum. On the other hand, this also means that it can be quite easy to develop gaps in one’s basic knowledge of the discipline, for the simple reason that these areas of study did not fall within your area of interest.

I discovered one such gap in my study of programming in general, and Python in particular, a number of months ago when I came across a quote online that went something like this: “Code that is not tested is broken by definition.”  Testing? “You mean running the code to see if it works?” I thought to myself. Within the next hour I had my first exposure to the method of test-driven development and the Python unittest module.

This was literally the exact opposite of how I had approached my own programming projects up until then, which might be termed “error-driven development”: write some code; run it; see if it works; if it doesn’t work, tinker at random until it does; write some more code and repeat. I quickly realized that, according to the above quote, all my code was broken, by definition. 

The test-driven development model is the reverse of this: write a test, run it and watch it fail; write some code to make the test pass; refactor; write another test and repeat. It was an enlightening experience to attempt writing even a simple program under a test-driven model, as it was immediately obvious that I had only the vaguest notions about things that I thought I knew fairly well.

Since then, I’ve re-written a number of programs I’d created for myself under a completely test-driven developmental model, and have integrated testing into my everyday coding practice. I’ve also collected a bunch of resources that I've found helpful along the way, which you can find below. Also, as you may know, of late there has been something of a controversy brewing on the merit and value of test driven software development. Some links on this are supplied at the end. As always, further recommendations are welcome in the comments!

Overview of Test-Driven Development (Video Lectures)

Unit Testing in Python (Video Lectures)

Python Unittest Module Docs

Python Unittest Intro Tutorials

Test Driven Development in Python

Unit Testing Today

50 Python Resources for Beginner and Intermediate Programmers

This is the third post in our recent series for beginning Python programmers.  In the first post, I detailed a self-study time table for beginner Python programmers.  The second post then laid out learning benchmarks for the project on the basis of MIT's Introduction to Computer Science course.  Today's installment provides a categorized list of Python resources for beginner to intermediate programmers.  Add any others you've found helpful in the comments and I'll update the list.  Enjoy!

Textbooks
Think Python: How to Think Like a Computer Scientist
The Art and Craft of Programming: Python Edition
A Byte of Python
Code Like a Pythonista: Idiomatic Python
Python Programming WikiBook
Python Style Guide
The Hitchhiker's Guide to Python
Building Skills in Python: A Programmer's Introduction to Python

Tutorial Textbooks
Learn Python the Hard Way
Dive Into Python
Hacking Secret Ciphers with Python
Invent Your Own Computer Games with Python
Making Games with Python and Pygame
A Beginner's Python Tutorial: Civilization IV

Intro Web Tutorials
Learn Python in Ten Minutes
Code Academy: Python Track
Python-Course: Intro to Python
Google Developers: Python Introduction
pGuides: Python
New Coder Python Tutorials
Tutorials Point: Python

Video
Python Video Index
43 Short, Targeted Intro Python Video Tutorials 
A Hands-on Introduction to Python for Beginning Programmers 
Python for Programmers: A Project-Based Tutorial
Google Developers' Python Class
Learn Python Through Public Data Hacking
Growing Python with Spreadsheets
Python for Hackers: Networkers Primer

Targeted Web Tutorials
How to Use the Reddit API in Python
Intro to Python Web Scraping
Python Network Programming
Sockets in Python: Into the World of Python Network Programming
Sockets Programming in Python
Python gnupg (GPG) Example

GUI Programming
An Introduction to Tkinter
Getting Started with wxPy
Creating an Application in Kivy 

Web Programming
Hacked Existence Full Django Website Tutorial Series
How to Tango with Django

Targeted Textbooks (Advanced)
Natural Language Processing with Python 
Data Structures and Algorithms with Object-Oriented Design Patterns in Python 

Reference
Python Standard Library
Python Package Index
Effbot Guide to the Python Standard Library
Python Module of the Week
Python Cheat Sheet (quick reference guide)
Ivan Idris' Almost a Hundred Python Resources

Projects and Sample Code
Karan's Python Mega Project List
Active State: Popular Python Recipes

Benchmarks: Teach Yourself Python in Less than Four Months, Part II

In the first post of this series, I developed a self-study time table for beginner Python programmers, using MIT's free online Introduction to Computer Science course as my general guide.  The present article will look more closely at the MIT course to set up learning benchmarks on the basis of the course's problem sets and quizzes.  The next post in the series will provide links to related but alternative text and video resources available for free on the web.

Before jumping in though, let's take a step back for a moment.  MIT is consistently rated one of the top universities in the world for computer science and information systems.  It's courses are challenging, to say the least. But, more importantly for the current context, we should also keep in mind that its courses are geared toward students who are completing degrees in engineering, physics, biology, chemistry and the like. And this orientation is reflected in its Introduction to Computer Science class in the course's focus on scientific computing, and in the choice of topics emphasized in its problem sets and quizzes.

Working through the course on their own, many people may find this aspect of the course intimidating or uninteresting, or simply irrelevant to their own individual learning goals.  The next post in this series will therefore provide alternative resources to supplement the course materials that may prove of interest to people whose primary focus is not on scientific computing. 

In the previous post, I worked out a time table for completion of the course which began by assuming a person would devote 10 hours of work to this project every week, and  finish the course in 15 weeks.  (You can also consult that post for alternative time lines.)  That ten hour weekly work load was broken down in the following manner:

      • Watch the lectures (2 @ 50 mins): ~2 hours
      • Textbook and background reading: ~2 hours
      • Recitation/discussion video tutorial: ~1 hour
      • Homework problems and exercises: ~2 hours
      • Free study tutorials or reading: 1-2 hours
      • Free study independent projects: 1-2 hours

With that in mind, let's set up some learning benchmarks using the course's 3 quizzes as our primary guide, with the interstitial space filled in by its 12 problem sets.  To begin, let's note when the quizzes are scheduled and what topics they cover.  Then we'll have a general sense of how much work-time is necessary to grasp those topics.

Quizzes

Quiz #1 follows the 9th lecture in the course.  You can find its topic list here.  It covers:
  • • Basic computer science terms and definitions: syntax, semantics, straight line vs. branching vs. looping programs etc.
  • • Basic aspects of Python: values, types, expressions, statements, control-flow, functions, scope.
  • • Basic algorithmic techniques: guess and check, linear, bisection, approximation, Newton's method.
  • • Binary representation of numbers
  • • Debugging protocols
  • • Orders of growth  
Quiz #2 follows the 19th lecture in the course.  You can find its topic list here.  It covers:
  • • Big O notation and orders of growth
  • • Sort and search methods and algorithms
  • • Python: values, types, (im)mutability, control flow, functions/methods, recursion, objects/classes, simulations
  • • Basics of statistics: standard deviation, confidence, linear regression
  • • Data abstraction, debugging
Quiz #3 is the course final, and follows the 26th lecture in the course.  You can find its topic list here.  It covers those topics found in the first and second quizzes, and it adds the following:
  • • Call stacks, exceptions, polymorphism
  • • Algorithms: divide and conquer, basing, orders of growth
  • • Simulations
  • • Basic statistics and computational models
  • • Optimization strategies  

Problem Sets

The course also has 12 problem sets.  Here we'll simply note when each is due, and what it covers:
  • 0) Due lecture 2: install python, set up IDLE, write a basic program to get user info, print out that info
  • 1) Due lecture 4: simple debt calculator, bisection search
  • 2) Due lecture 6: successive approximation and a word game, i.e. Newton's Method and Hangman
  • 3) Due lecture 7: debugging, implementing two versions of game introduced in lecture
  • 4) Due lecture 10: implementing a version of the Caesar Cipher
  • 5) Due lecture 12: implementing an RSS feed filter
  • 6) Due lecture 14: simulating a Roomba, using classes
  • 7) Due lecture 16: simulating spread of disease and virus population
  • 8) Due lecture 18: optimization, topic cont'd from previous assignment
  • 9) Due lecture 20: schedule optimization
  • 10) Due lecture 22: clustering to analyze census data
  • 11) Due lecture 24: optimization, finding most direct route between two points
Note: Detailed information on each of the problem sets can be found on the page for the lecture when that problem set is due.  So, the information for problem set 0, which is assigned in lecture 1, is actually on the page for lecture 2

Benchmark Summary

Let's now cross-reference the quiz schedule with the problem set schedule, and estimate the number of hours necessary to complete those assignments on the basis of our time table above.  We see that:
  • quiz #1 coincides with problem set #4 and lecture 10: ~ 40-50 hours of work
  • quiz #2 coincides with problem set #9 and lecture 20: ~ 90-100 hours of work
  • quiz #3 coincides with problem set #11 and lecture 26: ~ 150 hours of work
In the next post in this series, I will detail alternative text and video resources that can be used to supplement the materials offered in the MIT course.  

Online Learning: Teach Yourself Python in Less Than 4 Months, Part I

The purpose of this article is to lay out a general time management template for anyone who wants to jump in to programming and computer science with little or no experience in the field.  A future article will flesh out the details, providing links to learning resources and other materials freely available online.  [Edit: See the second article in the series, which covers learning benchmarks for beginner Python programmers.]

For starters, I should say up front that I do not have any formal background in Computer Science. I'm a language teacher by trade and training, and never really considered myself a "computer person."  But some time back, after expressing some interest in programming to a programmer friend, he challenged me to try and pick up a programming language. The gist of his argument was fairly straightforward: if you can understand English, with a bit of effort you can understand a programming language, it's just syntax and semantics.  That made it sound pretty simple, and my interest was piqued, so I set to work. 

After doing a bit of background research, I decided that I would focus on the Python programming language, using MIT's Introduction to Computer Science and Programming course – all the materials for which are available for free online – as my general guide.  I finished that course within three months, supplementing it with tutorials and readings that were more in line with my own particular interests. The skills and knowledge that I acquired in that time have proven to be indispensable in my daily life, for both work and play, so much so that I wonder how it is that I was able to get by for so long without them! 

As stated above, I do not have any formal background in computer science.  However, I have over ten years of experience in planning, developing and teaching natural language learning curricula, from task-based lessons to overarching course goals, in two languages.  This article will lay out a general time-plan for self-guided study of the Python programming language for absolute beginners, using the MIT Introduction to Computer Science class as its overarching framework and scaffold.   

To begin our assessment, let's take a closer look at the MIT course. The class has 26 lectures, each about 50 minutes long, for a total of 1300 minutes, or 21 total hours of time, less than a single day.  In theory, you could easily blow through the whole course's lecture series over a long weekend, if you did it like it was your job, or a marathon of your favorite television series on Netflix.

Obviously, that does not mean you can learn all the material covered in those lectures in a three day period.  The process of learning requires things to sink in, as it were, and that just takes time.  Furthermore, it just wouldn't make any sense to simply blow through all the lectures in this way, because we still have to account for the recitation/discussion sections associated with the course, as well as for the independent study necessary to complete homework assignments, which would be normal for any university course. 

In a serious course of study at any college or university, and even for graduate level work,  disciplined students should expect to devote around ten hours a week to study for each course they take.  Assuming a full time work week of 40 hours, this would make taking four college or university classes the labor equivalent of a full time job. 

To begin working out our time table, let's therefore assume that a person should devote 10 hours a week to this project.  A college semester is about 15 weeks long, so that comes out to 150 hours of total work to successfully complete a course that like offered by MIT.  Assuming you did nothing else except this, as if doing the work for this single course were a full time job at 40 hours a week, you could complete it within a month. This is doable, but very intensive. To finish in 3 months, you'd have to devote 12-13 hours to it a week.  To finish in six months, you would have to spend 6-7 hours on it a week.  To finish it in a year's time, you could spend just 3-4 hours of work on it a week. 

For the sake of simplicity, let's assume that we have 10 hours a week to devote to this project, taking our benchmarks and cues from the syllabus for the MIT course.  (We'll work out alternative time lines at the end of the post.)  What do we do with all this time?  The answer is deceptively simple:  watch the lectures, read, do tutorials and exercises, and begin work on your own individual programming projects.  Let's flesh this out a bit.   

With 26 lectures at 50 minutes each, that comes out to 100 minutes of lectures a week, the equivalent of the time you might spend watching a bad movie you wish you hadn't watched to begin with.  In a university course, each week you are also going to spend around another hour in your discussion/recitation section, reviewing materials covered in the corresponding lectures.  That leaves us with around 7 hours and 20 minutes of time for independent study.  How should one spend that time?  Reading, research and practice. 

Let's assume that in a given week, the professor covers more or less the same materials that can be found in the course textbook, in more to less the same amount of time that it would take you to read those sections of the text(s).  So now we have a ballpark figure of 1.5 hours to devote to reading, leaving us with just under 6 hours of time left for the week. 

Doing the reading is not an end in itself, there are also homework assignments that need to be completed. In the MIT course, the homework and problem sets reinforce the lessons covered in the lectures. However, as you complete such exercises, you will find that there are things in the textbook or from the lecture that you did not understand, or you will come across a problem that requires looking into something that has not yet been covered in the lectures or readings at all, and you will therefore have to inquire into these things a bit more closely. So homework will also necessitate more reading, research and tutorials.

Let's assume that doing the homework requires about as much time as you would normally spend in class including discussion section, around 2.5 hours.  We're now left with 3.5 hours of free study time to do with as we please.  This can be spent doing more background reading, tutorials, exercises, or working on one's own little programming projects. 

So here's our plan for 10 hours of work a week, to complete the course in about 15 weeks:
   • Watch the lectures (2 @ 50 mins): ~2 hours
   • Textbook and background reading: ~2 hours
   • Recitation/discussion video tutorial: ~1 hour
   • Homework problems and exercises: ~2 hours
   • Free study tutorials or reading: 1-2 hours
   • Free study independent projects: 1-2 hours

Let's break this down even further.  For each 50 minute lecture, one should do:
  • 1 hour of reading
  • 30 minutes of recitation/tutorial videos
  • 1 hour of problems or exercises
  • 1 hour of targeted external tutorials
  • 1 hour on your own little project(s)

Assuming you were to devote 90 minutes a day, 3-4 days a week to this project, within 4 months, you will have watched all the lectures from the course, read a couple books, done tens or hundreds of problems, completed a number of tutorials, done a lot of online (re)searching, and created a bunch of your own little programs, putting in 150 hours of work.

Doing 90 minutes a day, 2 days a week, it would take 50 weeks, just under a year, to complete the course.  Doing 60 minutes a day, 3 days a week is the same, of course.    

Doing 90 minutes a day, 3 days a week would take 33 weeks, about 8 months.

Doing 90 minutes a day, 5 days a week would take 20 weeks, or 5 months.

Doing 90 minutes a day, every day, would take 3.5 months. 

Doing 2 hours a day, 3 days a week would take about 6 months. 

Doing 1 hour a day, every day, would take just over 5 months. 

In the next article in this series, I'll detail specific textbooks, video and text-based tutorials, and other assorted learning materials to help put some muscle on the skeleton framework presented in this post.  

See the second article in the series, which covers learning benchmarks for beginner Python programmers.