1
num1=0
Stored_num=23

def input_num():
    num1=int(input('Enter the number again: '))

while num1!=stored_num:
    input_num()
else:
    print('Congrats ! The entered number mathched the stored number')

The code above is not accepting the else condition and not printing the message despite entering the stored value i.e. 23.

Please help me understand.

3 Answers3

1

You have named the variable Stored_num and are using stored_num to compare. Python is a case sensitive language so these are not the same. Change one of them to the other and it should work fine.

mushahidq
  • 96
  • 4
  • @ mushahidq, Thank you, Sir, for your answer. I tried the same but the output was not as expected without the global scope variable in function. Thank you very much for your answer. – Rajan Deshmukh Feb 26 '21 at 07:13
0

You have miss-typed the global variable and function scope variable.

num=0 Stored_num=23

def input_num(): num1=int(input('Enter the number again: '))

while num1!=stored_num:
    input_num()
else:
    print('Congrats ! The entered number mathched the stored number')

See, var Stored_num = 23 starts with capitals S, and inside stored_num start with small s. Make both the variable name the same and it will work.

RAHUL MAURYA
  • 128
  • 8
  • @ Rahul Maurya, Thank you, Sir, for your answer. I tried the same but the output was not as expected without the global scope variable in function. Thank you very much for your answer. – Rajan Deshmukh Feb 26 '21 at 07:13
0

Made few changes to your code:

num=0
Stored_num=23

def input_num():
    global num
    num=int(input('Enter the number again: '))

while num!=Stored_num:
    input_num()
else:
    print('Congrats ! The entered number mathched the stored number')

The outcome:

Enter the number again: 10
Enter the number again: 5
Enter the number again: 23
Congrats ! The entered number mathched the stored number

Process finished with exit code 0

Few notes:

  1. Python does not share the global scope variables. If you need to modify a variable defined outside of a def, you will need to announce it by using global
  2. Python is a case-sensitive language. (So Stored_num does not equal stored_num)

There was an error relating to num1 that didn't exist. Just renamed it to num.

I think that was it. (:

Rikki
  • 3,338
  • 1
  • 22
  • 34
  • 1
    `while does not require else. In fact, that's a wrong syntax.` Nope, it's valid syntax, just like `for-else`. Check this code snippet: https://repl.it/@gurukiran1/InnocentThirdKilobyte – Ch3steR Feb 26 '21 at 05:45
  • Oh I did not know that. Will update the answer. Thank you for pointing that out! (: – Rikki Feb 26 '21 at 05:47
  • @Rikki, Thank you very much, sir. Note 1 regarding global scope variables is really insightful from your detailed answer. I was unaware of it earlier. Thanks a lot, again. – Rajan Deshmukh Feb 26 '21 at 07:09