knowledge-kitchen / course-notes

Strings - Input & Output (in Python)

Receiving input from the user

Many programs receive input from the person using the program. This “user input” can come from any input device that a user has access to, such as computer’s keyboard, microphone, camera, oystick, trackpad, etc.

Input can also come from external data sources like databases, data published to the Internet, and really anywhere.

But for simple programs, the input usually comes from the keyboard… this is referred to as the “standard input”.

Python examples

The input() function is used to solicit user input. The user responds by typing on their keyboard, pressing the Enter/Return key when done.

A simple input/output program:

name = input("What's your name? ") # solicit user input, save it in a variable
message = "Welcome, " + name + " how are you today?" # put together a decent message to print
print(message) # print the message

The input() function always returns a string, meaning that even if the user enters a number in response to a prompt, the number is still considered a string data type, not a numeric data type.

Simple input/output program dealing with numbers… note the need to convert data types so numbers are properly computed as numbers and text is recognized as text:

quantity = input("How many Dentalium shells do you have?") # solicit user input
price_per_unit = 7.49 # in dollars
wealth = float(quantity) * price_per_unit # note the conversion of the quantity string to a floating point number
print("You have of $" + str(wealth) + " worth of wealth!") # note the conversion of the wealth floating point number to a string

Another one, showing more use of data type conversion to convert human years into “dog years”:

age = input("Enter your age: ") # solicit user input, save it in a variable... it's a string still
age_as_int = int(age) # convert the age to an integer and save this number in a variable
dog_years = age_as_int * 7 # conver the human age to dog years... save the resultant integer in a variable
dog_years_as_str = str(dog_years) # convert the dog years integer to a string so we can combine it with other text later
message = "Your age in dog years is " + dog_years_as_str # make a nice message to print to the user
print(message) # print it!

The same, but organized nicely into a function. We also add some logic to check Python’s built-in name variable to help us only run the code in the function if this code file is being run directly, not when it’s being imported into another code file as a “module”.

"""
This program converts human years into "dog years".
It is designed to be somewhat modular and reusable.
"""

def dog_years():
    """
    This is a function that asks the user to enter their age.
    The code then outputs that age in "dog years".
    """
    age = input("Enter your age: ") # solicit user input, save it in a variable... it's a string still
    age_as_int = int(age) # convert the age to an integer and save this number in a variable
    dog_years = age_as_int * 7 # conver the human age to dog years... save the resultant integer in a variable
    dog_years_as_str = str(dog_years) # convert the dog years integer to a string so we can combine it with other text later
    message = "Your age in dog years is " + dog_years_as_str # make a nice message to print to the user
    print(message) # print it!

# if running this file directly, run the function, otherwise don't.
if __name__ == "__main__":
    # run the code in the function named dog_years
    dog_years()

Sending output to the user

Many programs send output to the person using the program. This output can be displayed by any output device that the user has access to, such as the computer’s display or speakers. Output sent to the computer's display can usually either be displayed as plain text, or as graphics.

For simple programs, the output is usually plain text output to a console, referred to as the “standard output”.

Python examples

The print() function is the easiest way to provide some kind of textual output for the user to see it. This prints the outputted text to the command line interface (i.e. the Terminal).

The print() function has some behaviors that are important to understand:

print("hello") # by default prints "hello\n"... note the newline (line break) character attached automatically at the end.
print("hello", end="\n") # same as the default... just making it explicit
print("hello", end="") # you can override the newline character default and print nothing at the end
print("hello", end=" world!\n") # you can override the newline character and print whatever you want at the end
print("this", end="-") # override default ending
print("that", end="-") # override default ending
print("the other!") # defaults to end="\n"
# outputs "this-that-the other!\n" on one line

A much easier way to do the same thing as the last line above:

print("this-that-the other!")

print() can handle multiple arguments (multiple values separated by commas “,”):

print("hello world!") # outputs "hello world!\n"
print("hello", "world!") # by default prints "hello world!\n".. note the space placed between the two arguments
print("hello", "world!", sep=" ") # same as the default... just making it explicit
print("hello", "world!", sep="-") # overrides the default separator, uses "-" instead, and prints "hello-world!\n".
print("hello", "world!", sep=" fantastic ") # outputs "hello fantastic world!\m"
print("this", "this", "the other" sep="-", end="!\n")` #outputs "this-that-the other!\n"

A much easier way to do the same thing as the last line above:

print("this-that-the other!")

Putting it together

Most programs take in some form of input and produce some sort of output.

Here’s an example that asks the user for their name and outputs whether it’s a “good” name or not (based on its heavily-biased list of good names):

# ask the user for their name... store the result in a variable.
name = input("What's your name? ")
name_as_lowercase = name.lower()  # convert to lowercase

# a lis of names we accept as "good"
good_names = ["bob", "sheila", "jane", "joe"]  # list data type

# derive a True or a False, depending up on whether the name is in the list
# is the user's name in the list... True or False
is_good = name_as_lowercase in good_names

# decision-making... .based on the True/False result
if is_good == True:
    # if the name is good, print this
    print("That's a great name!")
else:
    # if the name is not good, print that
    print("That's not a great name!")

Here is that same program in a more modular and reusable style, using docstrings explaining the purpose of the code, matching in a case-insensitive manner, and placing code into functions with protective logic at the bottom to only run the code in the function in the situation where the file is being run directly, not when it’s imported into another file:

"""
A very simple example of how a Boolean value might used to determine what to output.
It is designed to be somewhat modular and reusable.
"""

# define a function... a block of modular reusable code to use later
def determine_good_name():
    """
    Asks the user for their name and tells them it's a bad name...
    unlesss they're lucky and their name is in our list of good names.
    """

    # ask the user for their name... store the result in a variable.
    name = input("What's your name? ")
    name_as_lowercase = name.lower()  # convert to lowercase

    # a lis of names we accept as "good"
    good_names = ["bob", "sheila", "jane", "joe"]  # list data type

    # derive a True or a False, depending up on whether the name is in the list
    # is the user's name in the list... True or False
    is_good = name_as_lowercase in good_names

    # decision-making... .based on the True/False result
    if is_good == True:
        # if the name is good, print this
        print("That's a great name!")
    else:
        # if the name is not good, print that
        print("That's not a great name!")


# run the code if this file is being run directly
if __name__ == "__main__":
    # if so, run the code function
    determine_good_name()