Python:为什么将条目设置为值1

时间:2018-11-21 06:18:14

标签: python-3.x

我是Python的新手,我想弄清楚为什么下面的代码中entry的值在代码顶部设置为“ 1”,为什么当我按“ 0”测试代码时,第一个也是唯一的数字,当“输入”已经与数字“ 1”绑定在一起时,“和”为“ 0”而不是“ 1”。 另外,entry被称为什么?有功能吗? 最好的问候

entry = 1
total = 0
while entry > 0:
    entry = int(input('Enter a number: '))
    total += entry
print('The sum of all numbers =', total)

4 个答案:

答案 0 :(得分:1)

entry是一个变量。

已将其设置为1以进入while loop。要使while循环运行,您需要将条件设为True。因此,它求值为1 > 0的{​​{1}}并进入循环。

由于True的值在while循环中被覆盖,因此它从用户输入中获取值。 如您所说,如果按0,则entry的值将变为0而不是1,并且将被添加到entry中,该值为0,因此sum将返回0。

您可以将其设置为大于零的任何值。

答案 1 :(得分:1)

这里Entry基本上用作标志,将其设置为True,以便While循环可以连续运行,直到以{{1} } False变量的值,然后我将其停止Entry循环并返回总和。

答案 2 :(得分:0)

entry是可变的。 entry = 1之后为1。因此,第一次进入while循环entry > 0是真实的,您进入循环并读取一个数字,并将其分配给条目。现在,如果输入0,则entry为0,0 + 0为0,因此total为0,而entry > 0为假,因此您脱离了{{ 1}}循环并打印:“所有数字的总和= 0”。

但是但是但是:问题“ 为什么将条目设置为值1”,我无法回答。您必须去问编写此代码的人,然后问:“为什么将条目设置为值1?”然后也许您会得到答案。但是我不能给你答案。

在我看来,出于愚蠢的原因而编写的愚蠢代码。我不知道。

答案 3 :(得分:0)

entry的初始值设置为1,另一方面,您也使用相同的变量获取input。因此,无论何时将0放在变量上,entry变量都将变为0作为初始值。 total已经设置为0,并且将entry值也添加为0,因此结果变为0。 因此,当loop返回并检查其条件entry > 0 becoming 0 > 0为假时。

所以代码执行了这样的操作

  

您编码

entry = 1
total = 0
while entry > 0:
    entry = int(input('Enter a number: '))
    total += entry
print('The sum of all numbers =', total)
  

第一次尝试

entry = 1
total = 0
while entry > 0: # 1 > 0 because entry = 1
    entry = int(input('Enter a number: ')) # entry is becoming 0
    total += entry # total = 0, because entry is 0 now
print('The sum of all numbers =', total)
  

最后一次尝试

entry = 1
total = 0
while entry > 0: # 0 > 0 False because entry = 0
    entry = int(input('Enter a number: '))
    total += entry
print('The sum of all numbers =', total)
  

输出

>>> The sum of all numbers = 0