Advertisement
acclivity

pyNumberGuess-version2

Nov 22nd, 2022
751
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. # Script gets a terget number from user-1, then gives user-2 multiple chances to "guess" the number
  2.  
  3. def get_number(prompt):
  4.     # A utility function to get a valid 3-digit number either as target list, or as a guess list
  5.     while True:
  6.         user_input = input(prompt)
  7.         # Check that string input is of length 3, and is all numeric
  8.         if len(user_input) != 3 or not user_input.isdigit():
  9.             print("Enter a 3-digit number\n")
  10.             continue
  11.         if user_input[0] > "0":      # the only other check required is that digit 1 is not zero
  12.             return list(user_input)
  13.         print("Number must be between 100 and 999")
  14.  
  15.  
  16. target_list = get_number("\nEnter a number: ")           # Get target number as a list
  17.  
  18. while True:
  19.     work_list = target_list.copy()        # work_list is a copy of the target number list
  20.     good, close = 0, 0
  21.     guess_list = get_number("\nEnter your guess: ")      # get guess as a list
  22.     for i, n in enumerate(guess_list):       # process each digit in the guess
  23.         if n == work_list[i]:        # does a digit in the guess exist in same position in the target?
  24.             good += 1
  25.             work_list[i] = "x"       # prevent target digit from being counted again
  26.         elif n in work_list:         # does the guess digit exist elsewhere in the target number?
  27.             close += 1
  28.             # find where the near-miss was in the target
  29.             pos = work_list.index(n)
  30.             work_list[pos] = "x"     # prevent target digit from being counted again
  31.     print(f"Correct Place: {good}")
  32.     print(f"Incorrect Place: {close}")
  33.     if good == 3:
  34.         break
  35.  
  36. print("You guessed the number. Congrats!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement