Fun with Python: an Input Game

I know, I know. It’s not Mathematica, but please bear with me.

Python vs. Mathematica

For starters, it wouldn’t be fair for me to compare them for several reasons:

  1. I have years of experience with Mathematica vs. the few weeks I’ve been working with Python.
  2. The two languages were created for very different purposes.

I’ll try anyway, if only for fun.

It’s interesting to see how different it is from Mathematica. For example, whitespace characters (i.e. tabs) actually have a function. Unlike Mathematica, I can’t haphazardly put enters wherever I want, nor is it automatic! I also need to keep my code well-organized because it takes so many more lines to write what could be one function in Mathematica, and Canopy (my Python interpreter) lacks the organization and aesthetic beauty of notebooks.

pythoninputs1.png
Compare and contrast.

At the same time, Python seems to be much faster than Mathematica at running code, even though both are higher level languages; they probably wouldn’t compare with something like C in terms of speed. And although Mathematica is more intuitive with pulling off calculations and visualizing data, Python has much greater flexibility and readability for other kinds of tasks. There probably many more things Python can do that I’m not aware of. Otherwise, why would it be so popular?

Defining Essential Functions

Many of Python’s more useful functions come in modules. We should all thank the generous individuals who have created these functions for us. We will use the sys module for the function sys.exit().

import sys

This program relies on counting the number of characters in each input and determining whether they are odd or even and, in the case of the user’s name, whether it is prime. We could use len() by itself, but the problem is that it does not subtract spaces. We can define a simple function named character() just in case someone uses their full name.

def character(word):
    return len(word) - word.count(' ')

The next step is to define a function that can determine whether a number is prime. Technically, we could use an existing library of prime numbers, which would be faster. Instead of importing a library, how about we make something that can check if a number is prime on the go? Let’s make a series of tests:

  1. Is the number (we’ll call it “n”) less than 2? If so, it is not prime. This automatically excludes 0 and 1. Negative numbers cannot be prime, either, but that does not matter because we cannot have a string of negative length.
  2. If n is greater than 2, is it divisible every number between 2 and itself? A prime number is defined as something that can only be divided by 1 and itself. We’ll use a for loop to test every number. Remember that range() does not include the second parameter/final number.
  3. If n passes the above tests, return True. Otherwise, return False.
def primeQ(n):
    if n < 2:
        return False
    else:
        for i in range(2,n):
            if n % i == 0:
               return False
        return True
Creating the Story

Now that everything is in place, we can begin making the actual program. Start by taking the user’s name, birth month, and favorite color. Use raw_input() to turn the input into a string; using input() will try to run the input as a function. For example, entering “Ellen” as the name will store a string for raw_input() but will cause an error for input() if there is no variable called “Ellen.” Use the character() function we defined earlier to store the number of letters in each input as a variable.

name = raw_input('Enter your name: ')
nameLetters = character(name)
month = raw_input('Enter your birth month: ')
monthLetters = character(month)
color = raw_input('Enter your favorite color: ')
colorLetters = character(color)

Then, determine if the number of characters in “name” is prime, odd, or even.Because we’ll need this information later, we’ll create a variable to store a value that shows what kind of number it is.

if primeQ(nameLetters) == True:
    nameValue = 1
elif nameLetters % 2 == 0:
    nameValue = 2
else:
    nameValue = 3

Before we create the story, we’ll have to make sure the user entered the right information.

  1. Ask the user if the information they entered is correct in a way that is readable with rawinput(). Because the user could answer “yes” or “no” in many different ways, ask them to enter “Y” or “N.”
  2. If the answer is “Y” for “yes,” continue to the story.
  3. If the answer is “N” for “no,” end the program. We could use quit() or exit(), but it is better to explicitly import the sys module and use sys.exit(), which functions pretty much the same way. Using quit() or exit() relies on the site module, which might not always be there, unlike sys.
answer = raw_input('This is what you entered:\n'
+ 'name: ' + name + '\nmonth: ' + month + '\ncolor: ' + color
+ '\nIs this correct? Enter Y or N.\n')

if answer == 'Y':
    print('Beginning...\n')
else:
    print('Sorry. Please try again.')
    sys.exit()

The rest of the code is a bunch of if statements that check whether monthLetters() and colorLetters are odd or even. For example, the following code checks whether the remainder of colorLetters and 2 is zero (if it’s even). If so, it prints a certain line of text that incorporates the user’s name. A different line of text is produced if it is odd.

if colorLetters % 2 == 0:
    print(name + ' is removed from school for their concerningly erratic behavior. '
    + name + ' burns down the psychiatric ward and escapes to Europe with a fake identity.')
else:
    print(name + "'s teachers say that they are gifted. " + name + ' becomes a young oil tycoon'
    + ' and becomes the youngest billionaire in the world. Climate change worsens.')

Finally, we can test the code. Here’s a run with my information (the bolded words are my inputs).


Enter your name: Ellen

Enter your birth month: February

Enter your favorite color: purple

This is what you entered:
name: Ellen
month: February
color: purple
Is this correct? Enter Y or N.
Y
Beginning…

Ellen is synthetically created on a cloudy February day.
Ellen is actually a robot. Ellen is mistakenly adopted by their current family.
Ellen is removed from school for their concerningly erratic behavior. Ellen burns down the psychiatric ward and escapes to Europe with a fake identity.
Ellen gets married and has 6 children.
Ellen pokes a button and accidentally kills 6.5 billion people. The world is in a crisis.
Ellen falls in a pool and dies at the age of 72.
Ellen will be greatly missed. The end.


As usual, everything is here, on Pastebin. There’s a collapsed preformatted block of text at the bottom. Look! Now that I’m using Python, I can take full advantage of the preformatted function on WordPress!

"""
This project outputs a story based on the character length of their inputs.
Visit my WordPress at ellenleescience.wordpress.com
"""
import sys
def character(word):
    return len(word) - word.count(' ')
    # subtract the number of empty spaces just in case someone puts their full name
def primeQ(n):
    # we need to find whether the number of letters if prime for later
    # 1 and 0 are not prime, and negatives are impossible
    if n < 2:
        return False
    else:
        # divide n by every number from 2 to n, since a prime can only be divided by 1 itself
        for i in range(2,n):
            # if the remainder is zero for any number, it is not a prime number
            if n % i == 0:
               return False
        return True
        # if n passes every test, it is prime

name = raw_input('Enter your name: ')
nameLetters = character(name)
month = raw_input('Enter your birth month: ')
monthLetters = character(month)
color = raw_input('Enter your favorite color: ')
colorLetters = character(color)

# now we determine if nameLetters is prime for later
if primeQ(nameLetters) == True:
    nameValue = 1
elif nameLetters % 2 == 0:
    nameValue = 2
else:
    nameValue = 3

answer = raw_input('This is what you entered:\n'
+ 'name: ' + name + '\nmonth: ' + month + '\ncolor: ' + color
+ '\nIs this correct? Enter Y or N.\n')

if answer == 'Y':
    print('Beginning...\n')
else:
    print('Sorry. Please try again.')
    sys.exit()

# the rest of the story is determined by nameValue and whether each Letters value is odd or even
if nameValue == 1:
    print(name + ' is synthetically created on a cloudy ' + month + ' day.')
    print(name + ' is actually a robot. ' + name + ' is mistakenly adopted by their current family.')
elif nameValue == 2:
    print(name + ' is born on a stormy ' + month + ' night.')
    print(name + ' is abandoned by their family. They are raised by stray dogs.')
else:
    print(name + ' is born on a sunny ' + month + ' day.')
    print(name + ' lives with a happy family until their parents die in an accident in the lab.')

if colorLetters % 2 == 0:
    print(name + ' is removed from school for their concerningly erratic behavior. '
    + name + ' burns down the psychiatric ward and escapes to Europe with a fake identity.')
else:
    print(name + "'s teachers say that they are gifted. " + name + ' becomes a young oil tycoon'
    + ' and becomes the youngest billionaire in the world. Climate change worsens.')

print(name + ' gets married and has ' + str(colorLetters) + ' children.')
if monthLetters % 2 == 0:
    print(name + ' pokes a button and accidentally kills 6.5 billion people. The world is in a crisis.')
else:
    print(name + ' finds a cure to rabies, but their research is stolen. They never recieve credit.')

if nameValue != 1:
    print(name + ' lives to the ripe age of ' + str(monthLetters*9) + '.')
    print("Cause of death:")
    if colorLetters % 2 == 0:
        print('tripped on a banana peel')
    else:
        print('hit by a meteor')
else:
    print(name + ' falls in a pool and dies at the age of ' + str(monthLetters*9) + '.')

print(name + ' will be greatly missed. The end.')

P.S.: How does the Python logo work?

Advertisements

One thought on “Fun with Python: an Input Game

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s