Skip to content

Instantly share code, notes, and snippets.

@xv
Created March 27, 2018 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xv/e8b059d886d0e71e69742eaede0d3a33 to your computer and use it in GitHub Desktop.
Save xv/e8b059d886d0e71e69742eaede0d3a33 to your computer and use it in GitHub Desktop.
The good ol' guess the secret number game done in Python.
import random
rand = random.randint(1000, 9999)
attempts = 0
# print rand
def check_proximity(num, guess):
"""
:param str num: The generated random integer casted as a string.
:param str guess: The user input, casted as a string.
"""
black, white = 0, 0
for i in range(len(num)):
for j in range(len(guess)):
if guess[i] == num[j]:
if i == j:
black += 1
elif guess[j] == num[j]: # if rand has repetition like 4660
white == white
else:
white += 1
print "%d black, %d white" % (black, white)
while True:
try:
user_input = int(raw_input("Enter a 4-digit guess: "))
attempts += 1
except ValueError:
print("Only numbers are allowed as input!")
continue
if user_input == int(rand):
print "Your guess '%s' is corrrect! Attempts: %d" % (rand, attempts)
break
elif not 1000 <= user_input <= 9999:
print("The range must be between 1000 and 9999. Try {}"
.format("lower" if user_input > 9999 else "higher"))
else:
# Cast int to str so that indices can be used to check the digit
check_proximity(str(rand), str(user_input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment