1

I would like to know how to get a list related action out of user input. This would be my "solution" but it doesn´t work and just gives me back the user´s input.

oldList = ['1', '2']
newList = input('Which number should be included in the List?')
if newList == 1:
    oldList.append(1)
elif newList == 2:
    oldList.append(2)

print(oldList)

Thanks in advance!

Leo
  • 11
  • 2

3 Answers3

1

The input by default will be in string format. So when you read input in newList, its value is : '1'. So the below code would work.

oldList = ['1', '2']
newList = input('Which number should be included in the List?') 
if newList == '1':     # and not 1
    oldList.append(1)
elif newList == '2':
    oldList.append(2)

print(oldList)

Input : 1

Output :

Which number should be included in the List?
['1', '2', 1]

You could instead also try keeping your same comparison and just converting newList into int. That would work as well.


NOTE : The above code will append an integer to oldList. So, if you want to append string , you should change the code to oldList.append(str(1)).

One more thing, if you just want to append a number which user inputs, you can use this -

Short-hand Version :

oldList = ['1', '2']
oldList.append(int(input('Which number should be included in the List?')))
print(oldList)
Community
  • 1
  • 1
Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
0
oldList = ['1', '2']
newList = str(input('Which number should be included in the List?'))
if newList == str(1):
    oldList.append(str(1))
elif newList == str(2):
    oldList.append(str(2))

print(oldList)
kieron
  • 332
  • 3
  • 19
  • 1
    Can you provide an explanation of why `str()` is necessary here? Remember, the goal of Stack Overflow isn't just to _show_ people the right answer, but help them _understand_ it. Take a look at @Abhishek's answer—it's an excellent example of how to address these types of questions. – Jeremy Caney Jun 13 '20 at 01:19
0

The input function returns string variables, not numbers so instead of this:

if newList==1:
 oldList.append(1)

use:

if newList=='1':
 oldList.append('1')

However, your code would be cleaner if you directly appended the input like this:

oldList.append(input('Which number should be included in the List?'))

-Edit: if you want to make sure that you are only storing numbers you could use the following code as well:

try:
 oldList.append(int(input('Which number should be included in the List?'))
except:
 print("That wasn't a number!")
Asriel
  • 182
  • 9