Python Forum
what is missing in my while statement ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what is missing in my while statement ?
#1
Hello friends, I'm new here.
I am still a beginner but I am quite familiar with loops and while statement and have used it many times.

I'm trying a simple exercise but the result only shows when the number I type exists in the list, otherwise I get an error which I don't understand :


list = [1,3,4,6,7]
number = int(input("Pick a number : "))
i=0
while list[i] != number :
    if i < len(list) :
        i = i+1
    else :
        print("your numeber has not been found")
print(f"the position of your number is {i}")
Could you please help me understand which part of my while statement is not correct ?

Thank you Smile
Larz60+ write Nov-28-2021, 03:10 AM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.
Reply
#2
You can use the 'in' clause:
list = [1,3,4,6,7]

number = int(input("Pick a number : "))
if number in list:
    print(f"Number is in list at index: {list.index(number)}")
else:
    print("your numeber has not been found")
Reply
#3
Your program crashes because you use list[i] before testing if i is in range.
Reply
#4
Post the full traceback you get.
As a side note - don't use list as name.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020