Numbers and Arithmetic
Sveip for å vise menyen
12345678910111213141516171819202122232425# Basic arithmetic operations with integers and floats x = 10 # integer y = 3 # integer a = 5.5 # float b = 2.0 # float # Addition sum_result = x + a print('Addition:', sum_result) # 10 + 5.5 # Subtraction sub_result = y - b print('Subtraction:', sub_result) # 3 - 2.0 # Multiplication mul_result = x * y print('Multiplication:', mul_result) # 10 * 3 # Division div_result = x / y print('Division:', div_result) # 10 / 3 # Exponentiation exp_result = y ** 2 print('Exponentiation:', exp_result) # 3^2
Integers vs. Floats in Python
In Python, integers and floats are two different types of numbers:
-
Integers (
int): These are whole numbers without any decimal point. Examples include-3,0,42, and100000. Integers can be positive, negative, or zero. -
Floats (
float): These are numbers that contain a decimal point. Examples include3.14,0.0,-2.5, and1.0. Floats are used when you need to represent fractional values or perform calculations that require more precision.
Key differences:
-
Integers do not have a decimal part, while floats always have a decimal point (even if the number is a whole number, like
1.0). -
Arithmetic operations involving an integer and a float will usually result in a float, to preserve any decimal information.
-
Example:
a = 5 # integer b = 2.0 # float result = a / b print(result) # Output: 2.5 (float)
Understanding the distinction between these two types is important for writing accurate and efficient Python code.
In Python, using / always performs float division, even if both numbers are integers (e.g., 5 / 2 results in 2.5). If you need integer division (discarding the remainder), use the // operator (e.g., 5 // 2 results in 2). Forgetting this difference can cause unexpected results, especially when working with loops or indexes. Always choose the correct operator for your intended outcome!
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår