0

I'm defining a function that creates a list with input values. I have 2 questions:

  1. How to define the list's name (n) from an input?
  2. How to transform numeric items in float type?

n=name of the list from an input

I've tried to assign the list to n, but after running the function, when writing the list name, it gave me a NameError.

About the 2nd issue, I've tried to turn the input into a float, but it didn't work and the list's numeric items were still strings.

def createlist():
    n=input("What's the list's name?"+'\n')
    a=input("Insert the list items"+'\n')
    l=[a]
    while a!='':
        b=input('\n')
        m=[b]
        l=l+m
        a=b
    l=l[:-1]
    print(n,'=',l)
    n=l

createlist()

n='List'

List = ['banana', 'apple', 'peach', '4.33', '56.243']

List

NameError: name 'List' is not defined

I expect output of List to be the created list, but it actually gives me a NameError. When writing a number as item it goes into the list as a string, not an int.

I'd like some help. Thanks.

Wang Liang
  • 4,244
  • 6
  • 22
  • 45
elio_934
  • 1
  • 2
  • [This demo](https://repl.it/repls/NimbleFlamboyantExponent) shows your code running fine on python 3, and [this demo](https://repl.it/repls/MediocreDaringAbstracttype) shows the `NameError` on python 2.7. If you're on a UNIX system, I believe `python my_prog.py` will default to using python 2.7 - try `python3 my_prog.py` instead. – Nick Reed Nov 01 '19 at 14:22
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – snakecharmerb Nov 02 '19 at 10:13

1 Answers1

0
  1. I think you are looking for something like exec.
  2. You can just iterate and try to convert to a float.

exec will actually run your code:

name = input()

so:

name = "LISTNAME" # after user input

exec(name + "=[]")

will create a new variable as a list named LISTNAME

Amir Kedem
  • 68
  • 1
  • 9