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

Shot Through The Art, And You're To Blame: New Tattoo Recognition Software Spots Evildoers By Their Ink

We all know that the encroaching insidiousness of facial recognition technology is getting harder and harder to thwart.  This can be somewhat of a good thing, like when it actually catches criminals or finds your lost dog, but for the average citizen, you can't even skip church without getting compiled into a face database (dataface?) these days.  No matter how much weird makeup you use to try to obscure yourself, there's just too many cameras out in the world attempting to capture your likeness.  Now, the technology has been refined to include the art on your body in addition to your body itself...


Just in case you didn't make it this obvious.
(Image courtesy creativefan.com.)

X Marks The Spotted: Windows 10 Is Watching You

As citizens of the cyber-community, we've unfortunately become conditioned to seeing ads that are eerily targeted to things we say, emails that appear from long-forgotten websites, and other evidence of deep data gathering made manifest for use of moneymaking.  Now, with the launch of Windows 10 becoming a necessity for some users, Microsoft seems to have pulled out even more stops to speed up their spying...

Seriously, what ISN'T spying on us these days?
(Image courtesy hackread.com.)

Who Would Jesus Watch? New Facial Recognition Software Tracks Church Attendance

Oh, god.  As if it weren't "bad" enough in the eyes of The Most High that your lapsed morals caused you to skip church on Sunday to be a brunch-munching heathen or false-idolater football fan, now you've also been caught...by computer.


The lord doesn't always work in mysterious ways...sometimes it's just computers and cameras.
(Image courtesy hackingchristianity.net.)

TAX ATTACKS! Your Guide To Online Tax Filing

Alright, Americans, it's time to pony up your pennies to Uncle Sam again.  It's one of those necessary evils, like death, except it happens to you every year.  Fortunately, like so many other aspects of modern life, we have computers that are here to help with this issue...

Keep as much of your hard-earned loot as possible!
(Image courtesy bostinno.streetwise.co.)


E-Emotional Rescue: Computer Programs That Deal In Your Feelings

Experts say that your computer is a better judge of your personality than even your closest family and friends.  It knows your preferences, correspondents, written words, tastes in imagery, secrets kept and deleted, and more.  But what happens in the possibly-near future when machines begin using all of this information to actually UNDERSTAND you?

When it comes to emotional intelligence and your computer, what constitutes too much information?
(Image courtesy singularityhub.com.)

According to the New Yorker, this may be happening more quickly than we expect.  Computers can already attempt to determine moods from vocal pitch and intensity, while simultaneously analyzing any attendant videos for evidence of micro-expressions or gestures that could reveal even more about an interaction.  Even the placement of words in a sentence can be taken to imply other things, indicating how angry, passionate, or spectacularly talented certain authors are.  Now, computers can not only be aware of these elements, but use them to temper their own responses or advice.

Rana el Kaliouby, an Egyptian scientist who runs the Boston-based company Affectiva, is on the forefront of this mecha-emotional leap.  Affectiva's most prominent software, Affdex, is trained to recognize four major emotions:  happy, confused, surprised, and disgusted.  Breaking down the user's face-image into deformable and non-deformable points, the software analyzes how far certain parts of one's face will move (such as a smile or frown raising or lowering the corners of the mouth) in relation to other set points on the face (such as the tip of the nose.)  Things like skin texture (where wrinkles appear, or not) also factor in.  These metrics are analyzed into computing what you feel.

Based off the research of 1960s scientist Paul Ekman, the idea behind this technology stems from a simple, universal concept:  all humans, regardless of race, gender, age or language barriers, have at least six specific facial expressions that register particular emotions.  Ekman broke these expressions down into their constituent movements and wrote a 500-page epic called FACS (Facial Action Coding System) on the subject.  The work has been considered the preeminent treatise on this topic for decades now.

Other companies are on the e-emotional bandwagon too, with names like Emotient, Realeyes, and Sension.  Companies who rely on videoconferencing could now have a useful extra line on what their clients and associates are thinking.  Emotions, which have been found to be closely neurologically related to decision-making and common sense, now can be deduced from faces and choices with a degree of accuracy that seems like mind-reading.

