简体   繁体   中英

How to print out a statement only once in loop

I've got a problem: I've got a sequence of numbers and a number n. I need to write a programm that should output all positions of n in the numerical sequence. In case if n is not in the sequence, print the line "not found". Actually, I have an issue with this "not found". It's needed to be printed out only onece, but it prints out several times. How can I fix it?

line = input()
n = input()
line = line.split()
pos_list = []
x = 0
for j in range(len(line)):
        pos_list.append(j)
#print(pos_list)
for i in line:
    if i == n:
        print(line.index(n, x))
    else:
        print("not found")
    x = x + 1

For example for line = 3 5 3 6 4, n = 7 I've got:

not found
not found
not found
not found
not found

If I use break after print("not found") it always prints not found even n is in the sequence

Try to "remember" if n was found. If not print "not found" once after the loop is done:

line = input()
n = input()
line = line.split()
pos_list = []
x = 0
found = False
for j in range(len(line)):
        pos_list.append(j)
#print(pos_list)
for i in line:
    if i == n:
        print(line.index(n, x))
        found = True
    x = x + 1
if not found:
    print("not found")

You can put this code it works fine:

line = input()
n = input()
line = line.split()
pos_list = []
x = 0
for j in range(len(line)):
        pos_list.append(j)
#print(pos_list)

flag =0
for i in line:
    if i == n:
        flag=1
        print(line.index(n, x))
    x = x + 1

if (flag==0):
    print("not found")

but if you want to find substrings, then you this code doesn't works. You are saperating line string into array of strings by dividing line through spaces: Example:

line="hello worldhello helloYou"
n="hello"

so here hello is at location 0 not on 11, 17 position. Because you are not considering substring

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