Naming
I don't like to start out a review with picking on naming, but these variable names are awful:
x=[]
amount=int(input("How many numbers?"))
previous1 = 0
previous2=1
Some renaming ideas:
x
-> numbers
amount
-> count
previous1
, previous2
-> result
(more on this later)
Loop over elements rather than indexes
The index variable i
is unnecessary and not useful:
for i in range(amount):
previous1=x[i]+previous1
Better to iterate directly over the elements:
for num in x:
previous1=x[i]+previous1
Augmented assignment
Note that this:
previous1 = x[i] + previous1
Is equivalent to this (thanks to commutativity with respect to addition):
previous1 = previous1 + x[i]
This latter form can be simplified as:
previous1 += x[i]
Use sum
If you want to add many numbers, you don't need a loop:
previous1 = sum(x)
Strange -
Given numbers \$x_1, x_2, ..., x_n\$, your implementation performs something like \$x_n - (x_{n-1} - (... - (x_2 - x_1))))...)\$ which seems pretty odd. For example if the input is [1, 2, 3, 4]
it performs 4 - (3 - (2 - 1))
which I'm not sure how is useful...
Poor formatting
Please follow PEP8, the Python style guide.
Suggested implementation
It would be good to move the calculation logic to a function,
and separate it from the input reading.
While at it, some doctests would be interesting too.
With the above suggestions applied (and then some more):
def calculate(numbers, operation):
"""
>>> calculate([1, 2, 3, 4], '+')
10
>>> calculate([1, 2, 3, 4], '-')
2
>>> calculate([1, 2, 3, 4], '*')
24
>>> calculate([1, 2, 3, 4], '/')
2.6666666666666665
"""
if operation == "+":
return sum(numbers)
if operation == "*":
result = 1
for num in numbers:
result *= num
return result
if operation == "-":
result = 0
for num in numbers:
result = num - result
return result
if operation == "/":
result = 1
for num in numbers:
result = num / result
return result
raise Exception('Unsupported operator')
def main():
count = int(input("How many numbers?"))
operation = input("(*), (/), (+), (-)")
numbers = [int(input("Number: ")) for _ in range(count)]
print(calculate(numbers, operation))
3 + 4 * 5
, where most people would say that the answer is 23. If you parse continuously you get7*5
equaling35
. So it is good exercise to extend it, but you need to implement some sort of parser to acknowledge the different associativity of operators. \$\endgroup\$eval()
:) \$\endgroup\$