Basic Python Tutorial

Introduction

In this tutorial, we will learn how to write a simple Python program that takes user input, performs a calculation, and displays the output.

Step 1: Create a Python File

Open your text editor or IDE and create a new Python file. You can name it calculator.py.

Step 2: Write the Code

In your calculator.py file, write the following code:


# Simple Python Calculator
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Division by zero"
    return a / b
        

This code defines four functions: add(), subtract(), multiply(), and divide().

Step 3: Take User Input

Next, we will add code to ask the user for two numbers and perform a calculation:


# Take user input
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Choose operation (add, subtract, multiply, divide): ")

if operation == "add":
    result = add(num1, num2)
elif operation == "subtract":
    result = subtract(num1, num2)
elif operation == "multiply":
    result = multiply(num1, num2)
elif operation == "divide":
    result = divide(num1, num2)
else:
    result = "Invalid operation"
        

Step 4: Display the Output

Finally, we will display the result of the operation:


# Output the result
print("Result:", result)
        

Step 5: Running the Program

Once the code is ready, save the file and run it. You can run the program in your terminal or command prompt by navigating to the directory where the file is saved and typing the following command:

python calculator.py

When prompted, enter two numbers and choose an operation. For example:


Enter first number: 5
Enter second number: 3
Choose operation (add, subtract, multiply, divide): add
Result: 8.0
        

Conclusion

In this tutorial, you learned how to create a basic Python calculator that takes user input, performs a calculation, and displays the result. You can now experiment by adding more operations or improving the user interface!