Chapter 2: Input, Processing, and Output

"'The Babel fish,' said The Hitchhiker's Guide to the Galaxy quietly, 'is small, yellow and leech-like, and probably the oddest thing in the Universe. It feeds on brainwave energy received not from its own carrier but from those around it. It absorbs all unconscious mental frequencies from this brainwave energy to nourish itself with. It then excretes into the mind of its carrier a telepathic matrix formed by combining the conscious thought frequencies with nerve signals picked up from the speech centres of the brain which has supplied them. The practical upshot of all this is that if you stick a Babel fish in your ear you can instantly understand anything in any form of language. The speech patterns you actually hear decode the brainwave matrix which has been fed into your mind by your Babel fish.'
'Now it is such a bizarrely improbable coincidence that anything so mindbogglingly useful could have evolved purely by chance that some thinkers have chosen to see it as the final and clinching proof of the non-existence of God.
'The argument goes something like this: 'I refuse to prove that I exist,' says God, 'for proof denies faith, and without faith I am nothing.'
'But,' says Man, 'the Babel fish is a dead giveaway, isn't it? It could not have evolved by chance. It proves you exist, and so therefore, by your own arguments, you don't. QED.'
'Oh dear,' says God, 'I hadn't thought of that,' and promptly vanishes in a puff of logic.
'Oh, that was easy,' says Man, and for an encore goes on to prove that black is white and gets himself killed on the next zebra crossing."

-Douglas Adams, The Hitchhiker's Trilogy

Input, processing, and output are important concepts both on an abstract level, and a functional level. On the abstract level, many problems are solved by getting input, processing that input, and displaying an output. On a functional level, Python provides ways to both capture user input, and display output that is meaningful to the user. Processing on a functional level is simply the steps you take to solve a problem. Let's take a look at how Python handles input, processing, and output.

User Input

Python provides a function called input() that will collect a string from the user.

In [1]:
#String Input

myInputString = input("Please provide an input string: ")
output = myInputString

print(output)
Please provide an input string: Don't Panic!
Don't Panic!

