gpt4 book ai didi

python - 如何在 Python 中将多个输入添加到一起

转载 作者:太空宇宙 更新时间:2023-11-03 18:18:22 24 4
gpt4 key购买 nike

我想重复输入“g 1 2 3”之类的内容,并在每次输入时将数字添加到变量中。我做了一个测试程序,但是输出是错误的,例如如果我输入“g 1 2 3”3次,我希望我的变量打印“3”,但它打印“0”。我的代码有什么问题吗?

AddTot = int(0)
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
NameMSplit = NameMarks.split()
while NameMarks != 'Q':
Name1 = int(NameMSplit[1])
Name2 = int(NameMSplit[2])
Name3 = int(NameMSplit[3])
AddTot + Name1
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
print(AddTot)

最佳答案

AddTot + Name1 不会修改AddTot,因为结果不会存储在任何地方。替换为

AddTot += Name1 # same as `AddTot = AddTot + Name1`

也就是说,您的程序仅使用第一个输入。要解决此问题,请在循环体内移动 NameMSplit = NameMarks.split():

AddTot = int(0)
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
while NameMarks != 'Q':
NameMSplit = NameMarks.split() # here
Name1 = int(NameMSplit[1])
Name2 = int(NameMSplit[2])
Name3 = int(NameMSplit[3])
AddTot += Name1
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
print(AddTot)

至于进一步改进,您可以稍微缩短代码:

AddTot = 0 # or int() without argument
say = "Please input your name followed by your marks seperated by spaces "
NameMarks = input(say)
while NameMarks != 'Q':
marks = [int(x) for x in NameMarks.split()[1:]]
AddTot += marks[0]
NameMarks = input(say)

print(AddTot)

关于python - 如何在 Python 中将多个输入添加到一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com