如何解决请让我清楚这一点
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 条件并且不打印消息。
请帮我理解。
解决方法
您已将变量命名为 Stored_num
并使用 stored_num
进行比较。 Python 是一种区分大小写的语言,因此它们并不相同。将其中一个更改为另一个,它应该可以正常工作。
您错误地输入了全局变量和函数作用域变量。
数量=0 Stored_num=23
定义 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 开头。 使两个变量名称相同,它将起作用。
,对您的代码进行了一些更改:
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
一些注意事项:
- Python 不共享全局范围变量。如果需要修改在
def
之外定义的变量,则需要使用global
声明它
- Python 是一种区分大小写的语言。 (所以
Stored_num
不等于stored_num
)
与 num1
相关的错误不存在。刚刚将其重命名为 num
。
我想就是这样。 (:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。