Skip to content Skip to sidebar Skip to footer

Python 2.7 - Invalid Literal Errors

Python Version - 2.7.11 I am following Zed Shaw's Learn Python the Hard Way and am currently at Exercise 21 I am trying to modify the code so that the script prompts the user to en

Solution 1:

You need to split your input into two numbers before converting these to float; use str.split():

whileTrue:
    ages = raw_input('Enter 2 numbers')
    try:
        age1, age2 = [float(age) for age in ages.split(',')]
        breakexcept ValueError:
        print("Sorry, you did not enter two numbers, try again")

add(age1, age2)

I've added a while True loop to keep asking for correct input whenever there is an error; the ValueError exception is raised both if float() fails to convert a value or if there are not enough or too many inputs given. If conversion succeeds and there are exactly two values to assign to age1 and age2, no exception is raised and the break statement exits the endless loop. See Asking the user for input until they give a valid response for more details on how this works.

Solution 2:

I think you might have meant to split the values?

nums = map(float, raw_input('Enter 2 numbers').split(','))
age = add(*nums) 

map will apply a function, in this case float() across a collection of items, which is a list of strings as a result of split().

*nums is some variant of tuple-unpacking. It takes a collection of items, and "expands" them into the arguments needed for the function.

Alternatively, this also works, but it is simply more to type.

age = add(nums[0], nums[1]) 

Solution 3:

try this.

age1,age2=(float(x) for x in raw_input('Age_1, Age_2: ').split(','))
print add(age1,age2)

.split(n) will create a list from a string by splitting the string at each index of n. Code is the same as:

n = raw_input('Age_1, Age_2')
n = n.split(',')
age1 = float(n[0])
age2 = float(n[1])
print add(age1, age2)

Solution 4:

If you would like the user to input multiple values you will need to change your code up. As raw_input() can only unpack one value.

for example, you cannot input a tuple and have raw_input() unpack it

>>> a, b = raw_input('enter two numbers: ')
>>> enter two numbers: 69, 420
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
ValueError: too many valuesto unpack

instead maybe try this:

>>>variables = []>>>for i in range(len(<How many inputs does your function need>)):>>>   variables.append(float('enter variable{}:'.format(i)))>>>>>>age = add(variable[0], variable[1]... variable[n])

or as others have noted try to parse your input with string manipulation:

'string'.split()

.split method is very handy. check out the python wikibooks for an overview and examples of string methods

https://en.wikibooks.org/wiki/Python_Programming/Strings

Post a Comment for "Python 2.7 - Invalid Literal Errors"