1

Hi I apologize if this looks like homework, but I have been trying and failing to make this work, and I would really appreciate some expert help. I am trying to self-teach myself python.

I'm trying to solve problems in CodinGame and the very first one expects you to count the times input strings are passed to the program. The input string comes in two parts (eg. "Sina dumb"). I tried to use this:

count = int(sys.stdin.readline())
count = int(input())
count = int(raw_input()) #python2

But the program fails with:

    ValueError: invalid literal for int() with base 10: 'Sina dumb\n'

depending on if I leave the newline in or not. Please what am I doing wrong, and how can I make it better?

0

3 Answers 3

3

In python2.x or python 3.x

sys.stdin.readline() and input gives type str. So int("string") will produce error if string contains chars.

I think you need this(assuming)

import sys
input_var = input() # or raw_input() for python 2.x

# entering Sina dumb 
>>>print(len(input_var.split()))
2

Update

If you want to count how much input you enter.Try this

import sys
from itertools import count
c = count(1)
while True:
    input_var = input()
    print ("you entered " + str(next(c)) + " inputs")
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! but I think I didnt express myself properly; I am not counting the strings in the input value, but the number of times the program gets an input. So each input() should count as 1.
@Sina But you’re still doing int(some_input), so you are trying to cast whatever the user entered as a number—which will fail. Instead, you should just increment the count, like count += 1.
0

On one hand, in this case, python say you that you tried ton convert the String 'Sina dumb\n into integer that is not valid, and this is true. This probably triggered at the second line, int(input)

On the other hand, to solve your problem,one simple approach as each row you pass as input contains the end of line character \n you can for example get the input content, and split it at \n characters and count the size of the resulting list.

Comments

-1

input() in python 3.x and raw_input()in python 2.x give a string. If a string contains anything but numbers it will give a ValueError.

you could try regular expression:

import re
line = input()
count = len(re.findall(r'\w+', line))
print (count)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.