If you need to prompt the user for an integer or float, Python provides methods to "cast" your input variable to another primitive data type.

  • int() will cast the input to an integer.
  • float() will cast the input to a float.
  • In [2]:
    #Int Input
    
    myInputInteger = int(input("Please provide an input integer: "))
    output = myInputInteger
    
    print(output)
    
    Please provide an input integer: 42
    42
    
    In [3]:
    #Float Input
    
    myInputFloat = float(input("Please provide an input float: "))
    output = myInputFloat
    
    print(output)
    
    Please provide an input float: 3.14
    3.14
    

    Processing

    Since the idea of input, processing, and output is pretty intuitive; let's look at an example of how we might solve a problem in Python using this approach. For instance, if a user needs to calculate a weighted average of three tests.

    It is often helpful to develop a program by first thinking about the problem in terms of analysis, design, and implementation.

  • Analysis: Understand the problem by writing down all of the needed variables.
  • Design: Pseudocode an algorithm that outlines the solution.
  • Implementation: Create a program that implements the algorithm.
  • </p>

    Example

    Problem: Using this grade assessment, compute a course grade as a weighted average for any combination of two tests and one final exam.


    Grade Assessment Item Percentage of Grade

    Test 1 (0.0 to 100.0) 25%

    Test 2 (0.0 to 100.0) 25%

    Test 3 (0.0 to 100.0) 50%

    Analysis:
    Variables

  • testOne
  • testTwo
  • testThree
  • weightedAverage


  • Example
  • testOne = 67
  • testTwo = 73
  • testThree = 93
  • weightedAverage = (67 x .25)+(73 x .35)+(93 x .50)


  • Design
  • get testOne as float
  • get testTwo as float
  • get testThree as float

  • process weightedAverage
  • (testOne x .25)+(testTwo x .25)+(testThree x .50) =81.5
  • display weightedAverage

  • Implementation

    In [4]:
    #Input
    testOne = float(input("Please provide a grade for test 1:"))
    testTwo = float(input("Please provide a grade for test 2:"))
    testThree = float(input("Please provide a grade for test 3:"))
    
    weightedAverage = 0.0
    
    #Process
    weightedAverage = (testOne * .25)+(testTwo * .25)+(testThree * .50)
    
    #Output
    print("The weighted average is:",weightedAverage)
    
    Please provide a grade for test 1:67
    Please provide a grade for test 2:73
    Please provide a grade for test 3:93
    The weighted average is: 81.5
    

    Formatting Output

    We have already learned about the print() function, which outputs data to the screen. Now let's look at some of the ways we can format that output data.

    Escape Character: An escape character is a special character preceded with a backslash ( \ ) that appears inside a string.

    Escape Character Effect
    \ n Causes output to be advanced to the next line.
    \ t Causes output to skip over to the next horizontal tab position.
    \ ' Causes a single quote mark to be printed.
    \ " Causes a double quote mark to be printed.
    \ \ Causes a backslash character to be printed.

    Starting out with Python
    In [5]:
    #New Line
    
    print("Line 1","\nLine 2")
    
    Line 1 
    Line 2
    
    In [6]:
    #Tab
    
    print("Don't\tPanic")
    
    Don't	Panic
    
    In [7]:
    #Single Quote
    
    print('Don\'t Panic')
    
    Don't Panic
    
    In [8]:
    #Double Quote
    
    print("\"Don't Panic\"")
    
    "Don't Panic"
    
    In [9]:
    #Backslash
    
    print("\\M/ I WANNA ROCK! \\M/")
    
    \M/ I WANNA ROCK! \M/
    

    Suppose you want to print an amount in dollars to the screen. The acceptable format for this would be to place a dollar sign ($) in front of your number, and then format the amount to two decimal places. Let's experiment and see what happens.

    In [10]:
    amount = 100.756
    
    print("$", amount)
    
    $ 100.756
    

    As you can see, we need to fix two problems with the output. 1, we need to remove the default space between the dollar sign and the number. 2, we need to format the number to two decimal places. First, lets look at two solutions, the seperator, sep="" and end, end="".

    In [11]:
    #Seperator
    
    amount = 100.756
    
    print("$", amount, sep="")
    
    $100.756
    
    In [12]:
    #End
    
    amount = 100.756
    
    print("$", end="")
    print(amount)
    
    $100.756
    

    Now we need to fix the decimal place in our example. Python provides a format() function to solve this problem.

    In [13]:
    #Format
    
    amount = 100.756
    
    print("$",format(amount,"0.2f"),sep="")
    
    $100.76
    

    As you can see above, Python formatted our float to two decimal places. This is because in our format() function, we specified the "format" to be "0.2f". Python also provides many more format functions, but most use cases will requre "0.2f".

    Character Output Format
    d, i Integer.
    u Unsigned Integer.
    f Floating point as m.ddddd.
    e Floating point as m.ddddde+/-xx.
    E Floating point as m.dddddE+/-xx.
    g Use %e for exponents less than -4 or greater than +5, otherwise use %f.
    c Single character.
    s String, or any Python data object that can be converted to a string by using the str function.
    % Insert a literal % character

    Problem Solving With Algorithms and Data Structures using Python

    Additional formatting options...

    Modifier Example Description
    number %20d Put the value in a field width of 20.
    - %-20d Put the value in a field 20 characters wide, left-justified.
    + %+20d Put the value in a field 20 characters wide, right-justified.
    0 %020d Put the value in a field 20 characters wide, fill in with leading zeros.
    . %20.2f Put the value in a field 20 characters wide with two characters to the right of the decimal point.
    (name) %(name)d Get the value from the supplied dictionary using name as the key.

    Problem Solving With Algorithms and Data Structures using Python