Created
June 6, 2018 13:38
-
-
Save Marva82/5bbfd6c0698c16b515e34eb03e156776 to your computer and use it in GitHub Desktop.
Python Calculator that accepts multiple inputs from a user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Creating a calculator that gets multiple input from the user | |
from functools import reduce | |
def addition(*args): | |
newList = [] | |
for i in inputList: | |
z = int(i) | |
newList.append(z) | |
NumbersSum = sum(newList) | |
return NumbersSum | |
def subtraction(*args): | |
newList = [] | |
for i in inputList: | |
z = int(i) | |
newList.append(z) | |
NumbersSub = newList[0] - sum(newList[1:]) | |
return NumbersSub | |
def multiplication(*args): | |
newList = [] | |
for i in inputList: | |
z = int(i) | |
newList.append(z) | |
NumbersMult = reduce(lambda x, y: x*y, newList) | |
return NumbersMult | |
def division(*args): | |
newList = [] | |
for i in inputList: | |
z = int(i) | |
newList.append(z) | |
NumbersDiv = reduce(lambda x, y: x/y, newList) | |
return NumbersDiv | |
print("Please enter your choice\n" + | |
"1 -> Addition\n" + | |
"2 -> Subtraction\n" + | |
"3 -> Multiplication\n" + | |
"4 -> Division\n") | |
choice = int(input("Enter your choice: ")) | |
if 1 <= choice <= 4: | |
print("Please enter your values: ") | |
inputList = input().split() | |
#print(inputList) | |
if choice == 1: | |
varList = addition(inputList) | |
print("The sum of your inputs is: ", varList) | |
elif choice == 2: | |
varList = subtraction(inputList) | |
print("The difference of you inputs is: ", varList) | |
elif choice == 3: | |
varList = multiplication(inputList) | |
print("The product of your inputs is: ", varList) | |
elif choice == 4: | |
varList = division(inputList) | |
print("The quotient of your inputs is: ", varList) | |
else: | |
not_valid = "{} is not a valid choice\n".format(choice) | |
print(not_valid) |
can you please explain why inputList was used as range in the for loop instead of the variable newlist itself?
Because, inputList length will return the original length of user's input, whereas newList is empty initially and will lead to errors while appending,
Example: Iteration 1:
newList = []
for i in inputList:
z = int(i)
newList.append(z)
here, initially the size of newList is 0,
for i in newList => will be for i in 0 (in literal terms)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you please explain why inputList was used as range in the for loop instead of the variable newlist itself?