Advertisement
kenadams53

Three_ways_to_search_list

Aug 31st, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. # 4.5 (102) Python code by Ken Adams
  2. # Three methods for searching a list while, for and enumerate
  3. ################################## using a while loop #################################33
  4.  
  5. sequenceW = ['A','B','C','D']
  6. print("sequenceW")
  7. print(sequenceW)
  8. value_wantedW = "B"
  9. print("Find " + value_wantedW)
  10. def position_while(value_searched, sequenceW):
  11. print("This is the while function")
  12. position = 0 # start at he first item on the list
  13. while position < len(sequenceW): # the while stops when all the list is checked
  14. if sequenceW[position] == value_searched: # if the value is found
  15. return position # its position is returned, the return statement closes the function
  16. position += 1 # if we dont find the value we move on to the next item on the list
  17. print(str(value_searched) + " is not on the list")# if the while gets to the end the item is not on the list
  18. return None # the function will return none and close
  19.  
  20. the_place= position_while(value_wantedW,sequenceW)
  21. print(value_wantedW +" is at position " + str(the_place))
  22.  
  23. ####################################
  24. print("\n")
  25. sequenceF = ['A','B','C','D']
  26. print("sequenceF")
  27. print(sequenceF)
  28. value_wantedF = "H"
  29. print("Find " + value_wantedF)
  30. #Example 2 - A for loop over a range; similar code to while
  31. def position_for(value_searched, sequenceF):
  32. print("This uses a for loop")
  33. for position in range(len(sequenceF)):
  34. if sequenceF[position] == value_searched: # if the value is found
  35. return position
  36. print(str(value_searched) + " is not on the list")
  37. return None
  38.  
  39. the_placeF= position_for(value_wantedF,sequenceF)
  40. print(value_wantedF +" is at position " + str(the_placeF))
  41.  
  42. ################################################## using enumerate
  43. print("\n")
  44. sequenceE = ['A','B','C','D']
  45. print("sequenceE")
  46. print(sequenceE)
  47. value_wantedE = "D"
  48. print("Find " + value_wantedE)
  49. #Example 3 - The enumerate function; similar code to while
  50.  
  51. def position_emum(value_searched, sequenceE):
  52. print("This is pyhons own enemerate")
  53. for position, item in enumerate(sequenceE):
  54. if sequenceE[position] == value_searched:
  55. return position
  56. print(str(value_searched) + " is not on the list")
  57. return None
  58.  
  59. the_placeE= position_emum(value_wantedE,sequenceE)
  60. print(value_wantedE +" is at position " + str(the_placeE))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement