简体   繁体   中英

Having a number go through 3 numbers in an array

I am currently trying to do an assignment for my programming class and the assignment requires I create a range between 1-10 and input a number in that range. After the input is given the number will be multiplied by the first number in an array of 3 numbers (19, 85, 2). so say I put in the number 2. It would than be multiplied by 19. After the first calculation it will subtract the second element in the array from the total of the first calculation, and after that it will divide the second calculation by the third element in the array. I do not know how to have a number go through separate elements of the same array. Right now I can get the number I input to multiply but it multiplies with all 3 numbers in the array instead of the first.

def multiply( array , n ): 
    unumb = 0
    while 1 > unumb or 10 < unumb:
     try:
         unumb = int(input("Please enter a number (1 - 10) : "))
     except ValueError:
        print ("That wasn't an integer in range")
    for i in range(n): 
        unumb = unumb * array[i] 
    return unumb

  

array = [19, 85, 2] 
n = len(array) 

print(multiply(array, n)) 

Output:

Please enter a number (1 - 10) : 2
6460

Since you're doing a different thing with each element of the array, it doesn't really make sense to iterate over it -- just access the elements with [0] , [1] , and [2] :

while True:
    try:
        x = int(input("Please enter a number from 1 to 10: "))
        if x not in range(1, 11):
            raise ValueError("That wasn't an integer in range")
        break
    except ValueError as e:
        print(e)

a = [19, 85, 2]
print(f"Result: {(x * a[0] - a[1]) / a[2]}")

As you have to do three different calculations you don't need to iterate, also I noticed that you used a function structure, so I wrote something similar to your code.

def multiply(array):

    #Getting the input.
    unumb = int(input("Please insert a number between 1 and 10: "))

    if 1 <= unumb <= 10:

        unumb*=array[0]
        unumb-=array[1]
        #unumb/=array[2] #If you want a float result.
        unumb = int(unumb/array[2]) #If you want a int result.

        return unumb

    else: print("Not a number between 1 and 10.")


array = [19,85,2]
print(multiply(array)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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