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??
#1
Let's say that I have a list with all the letters of the English alphabet in it.

Is it possible to allow a user to input an alpha character,

then assign that character to a variable,

and then use that variable in the index function (or some other way) to find the index number of the corresponding letter in the list?

My failed attempt looked something like this:


alpha_char = input("Enter a letter of the English alphabet: ")
index_num = alphabet_list.index(alpha_char)


The error that I received was: ValueError: ' ' is not in the list

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. Somehow, trying to use a variable as the index element seems to have converted it to a space or a null character (I think). I searched the web for an answer, for a while, but everyone wanted to explain how to go the opposite direction (getting the index number as input from the user and then fiding the value that corresponds to it in the list).

Thanks for any help!
Reply
#2
This is 'long hand' and could be shorter.

alpha_upper = [chr(n) for n in range(65, 91)]  # A...Z
alpha_lower = [chr(n) for n in range(97, 123)]  # a...z

alpha_lst = alpha_lower + alpha_upper
alpha_lst.sort()
alpha_input = ""
while alpha_input not in alpha_lst:
    alpha_input = input("Enter a letter of the English alphabet: ")

index_num = alpha_lst.index(alpha_input)
char = alpha_lst[index_num]
print(index_num, char)
I think it's what you're trying to do.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#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
#4
Hey, thank you both!

The second message made me take a closer look at the output, and then try a different input that showed the source of my issue was not what I thought at first. Earlier in the code, I tried to use a replace(), to remove spaces from a text string, and since there were no errors from that line, I had thought that the process had worked, but it must not have. A closer look at the output revealed that although I thought the print had worked, it only worked until it hit one of the spaces in the string (that were not removed). The early characters did print out, as I had noticed, but the error code wasn't because the index command didn't work with the variable, but because it had actually been fed the first space in the text string, and therefore failed to find that character in the list of alpha characters. I'll need to revisit the attempt to remove spaces from the string. The problem (which didn't generate an error immediately) was from this line:

lower_msg.replace(" ", "")

although it didn't reproduce correctly here with copy/paste,

in the compiler it actually looks like:

lower_msg.replace(__old:" ", __new"")

Since it added the other part itself, and it didn't generate any codes, I incorrectly assumed, it must have worked. It probably did exactly what I had asked, but not what I thought I had asked it to do. A good mistake to experience, just because there were no errors, doesn't mean that it did exactly what you thought it did.
Reply
#5
replace is somewhat misleading. str objects are immutable, you cannot change the characters or length of a str. Replace creates a new str object, so when you use replace(), you need to assign the return value to a variable.

you are being stingy about posting code. Your posts are confusing because you make incorrect assumptions about code you don't post.
Reply
#6
Python needs to be idiot-proof. Make sure your users, mostly you probably, can't enter something wrong and proceed, if you can.

import string

alphabet = string.ascii_lowercase
letter = "X"
while not letter in alphabet:
    letter = input('Enter a small letter of the alphabet ... ')
Reply
#7
Dean,

I was a little shy to show much code, since I'm guessing that most of the folks here make a pretty good living by writing and editing code for years now.

In contrast to them, I just started writing Python for the first time last week, and I'm far from making my first dollar with it since my skills are very rudimentary at best.

Also, I didn't want to get confused by comments about parts of my code that might be clumsy or weak, but were working, when I was trying to focus on solving the only compliler problem I had. I wasn't even sure if my question might not be too dumb to warrant an answer. I should have just waded on in and been more trusting I guess.

Last week I watched the four hour introduction to Python, from Giraffe Academy, on YouTube, and now I'm working on trying to apply those concepts in my own little projects, combining the various ideas. I don't really expect to rise to the level of being a career coder, since I'm not that young anymore, but I was hoping to get enough Python to perhaps get through the Grow with Google program on cyber security. Since Python and SQL are part of that certification program, I thought I had better just see if Python was even possible for me to learn quickly.

About 30 years ago, I did some very light programming in Basic and Pascal, and later I took a semester college class in Cobol and also one in C++, so I'm not completely ignorant of the coding world (just mostly ignorant). Since that time though, I haven't coded a line in any language, and I essentially only used computers for office tasks, or web browsing. I guessed that I would know pretty quick if learning Python was feasible, or ridiculous, at this stage of life. As long as the cyber security waters don't run too deep into coding, I'm thinking I might be able to make it.

My little problem program is working now, and I'll post it, so you can see what I'm learning. The translate function and some of the import stuff I barely understand, but I wrote every character of it myself, with a little consulting from internet sources where I got stuck. This is my longest program in Python so far, and I've done about 17 of them now in the past two weeks. Thanks for the tips!
Reply
#8
'''
This program is designed to make a secret message encoder for my kids to try out,
but also, to help me learn Python, and to try out the "for loop" function in combination
with other Python commands. As I write this code, I have only been using Python
for two weeks, and I have written less than 20 Python files so far. 01/20/2023
'''

user_message = input("Enter a secret message to be put in cipher: ")
alphabet_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z"]
numbers_to_text = {
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
"0": "zero",
}
secret_msg = ""
test = False
while test == False:
secret_number = input("Enter a secret whole number between 1 and 26: ")
if secret_number.isnumeric():
secret_number = int(secret_number)
if secret_number > 0 and secret_number < 27:
test = True
else:
print("Not a whole number from 1-26")
else:
print("Not a numeric value")
import string
# The next two lines convert any numbers in the sentence to their text equivalents
num_table = str.maketrans(numbers_to_text)
num_to_text = user_message.translate(num_table)
# The next line makes everything lower case
lower_msg = num_to_text.lower()
# The next 2 lines remove any punctuation
translator = str.maketrans("", "", string.punctuation)
no_punct = lower_msg.translate(translator)
# The next line removes all the original word spacing
clr_spaces = no_punct.replace(" ", "")
lower_msg = clr_spaces
string_length = len(lower_msg)
count = 0
# This is my very first use of a for loop function
for letter in lower_msg:
alpha_char = lower_msg[count]
# print(alpha_char) This line was just added as a debugging test
count += 1
index_num = alphabet_list.index(alpha_char)
new_index = index_num - secret_number
new_char = alphabet_list[new_index]
secret_msg = secret_msg + new_char
# The next two lines add a space every five characters to hide original word spacing
import re
chunked = (" ").join(re.findall(".{1,5}", secret_msg))
secret_msg = chunked
print("\nYour secret message now reads: " + secret_msg)
Reply
#9
there was probably a better way to do that, since all the indentation formatting was lost with copy/paste. One thing I did have to catch on to this time, since I am using PyCharm, is that sometimes the program sticks suggestions right into the code and you have to right click them and turn it off, or it can cause a failure.
Reply


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