Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.2 Data Types 1 - Integers, Floating-Point Numbers, and Strings
A data type defines the kind of value a variable can hold and what operations can be performed on it.
Integers
Integers are whole numbers without decimal points. They can be positive, negative, or zero.
// Declare an integer In javascript
let age = 25;
console.log("Age: " + age); // Output: Age: 25
# Declare an integer in Python
age = 25
print("Age:", age) # Output: Age: 25
Floating-Point Numbers
Floating-point numbers, or “floats,” represent real numbers that contain a fractional part, expressed with decimals.
// Declare a floating-point number in Javascript
let price = 19.99;
console.log("Price: $" + price); // Output: Price: $19.99
# Declare a floating-point number in Python
price = 19.99
print("Price: $", price) # Output: Price: $ 19.99
Strings
Strings are sequences of characters (letters, numbers, symbols) enclosed in quotes. They are used to represent text
// Declare a string in Javascript
let greeting = "Hello, World!";
console.log(greeting); // Output: Hello, World!
# Declare a string
greeting = "Hello, World!"
print(greeting) # Output: Hello, World!
# Function to perform basic arithmetic operations
def basic_calculator():
# Taking input from the user for the first number
num1 = input("Enter the first number: ")
# Checking if the input is a float or integer
if '.' in num1:
num1 = float(num1)
else:
num1 = int(num1)
# Taking input for the operator (+, -, *, /)
operator = input("Enter an operator (+, -, *, /): ")
# Taking input for the second number
num2 = input("Enter the second number: ")
if '.' in num2:
num2 = float(num2)
else:
num2 = int(num2)
# Performing the chosen operation
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
# Handle division by zero
if num2 == 0:
result = "Error! Division by zero."
else:
result = num1 / num2
else:
result = "Invalid operator!"
# Printing the result
print(f"The result is: {result}")
# Run the calculator function
basic_calculator()