When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...
Here’s a Java program for a simple calculator.
It performs addition, subtraction, multiplication, and division using switch-case and user input.
๐งฎ Java Program: Simple Calculator
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Display menu
System.out.println("=== Simple Calculator ===");
System.out.print("Enter first number: ");
double num1 = sc.nextDouble();
System.out.print("Enter second number: ");
double num2 = sc.nextDouble();
// Show operation choices
System.out.println("\nChoose an operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.print("Enter your choice (1-4): ");
int choice = sc.nextInt();
double result;
// Perform calculation
switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Result: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Result: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result: " + result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result: " + result);
} else {
System.out.println("Error! Division by zero is not allowed.");
}
break;
default:
System.out.println("Invalid choice! Please select 1–4.");
}
sc.close();
}
}
๐ Explanation
-
Scanner class is used to take input from the user.
-
The user enters two numbers and selects an operation.
-
Switch-case executes the correct arithmetic operation.
-
A check prevents division by zero.
-
Finally, the result is displayed on the console.
✅ Sample Output
=== Simple Calculator ===
Enter first number: 15
Enter second number: 5
Choose an operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice (1-4): 4
Result: 3.0
Comments
Post a Comment