-1

So I'm a total beginner when it comes to Python and the "not" operator is kinda confusing me. So i was watching a BroCode video and he wrote this code:

name = None

while not name:
    name = input("Enter your name: ")
print("Hello, "+name)

My question is: Doesn't this mean; while name is not nothing, do this? Isn't "not" supposed to make things opposite? So by that logic this code is not supposed to work. The condition of the while loop is that the name needs to be something, but it's not, so why does it even execute?

4

2 回答 2

0

在这样的 while 循环中,None将有效地评估为False. 正如您所说,将其not反转,将其转换为True条件,并使循环运行。

所以这里发生的是循环到达,并且由于没有输入,并且 as name = None,条件通过并进入循环体。如果用户输入一个空字符串,下一个循环将再次评估它False并再次运行循环,直到输入一个有效的非空字符串。

所以这是确保输入字符串的简单方法。

于 2021-10-16T20:26:28.150 回答
0

not简单地否定其论点的“真实性”。None空字符串被认为是虚假的,而非空字符串被认为是真实的。

此代码的改进版本将初始化name为空字符串;没有特别的理由关心 和 之间的区别None""什么时候not None只会被评估一次。(input将始终返回 a str,为空或否。)

但更好的版本只会对name.

while True:
    name = input("Enter your name: ")
    if name:
        break

循环保证至少执行一次,所以name一旦循环退出就会被定义。无需在循环之前初始化值。作为额外的奖励,您可以直接测试字符串的真实性,而不是否定的真实性。

于 2021-10-16T20:26:42.333 回答