Gramms Gramms - 6 months ago 10
Python Question

Searching for an equal string?

I am not sure how to word the question title.

a = "Alpha";
b = "Bravo";
c = "Charlie";

fn = input("What is your first name: ")

for fletter in fn.split():
fl = fletter[0]


The code above gets the first letter entered. The goal is to then get the first letter to possible check in a while loop to see if the value of fl = one of the starting strings. Is that possible to do? Tips on where to begin?

Answer

Solution 1 [Using a dictionary]

Also makes things much simpler.

In this case, instead of defining separate variables for each string, you store them in a dictionary. So for example, instead of this:

a = "Alpha"
b = "Bravo"
c = "Charlie"

You would have this:

letterwords = {"a":"Alpha", "b":"Bravo", "c":"Charlie"}

This works very similarly to a list, however instead of indexing the dictionary you would reference to separate objects inside a dictionary according to its key. So if the dictionary letterwords is defined as above, you would reference to the string Alpha by calling letterwords["a"]. Therefore, in this case, the code would look something like this:

letterwords = {"a":"Alpha", "b":"Bravo", "c":"Charlie"}
fn = input("Please enter your first name: ")
try:
    letterwords[fn[0]]
except KeyError:
    print("There is no matching variable with that letter in the database.")

Solution 2 [Using the eval() function]

Not recommended.

This is perfectly possible, with the eval function. However, you should be aware that this is a quite dangerous function to run, as malicious users can use this to control the console. (Especially if you imported os.) However, it should get you over the hump for now. Here's the code:

a = "Alpha"
b = "Bravo"
c = "Charlie"
fl = input("Please enter your first name: ")
try:
    compared = eval(fl[0])
except NameError:
    print("Your first name's first letter does not match any strings in the database.")

More information on the eval() function here: https://docs.python.org/3/library/functions.html#eval

Hope this helped!

Comments