Python2:在FOR循环中添加整数

2024-06-26 00:12:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在课堂上做实验,遇到了这个问题:

编写一个程序,使用for语句作为计数循环,将用户输入的整数相加。首先程序询问要加多少个数字。然后程序提示用户输入每个数字。最后打印总和。

我很难回答这个问题,如果有人能帮我那就太好了,谢谢!你知道吗

到目前为止,我已经写了:

    NumOfInt=int(raw_input("How many numbers would you like to add up?")) 
    for i in range(NumOfInt):

Tags: 用户程序forinputraw数字整数语句
2条回答

我想这就是你要问的:

使用for循环编写一个程序,询问用户要加多少个数字。然后,它会问他们这个数量的次数为一个数字,这将被添加到总数。然后打印出来。你知道吗

如果是这样的话,那么我相信您只需要向用户请求这个数量的数字,并以与您的类似的方式编写for循环:

NumOfInt = int(input("How many numbers would you like to add up? : "))
total = 0

for i in range (NumOfInt):
    newnum = int(input("Enter a number! : "))
    total += newnum

print("Your total is: " + str(total))

这将把他们的输入加到总数中,直到他们输入的数字超过NumOfInt:

How many numbers would you like to add up? : 4
Enter a number! : 1
Enter a number! : 2
Enter a number! : 3
Enter a number! : 4
Your total is: 10

我希望这有帮助:)

number = int(raw_input("How many numbers?"))
tot = 0

for x in range(number):
    tot += int(raw_input("Enter next number:"))
print tot

相关问题 更多 >