5. Calculator
Building a calculator is one of the most obvious choices for any beginner, no matter the programming language you are learning. Building this project you would learn to design a graphical UI with Python and make you familiar with a library like Tkinter, PyQT, Pyforms, and Kivy among others. This library enables you to create buttons to perform different operations and display results on the screen.
You can use separate functions to handle the calculations, and then code the user interface using any GUI module. The Tkinter library, however, is more beginner-friendly.
A simple approach is to define functions for each operation (add, subtract, multiply, divide), which will accept two numbers as parameters. The operations will be performed on those numbers and the result will be returned. Based on the user's input, the decision for the operation function can be made using if/else statements.
1def add(x, y):
2 return x + y
3
4
5def subtract(x, y):
6 return x - y
7
8
9def multiply(x, y):
10 return x * y
11
12
13def divide(x, y):
14 return x / y
15
16
17print("Select operation.")
18print("1.Add")
19print("2.Subtract")
20print("3.Multiply")
21print("4.Divide")
22
23while True:
24 choice = input("Enter choice(1/2/3/4): ")
25 if choice in ("1", "2", "3", "4"):
26 num1 = float(input("Enter first number: "))
27 num2 = float(input("Enter second number: "))
28
29 if choice == "1":
30 print(num1, "+", num2, "=", add(num1, num2))
31 elif choice == "2":
32 print(num1, "-", num2, "=", subtract(num1, num2))
33 elif choice == "3":
34 print(num1, "*", num2, "=", multiply(num1, num2))
35 elif choice == "4":
36 print(num1, "/", num2, "=", divide(num1, num2))
37 next_calculation = input("Let's do next calculation? (yes/no): ")
38 if next_calculation == "no":
39 break
40 else:
41 print("Invalid Input")