Python Forum
New to python, starting from scratch
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New to python, starting from scratch
#1
Big Grin 
questions = ["What is your name?", "What is your favorite color?", "What is your quest?"]
n = 0
while True:
    print("Type q to quit")
    answer = input(questions[n])
    if answer == "q":
        break
    n += 1
    if n > 2:
        n = 0
abouv is a some code I don't get. If I remove all the questions but one, this code give the following error:

Error:
line 5, in <module> answer = input(questions[n]) IndexError: list index out of range
I cannot find what is the matter Wall
Yoriz write Apr-16-2021, 01:19 PM:
Please post all code, output and errors (in their 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.
Reply
#2
The code is made to work with a specific amount of items in the list questions
The error happens because the list only has an item at index 0.
When it goes through the while True loop the first time n has the value 0.
questions[n] returns the first item of the list.
it continues to n += 1, n now has the value of 1.
It goes through the while True loop again and tries to call questions[n] to get the next item at index 1.
Because there isn't another item it gives the IndexError: list index out of range error.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Kera Getting errors when following code example Image classification from scratch hobbyist 3 2,160 Apr-13-2021, 01:26 PM
Last Post: amirian
  starting python from windows command prompt MaartenRo 4 1,089 Sep-04-2020, 12:25 PM
Last Post: MaartenRo
  Restarting code from scratch palladium 1 804 Feb-29-2020, 04:46 PM
Last Post: ibreeden
  Issue starting Python on VSC (Nooby) Buggy 1 1,015 Mar-14-2019, 09:44 PM
Last Post: snippsat
  python 'SMTP debugging server' not starting local error pcsailor 1 1,732 Nov-26-2018, 10:13 PM
Last Post: micseydel
  Starting to learn python on a Mac asifhoss 8 5,909 Jan-03-2018, 08:29 PM
Last Post: karaokelove

Forum Jump:

User Panel Messages

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