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')

尽管输入了存储的值,即 23,但上面的代码不接受 else 条件并且不打印消息。

请帮我理解。

4

3 回答 3

1

您已命名变量Stored_numstored_num用于比较。Python 是一种区分大小写的语言,因此它们并不相同。将其中一个更改为另一个,它应该可以正常工作。

于 2021-02-26T05:26:00.857 回答
0

对您的代码进行了一些更改:

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')

结果:

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

几点注意事项:

  1. Python 不共享全局范围变量。如果您需要修改在 a 之外定义的变量def,则需要使用global
  2. Python 是一种区分大小写的语言。(所以Stored_num不等于stored_num

有一个与此相关的错误num1不存在。只是将其重命名为num.

我想就是这样。(:

于 2021-02-26T05:30:35.500 回答
0

您输入错误的全局变量和函数范围变量。

num=0 存储的_num=23

def input_num(): num1=int(input('再次输入数字:'))

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

看,var Stored_num = 23 以大写 S 开头,而在 stored_num 内部以小 s 开头。使两个变量名称相同,它将起作用。

于 2021-02-26T05:27:44.990 回答