We're less unique than anyone thinks.
(Image courtesy thewaylifeis.com.)

While useful (and now predominantly operational) in business, Kaliouby also spent time researching if this specific recognizance could act as an "emotional hearing aid" for those with autism.  The National Science Foundation offered Kaliouby and her mentor nearly a million dollars to develop this idea.  This proved successful, but the idea was almost immediately extrapolated by businesses from Pepsi to Toyota in the interest of learning more about their consumers' preferences.  These requests overwhelmed the scientists, leading to the creation of Affectiva.  The company, which claims to have refused requests to use the software for espionage (corporate and personal), wanted to generate revenue from investors to augment their autism-relating research.

Thus Affdex began testing users' response to advertisements, giving the promotions industry a leg up on what consumers would be feeling when exposed to their sales pleas.  More than two million videos from eighty countries lent the program an unprecedented amount of information, all adding up to more accuracy in prediction from the program.  Affectiva now deals in these negotiations and improvements full-time.  In coming years, with more "smart" devices and internet-enabled items out there for our interaction, emotional electronics could use their ever-increasing knowledge to hopefully make our lives better.

These programs have our attention, which is a valuable resource.  Now, can that be used to hold our interest, connect us more completely, and/or improve our circumstances (even just by knowing we need the room temperature raised a little?)  Or will it simply serve as another metric to keep tabs on a passive populace?  Will we have the right to know when and where we are being emotionally analyzed, and will we be able to thwart such advances if desired?  Kaliouby maintains that there must be an overall altruistic tilt to the usage of the program, explaining to various advertisers that, “In our space, you could very easily be perceived as Big Brother, as opposed to the gatekeeper of your own emotional data—and it is two very different positions. If we are not careful, we can very easily end up on the Big Brother side.”

Whether we'll end up selling our attention to gain happiness points to sell for more happiness remains uncertain.  But the fact remains that the market for your emotions is vast and lucrative.  Companies will want to know you're happy if it makes them feel they're doing something right.  Other more insidious organizations may be tickled to learn that you're feeling deeply unsettled and on edge (right where some of them want you.)  Will the future be made of humans wearing constant poker faces, lest we be called out by computers?  Will there be surcharges for extra super-sized doses of happiness from certain places or products?  Or should we maybe turn the lens in on ourselves, and understand the nature of our own feelings, before we release them into the wild to be tagged and tracked...or hunted?

And remember, all of this information is taken from imagery alone.  We're not even really "plugged in" yet...
(Image courtesy rdn-consulting.com)






Grounding Big Brother: Amnesty International Releases Anti-Government-Spyware Detection Software

Are you a closet revolutionary who is constantly aware of the deterioration of society and informs themself on ways it can be fixed?  Are you a casual bystander who once googled a song by a band that prided themselves on questioning authority?  Are you just paranoid as hell that the Man is out to get you?  Now, you can stop governmental cyber-peeping for sure, thanks to new technology released by Amnesty International.

As reported by the BBC, it is no secret that governments use "sophisticated spying tools that could grab images from webcams or listen via microphones to monitor people." Amnesty International knows how wrong that is, and has released the Detekt software to combat Big Brother's unsavory advances. Detekt scans your computer for government-grade spyware that might be missed (or intentionally looked over) by other more mainstream virus or malware detectors.

They're not this overt, but they are this unpleasant.
(Image courtesy wpremedy.com.)

Created through a collaboration between Amnesty International, the Electronic Frontier Foundation, Privacy International and Digitale Gesellschaft, the free software is designed to operate on Windows (the platform which most spied-on people are apparently using.) Its availability should be helpful in putting a damper on the $5 billion international government spyware market.

That's your tax money, getting spent to indiscriminately spy.  Kill the idea that this could ever be acceptable.
(Image courtesy betanews.com)

"People think the uses of spyware by governments are isolated cases. They are not," said Claudio Guarnieri, the German creator of Detekt. "Their discovery is isolated...Spyware is becoming the final solution for surveillance operations to overcome encryption.

