I just started learning Python a few days ago and I absolutely love it! OK so I had already built a very rudimentary calculator but I wanted to make it more advanced and simplify it. I know its just a calculator now but I wanted to write and structure it as if it were in a much larger program or algorithm. I'm not done with the last portion of the if statement I know that but I wanted to figure out how I could assign user input to an operators parameters and assign that operator to a variable outside of an if statement, and then assign user input a value and call on that variable inside of the if statement?
import math
import operator
user_num_00 = 0.0
user_num_01 = 0.0
num_ui_list = [" first ", " second ", " base ", " power ", ""]
operator_list = {
"1": operator.mul,
"2": operator.truediv,
"3": operator.add,
"4": operator.sub,
"5": operator.pow,
"6": math.sqrt
}
operation_ui_list = {
"1": " * ",
"2": " / ",
"3": " + ",
"4": " - ",
"5": " to the power of ",
"6": " to the root of "
}
def num_ui(x=num_ui_list[0]):
return "Enter the" + x + "number: "
def num_ui_answer(num_0, y, num_1, z):
num_answer = num_0 + y + num_1 + " = " + z
return num_answer
user_input = input("1. Multiplication\n2. Division\n3. Addition\n4.
Subtraction\n5. Exponent\n6. Root"
"\nChoose an operation: ")
user_operation = operator_list[user_input]
user_operation_answer = user_operation(user_num_00, user_num_01)
operator_string = operation_ui_list[user_input]
if user_input == "1" or user_input == "2" or user_input == "3" or
user_input == "4":
user_num_00 += float(int(input(num_ui())))
user_num_01 += float(int(input(num_ui(num_ui_list[1]))))
print(num_ui_answer(str(user_num_00), operator_string,
str(user_num_01), str(user_operation_answer)))
elif user_input == "5":
user_num_00 = float(int(input(num_ui(num_ui_list[2]))))
user_num_01 = float(int(input(num_ui(num_ui_list[3]))))
elif user_input == "6":
user_num_00 = float(int(input(num_ui(num_ui_list[4]))))
user_num_01 = ""
else:
print("Error")
Aucun commentaire:
Enregistrer un commentaire