简体   繁体   中英

How to fix string out of index range when customizing looping "input()" in python?

I'm experimenting with the input() function. I'm trying to make the code to loop for user input and continue or break the loop based on the user input.

while True:
    line = input("> ")
    if line[0] == "#" :
        continue
    if line == "done" :
        break
    print(line)
print('Done!')

I want to try to make the code to continue loop after an input "#" is written, but I'm having trouble when the user input "" a blank text (string index out of range).

How do I fix this and what if I want the continue to be when user input " #" instead? as in:

while True:
    line = input("> ")
    if line[1] == "#" :
        continue
    if line == "done" :
        break
    print(line)
print('Done!')
while True:
    line = input("> ")
    if line == "#": # removed '[0]'
        continue
    if line == "done":
        break
print(line)        
print('Done!')

I just removed the '[0]' list index, which is not needed as line is just a variable that holds the value of user input

Solved!

Manage to avoid this issue by first checking if index range is met first before indexing.

while True:
    line = input("> ")
    if len(line) == 0 : # check if blank
        print('please input something')
        continue
    if len(line) >= 2 : # check if index is in range
        if line[1] == '#' :
            continue
    if line == "done" :
        break
    print(line)
print('Done!')

I actually want to trigger the condition if the position of '#' are in line[1] or in any line[] like " #HelloWorld" or " # Something". Thanks for the effort to write some method I can use, it helped me a lot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM