Karthik
Karthik

Reputation: 21

Issue in code to guess random number

I am trying to write a simple python code to guess a random number between 1 and 20. For the incorrect guess, the system shows intended message but for the correct guess it is not giving the proper output.

Could someone help me understand the issue in the below code

import random
import sys
answer=random.randint(1,20)
nt=0
cg=0
while cg!=answer:
 nt=nt+1
 print('Guess the correct number')
 cg=input()
 if cg==answer:
   print('Congrats! You have guessed correctly in'  + str(nt) + ' tries')
   sys.exit()
 print('Guess is incorrect. Please try again. Answer is ' + str(answer) + ' in  ' + str(nt) + ' tries')
 continue

Upvotes: 0

Views: 62

Answers (1)

JkShaw
JkShaw

Reputation: 1947

In cg=input(), input() return type in 'str'. So the condition cg==answer will always be false.

Use:

cg=int(input())

instead of

cg=input()

read more about input() here

Upvotes: 1

Related Questions