-2

I am trying to write a code that asks a user to enter a digit. If the entered digit matches the other digit (say, some stored number), then whatever message is printed. If it doesn't, then the user should try to enter a digit again. If I put 'input' function and assign it to a variable at the beginning of a while loop, the loop works perfectly. Now, if I use the input function outside the while loop and rather reference it by using another variable, my loop crashes and prints "please, try again" infinitely when the entered digit doesn't match the stored digit.

a = 3
b = input('enter a digit: ')
while True:
   c = b
   if a == c:
      print('good')
   else:
      print('please, try again')

If I enter 4, the program prints "please, try again" infinitely.

My questions: 1) Why? 2) What can I do to make it work because I don't want to use input function in the while loop (my homework requires so)?

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
joker4171
  • 31
  • 3

1 Answers1

0

The issue is that you're assuming b contains the functionality

input('enter a digit: ')

but really it is just contains the output of the initial input call. So you are asking for input once at the beginning and then checking that entered digit infinitely even though it doesn't change.

also input outputs a string type so even if the user entered 3 the check would go

3 == '3'; false

you'll want something like

a = 3
while True:
   c = int(input('enter a digit: '))
   if a == c:
      print('good')
      break
   else:
      print('please, try again')