pythonstringlistaugmented-assignment

Adding a string to a list adds each character separately


function = input('Enter function')
a = input('do you want to enter another function')
b = [function]
if a.lower() == 'yes':
    while True:
        function1 = input('Next Function')
        b += function1
        if function1 == 'quit':
            break

print(b)

in this code if I input in function1: y = 9x + 1; it will put the values in the array, but in the format: 'y', ' ', '9x', ' ', '+', ' ', '1'. how do save the input as y = 9x + 1'? Also when I write quit, it prints the array, but the final value is q','u','i','t'. How do I eliminate those values?


Solution

  • For your first request you can simply use .append() on b to append the element to the list b.

    Code solving first issue:

    b.append(function1)
    

    For your second request you could simply check if quit was typed before appending element to b

    Code solving second issue:

    while True:
        function1 = input('Next Function: ')
        if function1 == 'quit':
            break
        b.append(function1)
    

    Final Code:

    function = input('Enter function: ')
    a = input('Do you want to enter another function: ')
    b = [function]
    if a.lower() == 'yes':
        while True:
            function1 = input('Next Function: ')
            if function1 == 'quit':
                break
            b.append(function1)
    
    
    print(b)