"The real problem is nobody really asked the public whether that's acceptable and some countries are legitimizing their use without considering the consequences and inherent issues."

One of those inherent issues being that average civilians shouldn't be covertly spied on by their government.  Better fire up the Detekt, we probably just got put on a list.

There is nothing noble about blindly swinging a cyber bat at peoples' computers, hoping a pinata of prosecutable info will explode.  Even if it did, that candy is probably supposed to be helping the people.
(Image courtesy thehackernews.com.)



Tetris-Enabled T-Shirt. That Is All.

Modern gamers have it so easy. You can race, shoot, hunt, hide, storm, and slay on portable platforms from your cell phone to a high-tech handheld gaming device. However, one man has taken this technology into an entirely different realm: fashion.

As reported by Time.com, "YouTube user Marc Kerger crafted the shirt, which features 128 LEDs and an Arduino Uno microcontroller board, in honor of Tetris’s 30th anniversary." A pair of AA batteries and you're off into belly-based, block-stacking bliss.

Tetris, the iconic Russian brainteaser, was invented in 1984 by Russian engineering student Alexey Pajitnov, and soon after took the world by shape-spinning, stackable storm.



E-Eats: Play Gourmet To Perfect Real-Life Cooking Skills

Do you want to create diverse, healthy meals, but don't think you have the skills? Don't want to risk expensive meal mistakes burning money? New software is poised to usher in a whole new means of cuisine: the CyberCook.

With elegant renderings, a vast array of ingredients, and realistic cooking technique motions involved, the game is as advanced visually as it is conceptually. Yet the technological breakthrough it symbolizes could reach outside the world of food and create greater educational methodology.

The CyberCook was developed by tech company Starship, whose CEO told www.factor-tech.com that,“It will change the way education is done, it will change the way the format is done of teaching people – and that’s the real clever bit, it’s not the 3D simulation, which everyone thinks is amazing, it’s actually the structure of what we allow people to do with it,” he said.

And perhaps with the dawn of 3-D printing (and maybe baking?), the social-media favorite word of "sharing" will take on a whole new meaning if your friends spot cookies in your e-oven.

But how do you throw a virtual pie?

Monkey In The Middle (Of My Parking Space): New Parking-Spot Auctioning App Banned In San Francisco

The new "sharing economy" sounds like a feel-good, community-building idea, but some elements of San Francisco have turned it into a very capitalistic marketing ploy. The new app MonkeyParking is designed to auction off soon-to-be-vacated parking spaces, which has given the wealthy a new societal edge but given middle-class communities a headache.

Claiming the app fosters a sense of community and "sharing", MonkeyParking is slated to park itself in New York, Rome, Seattle and Chicago soon.

The craziness of auctioning off publicly funded parking spaces is not lost to the sane media. Reporter Will Oremus of Slate notes, "I know this is Silicon Valley, where words have no meaning, but it takes a special brand of Ayn Rand–spouting nincompoop to try to pass off the unilateral privatization and scalping of public services as a new form of 'sharing.'"

Fortunately, citing a local statute that bans buying or selling of public parking spaces, San Francisco City Attorney Dennis Herrera has issued a cease-and-desist letter to MonkeyParking. But will the monkey be on your neighborhood's back soon?

Too much Monkey business.

Pirate Box: A Simple LAMP Stack Live Server Build

I first came across the PirateBox DIY project late last year, and thought it would be fun to set one up, but I didn’t really have an idea of where it could be put to good use. And then one day it hit me. I'm in a band and we play shows fairly regularly here in NYC. After shows people often ask if they can download any of our songs online (which, of course, they can), or they want to share pics they took during the set, or they want to get in touch with us and need our contact info, and so on. So I thought, hey, I’ll set up a Pirate Box for the band and run it as a live server during shows, and then people could share pics with us and one another directly, download songs directly from us rather than through an online middleman, get general info about the band, upcoming shows and so on.

