Home > Mobile >  How do I make python recognise spam as a list and not a string
How do I make python recognise spam as a list and not a string

Time:05-11

I am trying to get my program to take a user inputted list and use it as an argument for the stringList function but it keeps thinking that the list is just a string. How do I get it to see it as an actual list?

Here is the code that I have so far:


spam = ["apples", "bananas", "tofu", "cats"]
sillyList = []

def stringList(list):
    ending = len(list)
    
    try:
        print()
        for item in list[0: ending - 1]:
            print(item, end=", ")
        print("and "   list[ending - 1])

    except:
        print("Error: List contains no items. Do you wish to try again?")
        answer = input().lower()
        if answer == "yes" or "y":
            print()
            askListName()
        elif answer == "no" or "n":
            sys.exit()

def askListName():
    print("Enter the list name:")
    listName = input()

    try:
        stringList(listName)
    except:
        print("Error: Invalid list name.")

askListName()

CodePudding user response:

If the input is seperated by spaces or looks like this:

'apples oranges kiwi'

listName = input()
fruit = listName.split()
stringList(fruit)

if the input is seperated by commas or looks like this:

'apples,oranges,kiwi'

listName = input()
fruit = listName.split(',')
stringList(fruit)

the string.split method seperates a string by the the argument you provide. So .split('|') would seperate the input string by '|' character. If you leave out the argument, it defaults to splitting the string by whitespace.

CodePudding user response:

Variable names are hardcoded in the program - part of the Python file. Values typed by the user at runtime in "input", or read from a data file when the program is running, are "data".

These two are two very different things, and you should work your learning way to learn their difference.

For now: Python is one of the few languages that allow both "variable names" and "data" to "bridge": there is a special data structure that is a dictionary, and Python use those to hold the variable names. The "globals()" call will return a dictionary that holds all global variables in your program, so the spam list can be retrieved if you grab it from there. Just change this line:

stringList(listName)

to

stringList(globals()[listName])

And your program will get past the point you are stuck. (I did not check for further errors, though)

In the future, if you want user input interacting with names typed in your program, it is advisable to put this data in a separate, explicitly created dictionary - like in : mydata = {"spam": ["apple", ...], "sillyList": [...]} , then all user input must be one of mydata keys, and can't break your program.

Also, there are other points there: you should not be using sys.exit inside a function: just return from it, and eventually allow your code execution to "fall off" the bottom of your main file. Also, avoid using common Python built-ins as variable names: that is confusing for your readers, and may block you from using those constructs. In this case, inside yourfunction you use "list". Prefer "lst", "sequence", "list_" or similar, in order not to shadow Python's own "list".

  • Related