3.1.6.8 Lists - more details
Lists - some simple programs
Now let's find the location of a given element inside a list:
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
toFind = 5
found = False
for i in range(len(myList)):
found = myList[i] == toFind
if found:
break
if found:
print("Element found at index", i)
else:
print("absent")
Note:
- the target value is stored in the
toFindvariable; - the current status of the search is stored in the
foundvariable (True/False) - when
foundbecomesTrue, theforloop is exited.
Let's assume that you've chosen the following numbers in the lottery:
3, 7, 11, 42, 34, 49.
The numbers that have been drawn are:
5, 11, 9, 42, 3, 49.
The question is: how many numbers have you hit?
The program will give you the answer:
drawn = [5, 11, 9, 42, 3, 49]
bets = [3, 7, 11, 42, 34, 49]
hits = 0
for number in bets:
if number in drawn:
hits += 1
print(hits)
Note:
- the
drawnlist stores all the drawn numbers; - the
betslist stores your bets; - the
hitsvariable counts your hits.
The program output is:
4.
Comments
Post a Comment