git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Beginner] Spliting input


Hi,

On 25/06/2020 12:50, Bischoop wrote:
> I try to split input numbers, for example: 12 so I cant add them, I
> tried separated split(' ') but it's not working.
> Any ideas how to do this?
> 
> *
> numb1,numb2=input("enter 1st and 2nd no ").split()
> Avg=(int(numb1) + int(numb2)) / 2
> print(Avg)


So, this is an opportunity to do (and learn) some debugging!

One problem is that the first line does two things at once -- it reads 
the input and tries to split it into numb1 and numb2. Similarly for the 
"average" line.

You could instead try:

input_string = input("enter 1st and 2nd no ")
print(input_string)
numb1_as_string, numb2_as_string = input_string.split()
print(numb1_as_string, numb2_as_string)
numb1 = int(numb1)
numb2 = int(numb2)
print(numb1, numb2)
avg = (numb1 + numb2) / 2
print(avg)

Now, when if fails on input_string.split() (which I think is what 
happens) you can then be sure that you know what the input is. Let's say 
it's "17,3". Since you know that, you can experiment:

"17, 3".split() -> "17,", "3"  (note extra space)
"17 3".split() -> "17" "3" (aha, getting somewhere)
... and same results for both of these with split(' '), which should 
indicate that it's splitting on the space, and you didn't supply a space.

So now maybe try "17,3".split(',') -> "17", "3" (bingo!)

Bonus question: what happens with "17, 3".split(',')?





> *
> 
> --
> Thanks
>