I am getting an ValueError while using for loops

Question:

I was practicing for loops and wanted to create a program which asks user input and then convert it to normal and reverse string. For example:-

Enter a string: python

p n

y o

t h

h t

o y

n p

My code :-

inp = input("Enter a string: ")
for row, col in inp[::-1], inp:
    print(row, col)

The error i am getting when typing "python" is :-

 Traceback (most recent call last):
  File "C:UsersintelDesktopPythontest.py", line 2, in <module>
    for row, col in inp[::-1], inp:
 ValueError: too many values to unpack (expected 2)

When I type "py" then it shows no error:-

y p
p y
Asked By: user11363434

||

Answers:

The way you’ve got it, it isn’t trying to take one element from each list in turn.

You can wrap your lists in a zip and it will do exactly what you want.

inp = input("Enter a string: ")
for row, col in zip(inp[::-1], inp):
    print(row, col)

The reason it works for py is that the string is 2 elements long and you have two variables you assign to (row, col). It would work for pyt if you did for row, col, z in for example because the string is 3 characters and you have 3 variables to assign to, and so on and so forth.

Answered By: PyPingu