I began hunting on Craig’s List for an appropriate router to install the PirateBox ISO, but had no luck. Being the impatient type, I broadened my search criteria and found someone selling an old Mac Mini for $50. Perfect. That weekend, I went to a local flea market and picked up a cheap soho router and some cables for another $10, and set to work.

Because of some apparent incompatibilities between the PirateBox ISO and the Mac Mini hardware, I decided to scratch the idea of installing the PirateBox ISO and instead create my own build from scratch rather than spend endless amounts of time troubleshooting and tweaking to get the hardware and software to play nice with each other.

After a couple weeks of research and tinkering, I managed to put together a nice little LAMP stack running a main portal page, a band Wiki, a chat room, and a song downloads page (see below for full details). I keep the setup in an old laptop case with the Mac Mini and the router inside, plugged into a power cord. I’ve since brought it along to two shows and set it up somewhere inconspicuous on stage. When we’re doing sound check I just plug in the extension cord, turn on the router and the server, and it’s good to go!

I configured the network and server so that once someone has hopped onto the wifi, all they have to do is navigate to serverhostname.local to access the server, and I set the wifi broadcast name and the host name of the server to the name of the band.  Here are some screen caps from the initial setup.  Once someone connects to the wifi and navigates to the correct url (in the present case: utm.local), they are greeted with a success page. 


Clicking the portal link takes them to the site's main navigation page.


From there, users can navigate to the wiki:


Or to the chat room:


 Or to the download page:


Try not to laugh at the download page, this was what it looked like after initial setup, it's since been spiced up a bit.  If you want to see it now, you'll just have to come out to one of our shows!

All in all this was a fun little project.  It took about a month's worth of work (mostly on weekends) to get everything up and running, including preliminary research, installation, configuration and customization, as well as the time spent setting up an initial test on a VirtualBox VM on my laptop. 

There were, however, some frustrating hurdles along the way: finding an Ubuntu Server ISO that worked without problems on the Mac hardware, getting hostname resolution to operate correctly for both iOS and Android devices (avahi-daemon eventually did the trick, though a bug in older generations of the Android OS prevents those devices from being able to resolve the hostname.local URL to the IP address of the server), and, perhaps most ridiculously, uploading the band's logo into the MediaWiki (though drinking a bit less beer during configuration would have probably made that process go a bit more smoothly!).   

There's a lot more that one could go into here: installing Ubunutu Server onto the Mac Mini, installing and configuring the LAMP stack, comparisons of the various open source software packages I decided to include, as well as those that I decided against, potential security issues running an open wifi at bars and clubs in NYC, and so on.  But perhaps those are best left to their own individual posts. So for now, that's all folks!


UTM Live Server Build

Hardware
• Mac Mini, $50 on Craig’s List
• Netgear router, $10 at a local flea market
• Cables, $5 at the same flea market
Total Hardware Cost: $65

Software
• OS: Ubuntu Server
• LAMP Stack:
    • Apache2 Web Server
    • PHP5
    • MYSQL DB
    • PHPMyAdmin
    • OpenSSH
• Web Interface:
    • MediaWiki
    • Blueimp’s AJAX Chat
    • PHP login module for the downloads page (adapted from Harvard’s Building Dynamic Websites online course)
    • Noir HTML5 Template optimized for mobile devices
Total Software Cost: $0

Microsoft Changes Office Licensing Conditions

From The Age:
In the push to shift customers to the Office 365 subscription model, Microsoft has rejigged the licensing conditions on retail copies of Office 2013 such as Office Home & Student 2013. People tend not to read this sort of fine print, but this bit is kind of important.
According to the fine print, retail copies of Office Home & Student 2013 are now single-license, so you can only install them on one computer. Some people interpret this as meaning that the retail license is now similar to the OEM license, which covers copies of Office that come pre-installed on a new computer. Under an OEM license you can only run Office on that specific computer. If you buy a new computer, you can't uninstall that OEM copy of Office from your old computer and reinstall it on the new one.
You could transfer a retail copy of Office from your old computer to your new computer, at least you could until now.  If you read fine print, the licensing conditions have clearly changed between Office 2010 and Office 2013.