'if num.count(num[4]) == 3: is this python systax wrong [closed]

python

num = input("Enter 8 dugits seperated by comma: ").split()
    if num.count(num[4]) == 3:
      print("true")
    else:
      print("false")

always gives me a error in the above code at line 2.Can anyone please tell me what is wrong?



Solution 1:[1]

Let's analyze your code a bit. First line

>>> num = input("Enter 8 dugits seperated by comma: ").split()
Enter 8 dugits seperated by comma: 1,2,3,4,5,6,7,8
>>> num
['1,2,3,4,5,6,7,8']

If you do as your guide says, it returns list with one element. That probably isn't something you want.

Could this be something better:

>>> num = input("Enter 8 dugits seperated by comma: ").split(",")
Enter 8 dugits seperated by comma: 1,2,3,4,5,6,7,8
>>> num
['1', '2', '3', '4', '5', '6', '7', '8']

Now rest of your code works.

And it prints true if a digit in index 4 ( which is 5 in my example) appears in list exactly three times.

so entry 1,2,3,4,5,5,5,8 would print true and 1,2,3,3,3,3,3,3 would print false.

In real world you should add lot of error control. What happens if user adds more or less than eight digist, what if there is whitespace between commas and so on. And remember that str.split() returns list of strings even if you have digits. So if you do some calculations you need to parse your digits to integers. Otherwise you'll have hard times. See the difference:

>>> '1'+'2'
'12'
>>> 1+2
3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1