Why is this code returning multiple outputs The code
a = ["w", "u", "i", "r"]
count = 0
d = input("choose: ")
for c in a:
count = 1
if d == c:
print(count)
else:
print("wrong")
If I choose a string tha satisfies this condition "d==c", it returns the position of the string plus "wrong" three times,
If I choose a string doesn't satisfy the condition, it outputs wrong four times.
If I don't include the else part, it outputs only just the position of the string only once.
Please whats wrong with the code, as I need to include the else part
CodePudding user response:
If what you are trying to do is find the index of an element in a list use the .index
method:
a = ["w", "u", "i", "r"]
print(a.index("u")) -> 1
It returns an error if the element is not on list, you can overcome that by using a try-except
or checking if the element is in the list:
i = input("choose: ")
if i in a:
print(a.index(i))
else:
print("wrong")
or
try:
print(a.index(i))
except ValueError:
print("wrong")
CodePudding user response:
If I choose a string that satisfies this condition "d==c", it returns the position of the string plus "wrong" three times,
Is this what you're trying to do?
a = ["w", "u", "i", "r"]
d = input("choose: ")
for index, c in enumerate(a):
if d == c:
print(f"At index {index}")
else:
print("wrong")
Output :
>>> choose: i
wrong
wrong
At index 2
wrong
CodePudding user response:
Your logic is all good, but we need a small modification here, as you know when the value of d==c it will print the index, if we need to stop just right there so how about if we simply increment out count and if it's found then stop the loop, Please try:
a = ["w", "u", "i", "r"]
count = 0
d = input("choose: ")
for c in a:
if d == c:
print(count)
break
count = 1
else:
print("wrong")
This will print the index if d is found in list a else it will print "wrong"
CodePudding user response:
I think what you want to do is break
when the match is found, and unindent the else
:
a = "wuir"
count = 0
for c in a:
count = 1
if d == c:
print(count)
break
else:
print("wrong")
Unindenting the else
makes it part of the for
statement, not the if
. This means that it will be executed only if the entire for
loop finishes without a break
-- which means you'll only get the "wrong"
output at the very end of the loop if the d == c
condition was never met.
Result:
choose: i
3
choose: f
wrong