我有四个输入语句创建一个简单的计算。我希望用户能够在第一个提示中键入0,以便立即停止程序,但是程序会在用户停止前完成整个循环。如何使程序在键入像0这样的命令后直接停止迭代?在
def main():
input_1 = 1
input_2 = 1
input_3 = 1
input_4 = 1
while input_1 !=0:
input_1 = int(input('Please enter a value or type 0 to end: '))
input_2 = int(input('Please enter a second value: '))
input_3 = int(input('Please enter a third value: '))
input_4 = int(input('Please enter a fourth value: '))
print('The total amount is: ', end='')
print(all_inputs(input_1,input_1,input_1,input_1), end='')
def all_inputs(first,second,third,fourth):
sum = first + second + third + fourth
return(sum)
main()
我不是一个Python用户,但我知道你的问题在哪里。在
输入1、2、3和4的预设值在循环内完成。在
为什么不把输入_1放在循环外,而放在循环内呢。这样一来,只要你运行函数,它就会通过while look check if input_1!=0,如果是,循环将立即终止。在
事实上,既然已经用四个独立的变量收集了4个参数,为什么还需要一个循环呢。你可以这么做
您可以在input_1==0时退出,也可以将输入_1之后的所有内容包装在if中,以便仅在输入_1时执行!=0。在
虽然@FredMan是对的,但我觉得你真的可以整理你的循环。我不是Python人,但我想到的是:
有很多其他的方法来清理这个问题,但我觉得这是一个简单的修复方法,可以让你记住你想要的风格:)
编辑:这里有另一种方法
^{pr2}$相关问题 更多 >
编程相关推荐