Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当循环添加两个数字时_Python_While Loop - Fatal编程技术网

Python 当循环添加两个数字时

Python 当循环添加两个数字时,python,while-loop,Python,While Loop,我想写一个非常基本的代码。 添加两个数字,然后添加用户给定的另一个数字,打印结果,请求另一个,添加到上一个结果,打印新结果 我从这个开始: a=int(raw_input('give a number')) b=int(raw_input('give second number')) y=True n=False while input('Continue? (y/n)') != 'n': c = a + b print c b = int(raw_input('give an

我想写一个非常基本的代码。 添加两个数字,然后添加用户给定的另一个数字,打印结果,请求另一个,添加到上一个结果,打印新结果

我从这个开始:

a=int(raw_input('give a number'))
b=int(raw_input('give second number'))
y=True
n=False
while input('Continue? (y/n)') != 'n':
   c = a + b
   print c
   b = int(raw_input('give another number'))
好的,根据你的提示,我有正确的代码。我很感激,但它仍然不起作用。它添加两个数字,打印结果,然后要求另一个添加到结果(现在是确定的),但当你输入另一个时,它添加到a,然后打印。 也许你知道怎么了


当我输入“n”时,它并没有结束程序

我会避免使用
input()
代替
raw\u input()
(更安全,并且在Python 3中删除了
input()
)。使用它,您可以通过使用
int()
float()
将输入包装成数字。那么你有两种可能:

永远循环,如果在转换过程中出现错误,则结束循环:

...
while True:
    try:
        b = int(raw_input('give another number ("x" to exit)'))
    except ValueError:
        break
    ...
或者,如果看到某个sentinel值,请将其打断,例如0(该值的计算结果为false)


在大多数编程语言(包括Python)中,条件的计算结果必须为true或false。在这种情况下,字符串
“条件”
将始终计算为true,因为只有空字符串计算为false。要想退出
while
循环,必须首先确定中断循环所需的条件。与

while condition: pass
condition
可以是
if
语句,也可以是可简化为
True
False
的对象。大多数对象,如列表、元组和字符串,在不为空时计算为
True
,在为空时计算为
False
。另一个常见情况是两个值之间的比较;比如

1 < 2

您可以检查的最简单条件是EOF(文件结束)。这将是当用户不键入数字,而只是键入回车时

由您来告诉用户如何结束程序。因此,你还必须给他们写一份说明,例如:

b=input('give another number or type <enter> to end')
b=input('给结尾另一个数字或类型')
我也是初学者。我知道这个解决方案过于简单,但它是有效的

a=int(raw_input('Give a number'))

while True:
    print a
    userIn = (raw_input('Give another number or <cr> to end)'))
    if not userIn:
       break
    b = int(userIn)
    a = a + b
a=int(原始输入('Give a number'))
尽管如此:
打印
userIn=(原始输入('给出另一个数字或结束))
如果不是userIn:
打破
b=int(userIn)
a=a+b

请用文字告诉我们您希望的停止条件。非整数(例如字母“x”)?完全没有输入(用户只需点击回车)
而输入('Continue?(y/n)!='n':
如果
print d
打印出您希望它打印的内容,看起来您正在使用Python2.x,应该查看它,应该询问用户是否要停止,然后输入“end”应该结束program@wiedzminYo然后,您可以这样请求用户输入:
while input('请输入“end”退出)
,这与上面@C.B.的评论类似,感谢您对原始输入的建议。但有一个问题,在我尝试了你的方法之后,它不是加和a+b,而是像a=3 b=2打印c=32那样打印ab,我不明白why@wiedzminYo
原始输入
获取字符串。您需要使用
int
float
将它们转换为数字。
b=input('give another number or type <enter> to end')
a=int(raw_input('Give a number'))

while True:
    print a
    userIn = (raw_input('Give another number or <cr> to end)'))
    if not userIn:
       break
    b = int(userIn)
    a = a + b