1

I want to be able to change a list of distances from miles to kms, where the list of miles is obtained in the below bit of code:

input_string = input("Enter a list of distances, separated by spaces").strip()

To change the list of inputs into a list of integers, I used:

distances = input_string.split()
print("This is what you entered: ")
for distance in distances:
     print(distance)

def str2int(word):
    """Converts the list of string of miles into a list of integers of miles"""
    integer = int(word)
    if int(word):
        return integer
    else:
        sys.exit("Please try again and enter a list of integers.")


def validate_all(distances):
    """
    Checks if all the inputs are integers. If not all are integers, sys.exit
    without converting any of the distances and ask to try again.
    """

    true_list = []

    for distance in distances:
        if str2int(distance):
            true_list.append(distance)

    if len(distances) == len(true_list):
        return True
    else:
        return False

print("And now, we are going to convert the first one to kilometers:")
miles = distances[0]

if validate_all:
    # now, the calculation and display
    kms = miles_int * KMPERMILE
    print("The first distance you entered, in kilometers:", kms)

    for i in range(1, len(distances), 1):
        miles_int = str2int(distances[i])
        kms = miles_int * KMPERMILE
        print("The next distance you entered in kilometres:", kms)

BUT, when I try to check if all elements of the list of strings are able to be changed into an integer (with validate_all(word)) and have something like

12 23 apples banana 5

as my input, the program crashes saying that there is a value error at

str2int(word)
-> if int(word):

instead of me getting the sys.exit

Can anyone debug this for me/get this right for me please?

1
  • 1
    Can you post the error stack trace, please? Commented Jan 8, 2014 at 4:05

4 Answers 4

2
>>> t = '12 23 apples banana 5'
>>> [int(x) for x in t.split() if x.isdecimal()]
[12, 23, 5]
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a try-except clause:

def str2int(word):
    """Converts the list of string of miles into a list of integers of miles"""
    try:
        integer = int(word)
        return integer
    except ValueError:
        print "here"
        sys.exit("Please try again and enter a list of integers.")

print(str2int("asd"))

Output:

here
Please try again and enter a list of integers.

Note:

You can read more about Handling Exceptions and the try-except clauses in the Python docs.

Comments

0

You tried doing if int(x): ..., but int is not a predicate. If x is a string which cannot be converted to an int, a ValueError is raised. If x='0' for example, if int(x): ... is evaluated to False, despite being an int-like value.

What you need is the following predicate:

def is_int_able(x):
  try:
     int(x)
     return True
  except ValueError:
     return False

With this, you can do:

[ int(x) for x in line.split() if is_int_able(x) ]

Comments

0

Your validate_all() could make use of all() and str.digit():

In [1]: all(e.isdigit() for e in ['12', '23', 'apples', 'banana', '5'])
Out[1]: False

In [2]: all(e.isdigit() for e in ['12', '23', '5'])
Out[2]: True

But perhaps a better way would be to do away with this validation and employ the if filtering in a list comprehension:

In [3]: distances = ['12', '23', 'apples', 'banana', '5']

In [4]: [int(km) * km_to_miles for km in distances if km.isdigit()]
Out[4]: [7.456454304, 14.291537416, 3.10685596]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.