I have a question for Python if Moon.

Asked 2 years ago, Updated 2 years ago, 95 views

a=input('Enter multiple numbers:')
a=list(a)

try:
if a.index('%') :
del a[a.index('%')]

elif  a.index(' ') :                  
   del a[a.index(' ')]

except :
pass

for i in range(len(a)) :
print('\u2665' * 2*int(a.pop(0)))

= It's a simple heart program I don't understand the error. The if part is executed, but the elif part is not executed and causes an error.

I wonder if the chord is weird. It works well when I hit it one by one. I have no idea. I ask for your help me.

if문 elseif

2022-09-21 19:29

1 Answers

When registering a question, it is recommended to register the OS information and PYTHON version.

In addition, when presenting a source, it is necessary to specify what the source intends (purpose, etc.) so that the viewer can quickly understand it.

First of all, the reason why it doesn't work the way you want it is because you are not familiar with how to use the index method of the list.

The index returns the location in the list if the item exists, but an exception occurs if it does not exist.

try:                                      
    if a.index('%'):                      
       del a[a.index('%')]
    elif a.index(' '):                  
       del a[a.index(' ')]
except:                                  
    pass

If you put 1 space, 2 spaces, 3 spaces, and 3 spaces in the input...

a.index('%') does not have '%', so it will be excluded.

Of course elif does not work.

If index(''), returns only the location of the first found item.

This means that there are two spaces, but only one item is deleted.

To express what the questioner is trying to do, simply delete the blank or '%'.

In [17]: args = input()
1%2 3 4

In [18]: argsList = list(args)

In [19]: argsList
Out[19]: ['1', '%', '2', ' ', '3', ' ', '4']

In [20]: list(''.join(argsList).replace('%', '').replace(' ', ''))
Out[20]: ['1', '2', '3', '4']


2022-09-21 19:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.