In: Computer Science
Create a Guess the Number game.
Answer:
Here is the python code as per your requirement
Raw code:
#Code to generate secret number with four unique digits
import random
#user to ask if he want's to paly again after 10
tryAgain='Y'
#While loop
while (tryAgain!='N'):
#digits
digts='0123456789'
#secret string
secret=''
#iterating while loop till the string legth is 4
while(len(secret)<4):
#get the random number from digts string
num=random.choice(digts)
#if that digt is already in secret string don't do anything
if num in secret:
continue
#or else concatnate the string to secret
else:
secret=secret+num
#count initialized to 0
count=0
#to give chances 10 attempts
while(count<10):
#declaring variables to conoutn right postions at right index and right values and not right indexes
right_pos_num_count=0
right_num_nopos_count=0
#asking the user to enter guess
guess=input("Guess: ")
#iterate over the guess
for i in range(len(guess)):
#iterate over the secretn
for j in range(len(secret)):
#checking the position and index
if i==j and guess[i]==secret[j]:
#if both are same increment the count
right_pos_num_count+=1
#if positions are same and indexes aren't
if guess[i]==secret[j] and i!=j:
right_num_nopos_count+=1
#print the hints
print('Right digit and position: ',right_pos_num_count)
print('Right digit but wrong position: ',
right_num_nopos_count)
#if user guess right
if right_pos_num_count==4:
#print this and break the loop of 10
print('Congratulations you Guessed it right!')
break
#else incremnt the count of attempts
else:
count+=1
#ask the user if he wants to play again
tryAgain=input('wants to continue playing? (Y | N): ').upper()
Editor:
output:
Hope this helps you! If you still have any doubts or queries please feel free to comment in the comment section.
"Please refer to the screenshot of the code to understand the indentation of the code".
Thank you! Do upvote.