Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Last active December 10, 2015 22:59
Show Gist options
  • Save nhunzaker/4506352 to your computer and use it in GitHub Desktop.
Save nhunzaker/4506352 to your computer and use it in GitHub Desktop.
The first question I'm making for a list of python exercises!

Python Question 1

Problem: I need a program that can add stuff together.

First, add integers together:

$ python add.py 1 2 3 4 5
15

Once you have that, then allow it to add strings too:

$ python add.py Hello World I hear it\'s beautiful out there
Hello World I hear it's beautiful out there

Extra Credit: Add numbers until it finds a non-numeric value, then treat it like a string:

$ python add.py 1 2 3 Kittens
6 Kittens

Gentle nudges in the correct direction:

  • Google "pass arguments into python script" -- what do you find?
  • What are some ways to see if a string is numeric?
  • How do you convert something to a number? What about to a string?
  • What can you do to see if something (anything) is a string or number?
###
# Python Question 1: Add
# Essentially reduces a list of arguments into a single value
# (This is hardly perfect)
###
import sys
# Remember the first sys.argv value is the name of the script
values = sys.argv[1:]
# Is the first value a digit? If so start with 0. Otherwise start with
# a blank string
total = 0
for value in values:
# Does the value match a number?
# isdigit has a couple of sister methods that are really neat.
# See: http://docs.python.org/2/library/stdtypes.html#str.isdigit
if value.isdigit():
# Yes : convert the value into a number and add it
total += int(value)
else:
# No : convert to the total into a string and add the value
total = '' if total == 0 else str(total) + " "
total += value
# Done, remove white space
print total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment