简体   繁体   English

如何添加用户在 Python 中输入的一组数字?

[英]How to add a set of numbers that the user inputted in Python?

How do I add numbers in between two numbers the user inputted in Python 2.7.如何在用户在 Python 2.7 中输入的两个数字之间添加数字。 So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers.所以一个人会输入 75 和 80,我希望我的程序在这两个数字之间添加数字。 I am very new to programming and python so any help would be awesome!我对编程和 python 很陌生,所以任何帮助都会很棒!

This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))此示例不包括 75 和 80。如果您需要包含它们,请替换为 print sum(range(n1,n2+1))

n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))

@DSM is right! @DSM 是对的!

n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2

to capture user input use number1 = raw_input('Input number') .捕获用户输入使用number1 = raw_input('Input number') From there I'm not exactly sure what you mean from adding numbers between the two?从那里我不确定你在两者之间添加数字是什么意思? If you want 76+77+78+79 in that example如果你想在那个例子中 76+77+78+79

number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
    result+=n
print result

Here's a quick sample that should handle a few different situations.这是一个可以处理几种不同情况的快速示例。 Didn't go that in-depth since I don't know the scope of the situation.没有深入了解,因为我不知道情况的范围。 Realistically you should do some form of type-checking and loop until valid input is entered.实际上,您应该进行某种形式的类型检查和循环,直到输入有效的输入。 However this should get you started:然而,这应该让你开始:

def sumNums(a, b):
    total = 0
    if a < b:
        total = sum(range(a+1, b))
    elif b < a:
        total = sum(range(b+1, a))  
    return total

num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)

However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.但是,我确信使用列表和 sum() 有更全面的方法,但似乎您只需要一个基本的工作示例。

easy you just go很简单,你去吧

def add(x,y):
    if True:
        return add(x, y)
    else:
        return None


add([1,2,3,4][0], [1,2,3,4][2]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM