Search code examples
pythonpython-3.xinfinite-loopbreak

why Break is not Breaking out of loop for this small piece of code?


List item

# To put values in list till user want
#comparing value entered with the ascii value ofenter
# key , if enter then come out of infinite loop
# why break is not breaking out on enter press
#if value is not enter_key thn put this value in list
x=1
lis=[]
while x == 1 :
    var = str(input())
    if var == chr(10):  
        break                     
    lis.append(var)    

print("i m free now from infinite loop")
print(lis)

Solution

  • If the user presses the enter key without entering anything when prompted by str(input()), then the return value will be an empty string. Thus, you shouldn't be comparing var to chr(10), which is the newline character (\n). Instead try this:

    x=1
    lis=[]
    while x == 1 :
        var = str(input())
        if var == "":            #Compare to an empty string!
            break                     
        lis.append(var)    
    
    print("i m free now from infinite loop")
    print(lis)