0

I am trying to get python 2.7 to store a single line of input that contains both a string and three float numbers so that I can perform some averages, etc.

ex. input: Tom 25 30 20

I tried:

name, score1, score2, score3 = raw_input().split()
score1, score2, score3 = [float(score1),float(score2),float(score3)]

but it throws an "invalid literal" error due to the string. Additionally, my code feels bulky, would there be a simpler way to go about this?

Thank you for any help!

1
  • 3
    Your code functions fine exactly as written, it does not throw any error.
    – kindall
    Commented Apr 6, 2016 at 16:52

2 Answers 2

2

You could refactor this a little, but what you have works and isn't that bulky or bad.

>>> user_input = raw_input('Enter your name and three numbers: ').strip().split()
Enter your name and three numbers: Tom 25 30 20
>>> name = user_input[0]
>>> scores = map(float, user_input[1:])
>>> name
'Tom'
>>> scores
[25.0, 30.0, 20.0]

Doing it this way means using a list (with subscripts like scores[0], scores[1]) instead of variables with names like n1, n2 (which always suggests to me you should be using a list).

Using map with float means you don't have to write float(var) three times.

You might also consider strip() on your user input. It's usually a good idea, especially since you're implicitly splitting on whitespace.

3
  • Also a comment on the invalid literal error. You can check whether your string for some reason contains any non-printing characters and strip them out before converting them to floating: print repr(user_input)
    – fips
    Commented Apr 6, 2016 at 17:02
  • Yeah that is something different and we need more info from OP. Nothing posted in the question should cause that, AFAIK. Commented Apr 6, 2016 at 17:06
  • 1
    Thank you all for the added help. I was entering a string where it expected int before this, I just didn't catch it. Python is my first endeavor into programming, only been at it for a few months now!
    – cslewis
    Commented Apr 8, 2016 at 16:01
0

You could solve your problem like this:

input = raw_input("Give me the input [name number number number]: ").split(" ")
name = input[0]
floats = map(float, input[1:])
print "I'm your name ", name
print "I'm your floats ", floats
print "I'm a sample average ", sum(floats)/len(floats)

You can get any float with:

floats[i]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.