Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 4.5 (102) Python code by Ken Adams
- # Three methods for searching a list while, for and enumerate
- ################################## using a while loop #################################33
- sequenceW = ['A','B','C','D']
- print("sequenceW")
- print(sequenceW)
- value_wantedW = "B"
- print("Find " + value_wantedW)
- def position_while(value_searched, sequenceW):
- print("This is the while function")
- position = 0 # start at he first item on the list
- while position < len(sequenceW): # the while stops when all the list is checked
- if sequenceW[position] == value_searched: # if the value is found
- return position # its position is returned, the return statement closes the function
- position += 1 # if we dont find the value we move on to the next item on the list
- print(str(value_searched) + " is not on the list")# if the while gets to the end the item is not on the list
- return None # the function will return none and close
- the_place= position_while(value_wantedW,sequenceW)
- print(value_wantedW +" is at position " + str(the_place))
- ####################################
- print("\n")
- sequenceF = ['A','B','C','D']
- print("sequenceF")
- print(sequenceF)
- value_wantedF = "H"
- print("Find " + value_wantedF)
- #Example 2 - A for loop over a range; similar code to while
- def position_for(value_searched, sequenceF):
- print("This uses a for loop")
- for position in range(len(sequenceF)):
- if sequenceF[position] == value_searched: # if the value is found
- return position
- print(str(value_searched) + " is not on the list")
- return None
- the_placeF= position_for(value_wantedF,sequenceF)
- print(value_wantedF +" is at position " + str(the_placeF))
- ################################################## using enumerate
- print("\n")
- sequenceE = ['A','B','C','D']
- print("sequenceE")
- print(sequenceE)
- value_wantedE = "D"
- print("Find " + value_wantedE)
- #Example 3 - The enumerate function; similar code to while
- def position_emum(value_searched, sequenceE):
- print("This is pyhons own enemerate")
- for position, item in enumerate(sequenceE):
- if sequenceE[position] == value_searched:
- return position
- print(str(value_searched) + " is not on the list")
- return None
- the_placeE= position_emum(value_wantedE,sequenceE)
- print(value_wantedE +" is at position " + str(the_placeE))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement