0

This is the task: Using while loop, if statement and str() function; iterate through the list and if there is a 100, print it with its index number. i.e.: "There is a 100 at index no: 5"

If I code like this -

lst = [10, 99, 98, 85, 45, 59, 65, 66, 76, 12, 35, 13, 100, 80, 95]
i = 0
while i < len(lst):
    if lst[i] == 100:
        print("There is a 100 at index no:", str(i))
    i += 1

, then everything is fine but if I try using user inputted list instead of a set list the code is not working:

lst = input('Enter your nums:').split(',')
entered_data = list(lst)
i = 0
while i < len(entered_data):
    if entered_data[i] == 100:
        print("There is a 100 at index no:", str(i))
    i += 1

I don't understand why is that so. Please, help.

2 Answers 2

2

The input generates a string.

This string, you split it on coma, but it is still a list of strings.

Then you should cast the type of your entry.


entered_data = input('Enter your nums:')
lst = entered_data.split(",")
for indice, elt in enumerate(lst):
    try:
        if int(elt) == 100:
            print(f"There is a 100 at index no:{indice}")
    except ValueError:
        print(f"The entered value {elt} at indice {indice} is invalid. It must be an integer. It will be ignored.")


I replaced your while with a for that is a more pythonic way to achieve the same goal.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer, I got my mistake. I understand that for is better in this case, but according to task one should use while.
0

When you input elements, input function takes the input as string(str), not integers as you may be knowing.

a simple solution would be casting the element into an integer and all is done. So the code would be like

lst = input('Enter your nums:').split(',')
entered_data = list(lst)
i = 0
while i < len(entered_data):
    if int(entered_data[i]) == 100:
        print("There is a 100 at index no:", str(i))
    i += 1

Note that, the changed line is where you are comparing the element with integer 100. You can also print the 'entered_data', you will be able to see the single quotes around the single elements(I am using a jupyter notebook)

The code to show the list elements

lst = input('Enter your nums:').split(',')
entered_data = list(lst)
print(entered_data)
i = 0
while i < len(entered_data):
    if int(entered_data[i]) == 100:
        print("There is a 100 at index no:", str(i))
    i += 1

It's output is

Enter your nums:41,56,100,4
['41', '56', '100', '4'] 
There is a 100 at index no: 2

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.