简体   繁体   中英

How do I resolve a substring not found error?

I'm currently following Replit's 100 days of code tutorial. I am on day 40 and got tasked with making a dictionary to store the user's information, like their name.

My code:

info = {"name":"", "date of birth": "", "telephone number": "", "email": "", "address": ""}
questions = ["What is your name? ", "When were you born? ", "What is your telephone number? ", "What is your email? ", "What is your address? (Don't say it if you don't want to) "]
items = ["name", "date of birth", "telephone number", "email", "address"]

for i in questions:
  item = input(i)
  info[item.index(i)] = item #this was the line that caused the error. 

(I took an approach of using loops) But I run it and put in my answer. It then responds with a substring not found. I'd never heard of this before and didn't know what to do.

The error, word for word:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    info[item.index(i)] = item
ValueError: substring not found

I'm a little unsure about the .index() command, is it that?

You are using the wrong variable. item is your answer, items is the list of keywords. Also the human readable question will not be in the items list. This should work:

for i, question in enumerate(questions):
    item = input(question)
    info[items[i]] = item

As a side note, this bug would have been easier to spot if you named your variables more sensibly.

You are using wrong variable if you are confused of using for-loop your can use while-loop instead

    # initilizing index as zero since index starts from zero
    index=0
    while True:
      item=input(questions[index])
      items[index]=item
      index+=1
      # if index is equal to length of the list then this loop should end
      if index==len(questions):
          break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM