Python Forum
Variable for the value element in the index function??
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable for the value element in the index function??
#3
Your message is suspect. When I run this code:
Output:
from string import ascii_lowercase alpha_char = input("Enter a letter of the English alphabet: ") index_num = ascii_lowercase.index(alpha_char) print(index_num)
If I enter something that is not a lower case ascii character, I get this message:
Error:
ValueError: substring not found
Not the same error message.

It would be nice if you provided proof of this:
Quote:I know that the input process worked, because I used a print statement right before the error line, and I got the user input correctly printed.
Your posted code contains no print commands. You should post the code you are running. The code you have posted runs correctly as far as I can tell.

This did not happen:
Quote:Somehow, trying to use a variable as the index element seems to have converted it to a space or a null character (I think).
There is an error in your code that you did not post. If you post the code that has this behavior, we can help you understand what is happening.

I would not use index for something like this. I would use a dictionary.
from string import ascii_lowercase

# Make dictionary mapping characters to their index
alphabet_list = {letter: index for index, letter in enumerate(ascii_lowercase)}

alpha_char = input("Enter a letter of the English alphabet: ")
index_num = alphabet_list.get(alpha_char, None)
print(index_num)
Reply


Messages In This Thread
RE: Variable for the value element in the index function?? - by deanhystad - Jan-20-2024, 03:47 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 763 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,671 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 1,197 Aug-07-2023, 05:58 PM
Last Post: Karp
  Index Function not recognized in Python 3 Peter_B_23 1 1,512 Jan-08-2023, 04:52 AM
Last Post: deanhystad
  Retrieve variable from function labgoggles 2 1,153 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  Cant transfer a variable onto another function KEIKAS 5 2,063 Feb-09-2022, 10:17 PM
Last Post: deanhystad
  myList.insert(index, element) question ChrisF 1 1,751 Aug-27-2021, 03:49 PM
Last Post: bowlofred
  How i can add elements to table index of element blazej2533 3 2,151 Dec-03-2020, 08:16 PM
Last Post: Larz60+
Question Matching variable to a list index Gilush 17 6,322 Nov-30-2020, 01:06 AM
Last Post: Larz60+
  How to get index of minimum element between 3 & 8 in list Mekala 2 2,662 Nov-10-2020, 12:56 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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