在Python中减去2个以上的数字

pjngdqdw  于 2022-11-27  发布在  Python
关注(0)|答案(3)|浏览(167)

我对编程有点陌生。我正在学习Python,版本3. 6。

print("1.+ \n2.-\n3.*\n4./")
choice = int(input())
if choice == 1:
    sum = 0
    print("How many numbers you want to sum?")
    numb = int(input())
    for i in range(numb):
        a = int(input(str(i+1)+". number "))
        sum+=a
    print("Result : "+str(sum))

为了提高我自己,我试图建立一个计算器,但首先我问多少数字用户想要计算。你可以看到这在代码上面,但当谈到减或除或乘我不知道该怎么做。
我这样做的原因是我想做的计算器一样,在真实的计算器。

tsm1rwdh

tsm1rwdh1#

Python有-=*=/=运算符,它们的工作方式和你已经在使用的+=一样。

w6lpcovy

w6lpcovy2#

您也可以使用 * args或 * kargs来减去两个以上的数字。如果您在函数中定义了 * args关键字,那么它将帮助您获取所需数量的变量。

vnjpjtjt

vnjpjtjt3#

有两种方法可以解决这个问题:

方法-1

使用减法逻辑a-b-c-...=((a-b)-c)-...

def subt1(*numbers):     # defining a function subt1 and using a non-keyword argument *numbers so that variable number of arguments can be provided by user. All these arguments will be stored as a tuple.

    try:                     # using try-except to handle the errors. If numbers are given as arguments, then the statements in the try block will get executed.

        diff = numbers[0]    # assigning the first element/number to the variable diff

        for i in range(1,len(numbers)):     # iterating through all the given elements/ numbers of a tuple using a for loop
            diff = diff - numbers[i]        # performing the subtraction operation for multiple numbers from left to right, for eg, a-b-c = (a-b)-c
        return diff                         # returning the final value of the above operation

    except:                                 # if no arguments OR more than one non-numbers are passed, then the statement in the except block will get executed
        return 'please enter numbers as arguments'

subt 1(10,5,-7,9,-1)----〉这里subt 1执行10-5-(-7)-9-(-1)并返回值
4
subt 1(25.5,50.0,-100.25,75)----〉这里subt 1执行25.5-50.0-(-100.25)-75并返回值
0.75
subt 1(20 j,10,-50+100j,150 j)----〉这里subt 1执行20 j-10-(-50+100j)-150j并返回值
(40-230j)
subt 1()----〉这里,except块中的语句被返回,因为没有输入被传递
'请输入数字作为参数'
subt 1('e',1,2.0,3 j)---〉此处except块中的语句返回为传递的字符串'e',该字符串不是数字
'请输入数字作为参数'

方法-2

使用减法逻辑a-b-c-...= a-(b+c+...)= a-加法(b,c,...)

def subt2(*numbers):

    try:
        add = 0       # initializing a variable add with 0

        for i in range(1,len(numbers)):
            add = add+ numbers[i]       # performing the addition operation for the numbers starting from the index 1
        return numbers[0]-add            # returning the final value of subtraction of given numbers, logic : a-b-c = a-(b+c) = a-add(b,c)

    except:
        return 'please enter numbers as arguments'

subt 2(10,5,-7,9,-1)----〉这里subt 2执行10-5-(-7)-9-(-1)并返回值
4
subt 2(25.5,50.0,-100.25,75)----〉此处subt 2执行25.5-50.0-(-100.25)-75并返回值
0.75
subt 2(20 j,10,-50+100j,150 j)----〉这里subt 2执行20 j-10-(-50+100j)-150j并返回值
(40-230j)
注:以上所有测试用例均已在Jupyter笔记本电脑中进行了测试。

相关问题