04 Jan 2022

Posted on:

01 Jan 2022

0

# Resolved:Why "n" gets included in my list for the following code?

lis = []
inp = 0
while inp != "n":
inp = input("enter sequence of nos and type n after all digits has been entered \n>>>")
lis.append(inp)
print("Here is the list : ",lis)
print("Here is the tuple : ",tuple(lis))

1 answers ( 1 marked as helpful)
Posted on:

04 Jan 2022

1

Hey Swarntam,

Thank you for your question!

Think about the order of the events in your code. First, `inp = 0`. We check whether `inp != "n"`. It is not, so we enter the `while`-loop. We input a number, say 1, and assign that value to `inp`. In line 5, we append `inp` to the `lis` variable. Next, the program goes back to line 3 and checks whether `inp != "n"`. It is because we've just set it equal to 1. So, we enter the `while`-loop again. Let's type `n` this time, so that `inp = "`n`"`. The next line tells the program to append `"n"` to the `lis` variable. So, we get a list of the form `[1, "n"]`. Again, the program goes back to line 3 and checks whether `inp` is different from `"n"`. It is not because we've just set it equal to `"n"`. So, we don't enter the loop and skip directly to line 6 which prints out the list.

An easy fix to this problem would be to add an `if`-statement before appending `inp` to the list:

``````while inp != "n":
inp = input("enter sequence of nos and type n after all digits has been entered \n>>>")
if inp != "n":
lis.append(inp)
``````

Hope this helps!

Kind regards,
365 Hristina