【问题标题】:Please give me the clarity on this请让我清楚这一点
【发布时间】:2021-05-28 12:33:58
【问题描述】:
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 条件并且不打印消息。

请帮助我理解。

【问题讨论】:

    标签: python printing output func alloca


    【解决方案1】:

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

    【讨论】:

    • @mushahidq,谢谢您,先生,您的回答。我尝试了相同的方法,但是如果没有函数中的全局范围变量,则输出不如预期。非常感谢您的回答。
    【解决方案2】:

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

    数量=0 Stored_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 开头。 使两个变量名称相同,它将起作用。

    【讨论】:

    • @Rahul Maurya,谢谢您,先生,您的回答。我尝试了相同的方法,但是如果没有函数中的全局范围变量,则输出不如预期。非常感谢您的回答。
    【解决方案3】:

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

    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 不共享全局范围变量。如果您需要修改在def 之外定义的变量,则需要使用global 声明它
    2. Python 是一种区分大小写的语言。 (所以Stored_num 不等于stored_num

    num1 相关的错误不存在。只是将其重命名为num

    我想就是这样。 (:

    【讨论】:

    • while does not require else. In fact, that's a wrong syntax. 不,它是有效的语法,就像for-else。检查此代码 sn-p:repl.it/@gurukiran1/InnocentThirdKilobyte
    • 哦,我不知道。将更新答案。感谢您指出这一点! (:
    • @Rikki,非常感谢,先生。从您的详细回答中,关于全局范围变量的注释 1 确实很有见地。我之前并不知道。非常感谢,再次感谢。
    猜你喜欢
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    相关资源
    最近更新 更多