ในโปรแกรมนี้ เราจะมาดูวิธีการทำงานฟังก์ชันเครื่องคิดเลขพื้นฐานของเครื่องคิดเลขให้สำเร็จโดยใช้โปรแกรม python ที่นี่ เราสร้างฟังก์ชันแต่ละรายการเพื่อดำเนินการคำนวณและส่งคืนผลลัพธ์ นอกจากนี้ยังยอมรับการป้อนข้อมูลของผู้ใช้พร้อมกับตัวเลือกโอเปอเรเตอร์
ตัวอย่าง
# This function performs additiion
def add(a, b):
return a + b
# This function performs subtraction
def subtract(a, b):
return a - b
# This function performs multiplication
def multiply(a, b):
return a * b
# This function performs division
def divide(a, b):
return a / b
print("Select an operation.")
print("+")
print("-")
print("*")
print("/")
# User input
choice = input("Enter operator to use:")
A = int(input("Enter first number: "))
B = int(input("Enter second number: "))
if choice == '+':
print(A,"+",B,"=", add(A,B))
elif choice == '-':
print(A,"-",B,"=", subtract(A,B))
elif choice == '*':
print(A,"*",B,"=", multiply(A,B))
elif choice == '/':
print(A,"/",B,"=", divide(A,B))
else:
print("Invalid input") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Select an operation. + - * / Enter operator to use: - Enter first number: 34 Enter second number: 20 34 - 20 = 14